luxe 0.1.4: remembered models, wheel-driven lists, and a steadier phone app

- luxe starts on the model you last chose in this project, then the last one anywhere. Signing in
  opens the model picker instead of choosing for you.
- Every list in a modal takes the mouse wheel and a draggable scrollbar.
- The phone app shows reasoning in full, stays put while you read back through a long session, and
  shows a question's answer on its card.
- On Windows, luxe update replaces the running luxe, and a signed-in install no longer sees setup
  again.
- The file tree no longer shows "engine busy" in a large project, loop output is easier to follow,
  and the name is written lowercase.

The CHANGELOG has the full list.
This commit is contained in:
Evan Whittaker
2026-10-20 13:51:34 -05:00
parent 6184aa21fb
commit a0666d6c81
591 changed files with 4926 additions and 2942 deletions

View File

@@ -3,12 +3,12 @@ name = "luxe-tui"
version.workspace = true
edition.workspace = true
license.workspace = true
description = "Terminal UI for Luxe, built on ratatui: conversation, guided review, dashboard, and themes"
description = "Terminal UI for luxe, built on ratatui: conversation, guided review, dashboard, and themes"
repository.workspace = true
homepage.workspace = true
[dependencies]
luxe-core = { path = "../luxe-core", version = "0.1.3" }
luxe-core = { path = "../luxe-core", version = "0.1.4" }
# `unstable-rendered-line-info` enables Paragraph::line_count, used for precise wrapping-aware
# mouse hit-testing over word-wrapped surfaces (guide/dock/conversation clicks). It adds no crate;
# the API is marked unstable upstream but is stable within our pinned minor (re-check on upgrade).

View File

@@ -8,7 +8,7 @@ pub(super) fn hex(color: Color) -> Option<String> {
Color::Rgb(red, green, blue) => (red, green, blue),
Color::Indexed(index) => indexed_rgb(index),
Color::Reset => return None,
// The sixteen named colors belong to the terminal's palette. Luxe's own themes are pure
// The sixteen named colors belong to the terminal's palette. luxe's own themes are pure
// RGB, so this is only reached by a user theme; xterm's defaults are the least surprising
// stand-in available.
named => indexed_rgb(named_index(named)?),

View File

@@ -123,7 +123,7 @@ fn block_element(block: &Block, x: f64, y: f64, fill: &str) -> String {
/// Which cell edges a box-drawing glyph reaches, and whether its corner is rounded.
///
/// `(up, right, down, left)`. Only the light set: it is what Luxe draws with, and a heavy or double
/// `(up, right, down, left)`. Only the light set: it is what luxe draws with, and a heavy or double
/// rule would need its own stroke width rather than a flag here.
type Arms = (bool, bool, bool, bool);

View File

@@ -1,6 +1,6 @@
//! fixture_svg — a production render, exported as vector.
//!
//! The site needs pictures of Luxe, and a screenshot is the worst way to get one: it is a raster at
//! The site needs pictures of luxe, and a screenshot is the worst way to get one: it is a raster at
//! somebody's DPI, its text cannot be selected or searched, it weighs ten times what it should, and
//! it puts a terminal and a font in the pipeline where neither belongs. The render is already a
//! grid of glyphs and colors, so it can be drawn directly.

View File

@@ -76,7 +76,7 @@ fn cell_fraction_glyphs_are_drawn_not_typeset() {
for glyph in ['\u{e0b8}', '\u{e0ba}', '\u{e0bc}', '\u{e0be}'] {
assert!(is_drawn(glyph), "U+{:04X} should be geometry", glyph as u32);
}
// Letters and the geometric shapes Luxe uses as marks stay text: any font has them, and
// Letters and the geometric shapes luxe uses as marks stay text: any font has them, and
// they carry meaning that should remain selectable.
for glyph in ['a', '\u{276f}', '\u{25cf}', '\u{25c6}'] {
assert!(!is_drawn(glyph), "U+{:04X} should be typeset", glyph as u32);

View File

@@ -1,7 +1,7 @@
//! shiki_theme — luxe's palette as a syntax theme for the website's code blocks.
//!
//! The docs describe a terminal program; highlighting their code in somebody else's palette is a
//! small lie about what Luxe looks like. This writes a TextMate theme from the same JSON the TUI
//! small lie about what luxe looks like. This writes a TextMate theme from the same JSON the TUI
//! loads, so the code on the page is colored by the product's own tokens.
//!
//! It is also the palette's hardest test. A theme with six accents can hide a weak one behind a
@@ -32,7 +32,7 @@ fn theme_json(name: &str, theme: &HashMap<String, ColorValue>) -> String {
let hex = |token: &str| -> String {
match theme.get(token) {
Some(ColorValue::Rgb(red, green, blue)) => format!("#{red:02x}{green:02x}{blue:02x}"),
// Every token this maps is RGB in Luxe's own themes; anything else would be a theme
// Every token this maps is RGB in luxe's own themes; anything else would be a theme
// this generator was not written for, and inventing a color would hide that.
_ => panic!("{name}.{token} is not an RGB color"),
}

View File

@@ -96,7 +96,7 @@ fn stylesheet(dark: &HashMap<String, ColorValue>) -> String {
out.push_str(":root {\n color-scheme: dark;\n");
out.push_str(&block(dark, true));
// The canvas a baked-in capture sits on. A recording is the terminal's own background in every
// cell Luxe paints, so a plate in any other color turns the painted cells into rectangles; with
// cell luxe paints, so a plate in any other color turns the painted cells into rectangles; with
// one theme on the page these are the page's own colors, named for what they are for.
let _ = writeln!(
out,
@@ -178,7 +178,7 @@ mod tests {
/// Every exported token reaches the stylesheet. A token that resolves to an ANSI index or the
/// terminal default has no hex to give, which is fine in a terminal and useless on a page — so
/// Luxe's own theme must not contain one.
/// luxe's own theme must not contain one.
#[test]
fn every_exported_token_has_a_color() {
let dark = luxe();

View File

@@ -25,7 +25,7 @@ fn main() -> Result<()> {
}
let mut app = seeded_app(&theme, scenario).map_err(anyhow::Error::msg)?;
// `LUXE_FIXTURE_DESKTOP=<name>` paints the frame in an Omarchy theme from this machine, turned
// into Luxe's the way a session following the desktop does, so a theme no built-in matches can
// into luxe's the way a session following the desktop does, so a theme no built-in matches can
// be judged without applying it
if let Ok(name) = env::var("LUXE_FIXTURE_DESKTOP") {
app.theme_styles = desktop_styles(&name)?;
@@ -42,7 +42,7 @@ fn main() -> Result<()> {
}
let scenario_name = scenario.name();
execute!(io::stdout(), SetTitle(format!("Luxe fixture: {scenario_name}")))?;
execute!(io::stdout(), SetTitle(format!("luxe fixture: {scenario_name}")))?;
let mut terminal = terminal::init()?;
let result = run(&mut terminal, &mut app);
terminal::restore()?;
@@ -400,7 +400,7 @@ fn desktop_styles(name: &str) -> Result<luxe_tui::theme::styles::ThemeStyles> {
let desktop = luxe_core::omarchy::DesktopTheme { name: name.to_owned(), dir };
let registry = luxe_core::theme::ThemeRegistry::new().with_desktop(Some(&desktop));
let Some(resolved) = registry.resolve(luxe_core::omarchy::DESKTOP_THEME) else {
bail!("{name} has no colors Luxe can read")
bail!("{name} has no colors luxe can read")
};
Ok(luxe_tui::theme::styles::ThemeStyles::from_resolved(&resolved, name))
}

View File

@@ -84,8 +84,8 @@ fn tile(rows: &[&str], (plate_color, ink): (String, String)) -> String {
format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 {side} {side}\" \
width=\"{side}\" height=\"{side}\" role=\"img\" aria-label=\"Luxe\">\n \
<title>Luxe</title>\n \
width=\"{side}\" height=\"{side}\" role=\"img\" aria-label=\"luxe\">\n \
<title>luxe</title>\n \
<path fill=\"{plate_color}\" d=\"{plate}\"/>\n \
<g transform=\"translate({offset_x:.2} {TILE_PAD}) scale({scale:.4})\">\n \
<path fill=\"{ink}\" d=\"{letter}\"/>\n \
@@ -111,9 +111,9 @@ fn svg(rows: &[&str], letters: std::ops::Range<usize>) -> String {
out.push_str(&format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"{left} 0 {width} {height}\" \
width=\"{width}\" height=\"{height}\" data-cell=\"{CELL_W} {CELL_H}\" \
role=\"img\" aria-label=\"Luxe\">\n"
role=\"img\" aria-label=\"luxe\">\n"
));
out.push_str(" <title>Luxe</title>\n");
out.push_str(" <title>luxe</title>\n");
for (index, path) in paths.iter().enumerate() {
let step = index + letters.start + 1;
out.push_str(&format!(
@@ -293,7 +293,7 @@ mod tests {
assert!(svg.trim_end().ends_with("</svg>"));
assert_eq!(svg.matches("<path").count(), 4, "one path per letter");
assert!(svg.contains("--luxe-wordmark-1"), "letters are themable from CSS");
assert!(svg.contains("aria-label=\"Luxe\""));
assert!(svg.contains("aria-label=\"luxe\""));
assert!(svg.contains("data-cell=\"10 22\""), "the grid the highlight is drawn in");
}

View File

@@ -49,6 +49,7 @@ mod msg;
mod navigation;
mod opener;
mod outbox;
mod overlay_lists;
mod overlays;
mod pickers;
mod plan_handoff;

View File

@@ -104,7 +104,7 @@ impl App {
let stored: Vec<String> =
service.stored().into_iter().map(|option| option.id).collect();
let message = match stored.is_empty() {
true => "Nothing is signed in. /login sets a provider up.".to_string(),
true => "Not signed in to any provider · /login to add one".to_string(),
false => format!("Usage: /logout <provider> — signed in: {}", stored.join(", ")),
};
self.push_convo(ConvoBlock::System(message));
@@ -167,14 +167,18 @@ impl App {
/// flow does not stop to be congratulated. What the login had to say (the account, how many
/// models it reached, any advice that only makes sense now) becomes the picker's opening line,
/// and the transcript keeps the whole of it for a reader who scrolls back.
///
/// The picker opens at the top with nothing chosen: which model to run is the reader's call,
/// and a cursor already resting on one reads as luxe recommending it.
fn finish_login(&mut self, outcome: luxe_core::auth::LoginOutcome) {
self.close_auth_wizard();
let adopted = self.adopt_login(&outcome);
self.refresh_configuration();
let configured = self.provider_configured();
self.set_provider_configured(configured);
self.push_convo(ConvoBlock::System(login_report(&outcome, adopted.as_deref())));
self.open_model_picker_with(login_note(&outcome, adopted.as_deref()));
self.push_convo(ConvoBlock::System(login_report(&outcome)));
let current = Some(self.status.model.as_str()).filter(|model| !model.is_empty());
let note = login_note(&outcome, current);
self.open_model_picker_at_top(note);
}
/// Re-read what is configured, so the Configuration summary reflects a login that just landed.
@@ -184,45 +188,19 @@ impl App {
configuration.refresh(&service.providers());
}
}
/// Switch the session onto a provider that was just configured, answering what it landed on.
///
/// Without this, a login only takes effect on the next launch: the engine keeps routing to
/// whatever was active when the session started. The catalog is rebuilt first so a model that
/// only exists because of this login can be found.
fn adopt_login(&mut self, outcome: &luxe_core::auth::LoginOutcome) -> Option<String> {
if let Some(sources) = &self.model_sources {
self.model_catalog = (sources.build)().catalog;
}
let provider = outcome.provider_id.as_str();
let entry = self.model_catalog.iter().find(|entry| {
entry.info.r#ref.provider == provider
&& outcome.suggested_model.as_deref().is_some_and(|id| entry.info.r#ref.id == id)
});
// Fall back to any model for that provider, so a login always leaves a usable session.
let info = entry
.or_else(|| {
self.model_catalog.iter().find(|entry| entry.info.r#ref.provider == provider)
})
.map(|entry| entry.info.clone())?;
let display = info.display().to_string();
self.apply_model_selection(info);
Some(display)
}
}
/// What the model picker says at the top of itself after a login. Args: `(outcome, adopted)`.
/// What the model picker says at the top of itself after a login. Args: `(outcome, current)`.
///
/// Two lines at most, because the reader is on their way to choosing a model and this is a caption
/// rather than a report — the whole of it is in the transcript ([`login_report`]). `adopted` is
/// the model the login already left the session on, which is the row the cursor is sitting on;
/// saying so is what stops it reading as a choice the reader has not made yet.
fn login_note(outcome: &luxe_core::auth::LoginOutcome, adopted: Option<&str>) -> Vec<String> {
/// rather than a report — the whole of it is in the transcript ([`login_report`]). `current` is
/// the model the session was already on, which Esc keeps.
fn login_note(outcome: &luxe_core::auth::LoginOutcome, current: Option<&str>) -> Vec<String> {
// No count of the models, and none of their names: they are the rows underneath this line.
vec![
format!("{}.", configured_headline(outcome)),
match adopted {
Some(model) => format!("Now on {model} — enter keeps it, or choose another."),
match current {
Some(model) => format!("Choose a model, or esc to stay on {model}."),
None => "Choose a model to finish setting up.".to_string(),
},
]
@@ -242,16 +220,13 @@ fn configured_headline(outcome: &luxe_core::auth::LoginOutcome) -> String {
}
}
/// The whole of what a login had to say, for the transcript. Args: `(outcome, adopted)`.
fn login_report(outcome: &luxe_core::auth::LoginOutcome, adopted: Option<&str>) -> String {
/// The whole of what a login had to say, for the transcript.
fn login_report(outcome: &luxe_core::auth::LoginOutcome) -> String {
let mut lines = vec![format!("{}.", configured_headline(outcome))];
if let Some(account) = &outcome.account {
lines.push(format!("Account: {account}"));
}
lines.extend(outcome.notes.iter().cloned());
if let Some(model) = adopted {
lines.push(format!("Model: {model}"));
}
lines.extend(outcome.advice.iter().cloned());
lines.join("\n")
}

View File

@@ -318,7 +318,7 @@ fn worktree_command(app: &mut App, arguments: Option<&str>) {
),
(Some("remove"), Some(_), Some(root)) => {
// Asked of git now, not read from the last snapshot, which may predate a file made
// outside Luxe
// outside luxe
if app.send_action(Action::CheckWorktreeRemoval, "check the worktree") {
app.worktree_removal_check = Some(root);
}

View File

@@ -257,7 +257,7 @@ fn preparing_and_failing_reach_the_preview() {
}
/// `/worktree` says where the session works. `remove` asks git, through the engine, what is
/// uncommitted right now — a snapshot can predate a file made outside Luxe — and is refused,
/// uncommitted right now — a snapshot can predate a file made outside luxe — and is refused,
/// naming it, unless nothing is; then the session ends with its worktree to remove.
#[test]
fn worktree_says_where_and_removes_only_committed_work() {

View File

@@ -50,7 +50,7 @@ fn every_listed_command_runs_where_it_is_listed() {
"{place} lists {:?}, and running it does nothing",
entry.command.name
);
// What would leave Luxe is recorded, never launched: this loop runs every command
// What would leave luxe is recorded, never launched: this loop runs every command
// on every run of the suite, and it once opened a browser tab each time
let crate::app::ExternalOpener::Recorded(opened) = &app.opener else {
panic!("{place}: a test app must not be able to launch anything");

View File

@@ -586,7 +586,7 @@ fn edited_draft_ctrl_enter_sends_the_new_wording() {
}
/// The composer is the one place a reviewer writes prose, and it was push/pop-char only. It now
/// runs on Luxe's real editor: a cursor you can move, word operations, and Unicode safety.
/// runs on luxe's real editor: a cursor you can move, word operations, and Unicode safety.
#[test]
fn the_comment_composer_supports_real_editing() {
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

View File

@@ -105,7 +105,7 @@ impl App {
},
ConfigFile {
name: "models.json",
detail: "Providers, models, and which one Luxe starts on",
detail: "Providers, models, and which one luxe starts on",
path: luxe_core::user_dirs::luxe_config_file("models.json"),
},
ConfigFile { name: "auth.json", detail: "Credentials — written 0600", path: auth },

View File

@@ -154,7 +154,7 @@ impl App {
/// a configured theme that names nothing.
///
/// A theme that falls back looks like a theme that is not very different, so a warning in the log
/// alone left someone tuning a file Luxe had never read.
/// alone left someone tuning a file luxe had never read.
pub(crate) fn theme_notices(config: &Config, registry: &ThemeRegistry) -> Vec<String> {
let mut notices: Vec<String> =
registry.problems().iter().map(|problem| format!("theme not loaded — {problem}")).collect();
@@ -175,7 +175,7 @@ pub(crate) fn theme_notices(config: &Config, registry: &ThemeRegistry) -> Vec<St
notices
}
/// A notice for each mention source whose kind one of Luxe's own tabs uses, so the tab it no longer
/// A notice for each mention source whose kind one of luxe's own tabs uses, so the tab it no longer
/// gets is explained rather than missing.
pub(crate) fn mention_notices(config: &Config) -> Vec<String> {
config
@@ -184,7 +184,7 @@ pub(crate) fn mention_notices(config: &Config) -> Vec<String> {
.filter(|source| source.reserved())
.map(|source| {
format!(
"mention source `{}` is not listed — `@[{}:…]` belongs to Luxe's own tab. Give it a \
"mention source `{}` is not listed — `@[{}:…]` belongs to luxe's own tab. Give it a \
`kind` of its own in {}",
source.name,
source.kind(),

View File

@@ -463,7 +463,7 @@ fn history_preview(value: &str) -> String {
}
/// A user message as the transcript shows it: the reader's words as they wrote them, and a brief
/// Luxe wrote to the agent as one line saying what happened.
/// luxe wrote to the agent as one line saying what happened.
///
/// A question from a review is the exception, since its words *are* the reader's: it shows what
/// they asked, under where they asked it, so the answer below it is not an answer to nothing.

View File

@@ -192,7 +192,7 @@ fn follow_reported_model(app: &mut App, reported: &luxe_core::event::ModelRef) {
/// Rings the bell and sends a desktop notification for `event`, each where the reader asked for it.
///
/// The bell answers every moment, since asking for one is asking to be told when Luxe needs you;
/// The bell answers every moment, since asking for one is asking to be told when luxe needs you;
/// the notification answers the moments `notifications` names. Headless has nobody to tell.
pub(super) fn alert(app: &App, event: NotificationEvent, body: &str) {
if app.headless {
@@ -223,8 +223,8 @@ fn notify_reader(app: &App, body: &str) {
}
let project = app.project_root.as_deref().and_then(std::path::Path::file_name);
let title = match project {
Some(name) => format!("Luxe · {}", name.to_string_lossy()),
None => "Luxe".to_string(),
Some(name) => format!("luxe · {}", name.to_string_lossy()),
None => "luxe".to_string(),
};
app.notifier.notify(&title, body);
}

View File

@@ -185,11 +185,8 @@ fn reduce_inner(app: &mut App, msg: Msg) {
app.toggle_block_details_at(index);
}
Msg::ScrollDock { up } => app.dock.scroll_by(up, app.dock_scroll_max.get()),
Msg::ScrollContextFiles { up } => {
if let Some(files) = app.overlays.context_files.as_mut() {
files.scroll_by(up);
}
}
Msg::ScrollContextFiles { up } => scroll_context_files(app, up),
Msg::ScrollOverlayList { list, up } => app.walk_overlay_list(list, up),
Msg::ScrollDockList { list, up } => {
app.dock.scroll_list_by(list, up, app.dock_list_metrics(list));
}
@@ -444,6 +441,13 @@ fn reduce_inner(app: &mut App, msg: Msg) {
}
}
/// Scrolls the context files overlay, when it's open.
fn scroll_context_files(app: &mut App, up: bool) {
if let Some(files) = app.overlays.context_files.as_mut() {
files.scroll_by(up);
}
}
/// Moves the surface behind a scrollbar to where its track was pressed or dragged.
fn drag_scrollbar(app: &mut App, region: crate::mouse::ScrollRegionId, row: u16, height: u16) {
use crate::mouse::ScrollRegionId;
@@ -476,6 +480,7 @@ fn drag_scrollbar(app: &mut App, region: crate::mouse::ScrollRegionId, row: u16,
ScrollRegionId::DockList(list) => {
app.dock.drag_list(list, row, height, app.dock_list_metrics(list));
}
ScrollRegionId::OverlayList(list) => app.drag_overlay_list(list, row, height),
ScrollRegionId::Dock | ScrollRegionId::ContextFiles => {}
}
}

View File

@@ -167,7 +167,7 @@ fn request_text(app: &mut App) {
view.text_request = None;
view.text = crate::changes::TextLoad::Failed(
luxe_core::project_files::ProjectFileFailure::Unreadable(
"Luxe is not accepting requests".into(),
"luxe is not accepting requests".into(),
),
);
}
@@ -227,7 +227,7 @@ fn request_capture(app: &mut App) {
if let Some(view) = app.changes.as_mut() {
view.request = None;
view.load = crate::changes::ChangesLoad::Failed(
luxe_core::file_diff::FileDiffFailure::Git("Luxe is not accepting requests".into()),
luxe_core::file_diff::FileDiffFailure::Git("luxe is not accepting requests".into()),
);
}
app.push_convo(ConvoBlock::System("Could not read that file's changes.".to_string()));

View File

@@ -18,30 +18,48 @@ pub(crate) fn changed(app: &App) -> Vec<DockChangeItem> {
.unwrap_or_default()
}
/// Asks for every listing the tree is about to need and does not have.
/// Most listings the tree has asked for and not had back.
///
/// Called whenever what is open, or what changed, may have moved. A refused send leaves the folder
/// unasked, so the next sync tries again rather than the tree waiting on an answer that is never
/// coming.
/// A change across the project stales every open folder at once, and asking for all of them in one
/// go would fill the engine's queue ahead of what the reader sends next: a steer, a cancel. Each
/// landed listing syncs again, so the rest follow as these come back.
pub(crate) const MAX_LISTINGS_IN_FLIGHT: usize = 8;
/// Asks for the listings the tree is about to need and does not have, a few at a time.
///
/// Called whenever what is open, or what changed, may have moved, and on every landed listing.
/// The reader didn't ask for these, so a refused send says nothing; it leaves the folder unasked,
/// and the next sync tries again rather than the tree waiting on an answer that is never coming.
pub(crate) fn sync(app: &mut App) {
if app.workspace.is_none() {
return;
}
let changes = changed(app);
app.files.refresh_if_changed(&changes);
for folder in app.files.wanted(&changes) {
let request_id = ListingRequestId::new();
let action = Action::ListDirectory {
request_id: request_id.clone(),
path: folder.clone(),
include_ignored: app.files.show_ignored,
};
if app.send_action(action, "list a folder") {
app.files.requested(&folder, request_id);
let room = MAX_LISTINGS_IN_FLIGHT.saturating_sub(app.files.in_flight());
for folder in app.files.wanted(&changes).into_iter().take(room) {
// A full queue refuses the rest of this burst too
if !ask_for_listing(app, &folder) {
break;
}
}
}
/// Asks the engine for one folder's listing and notes it as in flight. Answers whether it went.
fn ask_for_listing(app: &mut App, folder: &str) -> bool {
let request_id = ListingRequestId::new();
let action = Action::ListDirectory {
request_id: request_id.clone(),
path: folder.to_string(),
include_ignored: app.files.show_ignored,
};
if !app.send_quietly(action, "list a folder") {
return false;
}
app.files.requested(folder, request_id);
true
}
/// Applies a landed listing or its failure. Answers whether the event was the tree's.
pub(crate) fn apply(app: &mut App, event: &luxe_core::event::Event) -> bool {
use luxe_core::event::Event;

View File

@@ -60,7 +60,7 @@ pub(super) fn confirm(app: &mut App) {
})
.collect();
if to_send.is_empty() {
app.status.flash_toast("Nothing to send: space resolves a thread, c writes a reply");
app.status.flash_toast("Nothing to send · space resolve · c reply");
return;
}
let Some(review_id) = app.guided_review.as_ref().map(|review| review.id.clone()) else {

View File

@@ -117,6 +117,11 @@ pub enum Msg {
ScrollContextFiles {
up: bool,
},
/// Walks a modal list's cursor one row (mouse wheel over it).
ScrollOverlayList {
list: crate::mouse::OverlayList,
up: bool,
},
/// Scrolls one of the dock's lists by one step (mouse wheel over that section).
ScrollDockList {
list: crate::workspace_dock::DockList,

View File

@@ -122,7 +122,7 @@ fn run_command(app: &mut App, command: crate::commands::Command) {
// The mode outlives the session, so it is chosen here rather than in a session made for it
id::MODE => super::commands::dispatch(app, command),
id::SESSIONS => app.open_sessions(),
// Leaves Luxe, so a session started for it would only be left empty
// Leaves luxe, so a session started for it would only be left empty
id::UPDATE => app.outbox.update = true,
_ if command.slash_name() == Some("/quit") => {
app.should_quit = true;

View File

@@ -16,7 +16,7 @@ pub struct Outbox {
/// A file the reader chose to edit. The editor needs the terminal back, so the TUI exits and
/// the CLI runs it, the same way the Configuration surface's own `EditFile` does.
pub editor_file: Option<PathBuf>,
/// The session's worktree, to remove once Luxe has left it: only the loop can end the session
/// The session's worktree, to remove once luxe has left it: only the loop can end the session
/// and only the CLI can remove the directory the process is standing in
pub worktree_removal: Option<PathBuf>,
/// A pull request to check out and fix in a new session, with the comments that go with it
@@ -25,7 +25,7 @@ pub struct Outbox {
pub issue: Option<u64>,
/// A session of yours to leave this one for, and what the reader carries into it
pub resume: Option<crate::main_loop::ResumeLaunch>,
/// Whether to leave and update Luxe
/// Whether to leave and update luxe
pub update: bool,
/// Text to hand to the reader's editor and bring back
pub text_edit: Option<TextEdit>,

View File

@@ -0,0 +1,96 @@
//! Overlay lists — what the wheel and the scrollbar do to a modal list that follows its cursor.
//!
//! Every such list draws the window around its cursor rather than keeping a scroll offset of its
//! own, so both gestures move the cursor: a notch walks it a row, the way the arrows do, and a press
//! or drag on the bar puts it at that point of the list. A view that drifted off its cursor would
//! leave Enter choosing a row nobody can see.
use super::App;
use crate::configuration::ConfigOutcome;
use crate::mouse::OverlayList;
impl App {
/// Where `list`'s cursor is and how many rows it has, while it is open.
pub(crate) fn overlay_cursor(&self, list: OverlayList) -> Option<(usize, usize)> {
let overlays = &self.overlays;
match list {
OverlayList::Models => {
overlays.model_picker.as_ref().map(|picker| (picker.cursor(), picker.match_count()))
}
OverlayList::Providers => overlays
.auth_wizard
.as_ref()
.and_then(|wizard| Some((wizard.selected_row(), wizard.provider_rows()?))),
OverlayList::Palette => {
overlays.palette.as_ref().map(|palette| (palette.selected(), palette.match_count()))
}
OverlayList::Themes => {
overlays.theme_picker.as_ref().map(|picker| (picker.cursor(), picker.len()))
}
OverlayList::Sessions => overlays
.session_picker
.as_ref()
.map(|picker| (picker.cursor(), picker.match_count())),
OverlayList::Slash => overlays
.slash_flyout
.as_ref()
.map(|flyout| (flyout.cursor(), flyout.filtered_items().len())),
OverlayList::Mention => overlays
.mention
.as_ref()
.map(|mention| (mention.cursor(), mention.filtered_items().len())),
OverlayList::Configuration => {
overlays.configuration.as_ref().map(|it| it.list_cursor())
}
}
}
/// Puts `list`'s cursor on `row`, previewing a theme the way arrowing onto it does.
fn put_overlay_cursor(&mut self, list: OverlayList, row: usize) {
let overlays = &mut self.overlays;
match list {
OverlayList::Models => overlays.model_picker.as_mut().map(|picker| picker.select(row)),
OverlayList::Providers => {
overlays.auth_wizard.as_mut().map(|wizard| wizard.select_provider(row))
}
OverlayList::Palette => overlays.palette.as_mut().map(|palette| palette.select(row)),
OverlayList::Themes => {
let preview = overlays.theme_picker.as_mut().and_then(|picker| picker.select(row));
preview.map(|theme| self.preview_theme(&theme))
}
OverlayList::Sessions => {
overlays.session_picker.as_mut().map(|picker| picker.select(row))
}
OverlayList::Slash => overlays.slash_flyout.as_mut().map(|flyout| flyout.select(row)),
OverlayList::Mention => overlays.mention.as_mut().map(|mention| mention.select(row)),
OverlayList::Configuration => {
let moved = overlays.configuration.as_mut().map(|surface| surface.select(row));
// Repaints in the setup theme under the cursor, as a key onto it does
moved.map(|()| self.apply_configuration_outcome(ConfigOutcome::Consumed))
}
};
}
/// Walks `list`'s cursor one row, stopping at either end rather than wrapping as the arrows
/// do: a wheel spun past the last row would otherwise fling the reader back to the top.
pub(crate) fn walk_overlay_list(&mut self, list: OverlayList, up: bool) {
let Some((cursor, rows)) = self.overlay_cursor(list) else { return };
let row = match up {
true => cursor.saturating_sub(1),
false => (cursor + 1).min(rows.saturating_sub(1)),
};
if row != cursor {
self.put_overlay_cursor(list, row);
}
}
/// Puts `list`'s cursor at the point of the list that `row` of a `height`-tall bar stands for.
pub(crate) fn drag_overlay_list(&mut self, list: OverlayList, row: u16, height: u16) {
let Some((_, rows)) = self.overlay_cursor(list) else { return };
let target = crate::widgets::drag_offset(row, height, rows.saturating_sub(1));
self.put_overlay_cursor(list, target);
}
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,165 @@
use crate::app::App;
use crate::fixture::{seeded_app, FixtureScenario};
use crate::model_picker::{ModelEntry, ModelPickerState};
use crate::mouse::{MouseTarget, OverlayList, ScrollRegionId};
use crossterm::event::{KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
use luxe_core::provider::{ModelInfo, ModelRef};
use ratatui::{backend::TestBackend, layout::Rect, Terminal};
/// An app with the model picker open over `count` models, drawn once so its regions are published.
fn picker_over(count: usize) -> App {
let mut app = seeded_app("nord", FixtureScenario::ChatIdle).expect("a seeded app");
let models = (0..count)
.map(|index| ModelEntry {
info: ModelInfo {
r#ref: ModelRef::new("p", format!("m{index:02}")),
..Default::default()
},
label: format!("Model {index:02}"),
configured: true,
unverified: false,
})
.collect();
app.overlays.model_picker = Some(ModelPickerState::open(models, None));
draw(&mut app);
app
}
fn draw(app: &mut App) {
let mut terminal = Terminal::new(TestBackend::new(120, 30)).expect("a terminal");
terminal.draw(|frame| crate::view::render(frame, app)).expect("a frame");
}
/// Routes one mouse event at `(column, row)` the way the event loop does, and applies it.
fn mouse(app: &mut App, kind: MouseEventKind, (column, row): (u16, u16)) {
let event = MouseEvent { kind, column, row, modifiers: KeyModifiers::NONE };
match crate::main_loop::route_mouse(app, &event) {
crate::main_loop::RouteAction::Msg(message) => app.update(*message),
crate::main_loop::RouteAction::None => {}
other => panic!("a modal list should take the gesture itself: {other:?}"),
}
}
/// The first published click target `pick` accepts, with its rect.
fn target(app: &App, pick: impl Fn(&MouseTarget) -> bool) -> Option<(Rect, MouseTarget)> {
let hit = app.hit.borrow();
let found =
hit.clicks().find(|(_, target)| pick(target)).map(|(rect, target)| (rect, target.clone()));
found
}
fn models_cursor(app: &App) -> usize {
app.overlay_cursor(OverlayList::Models).expect("the picker is open").0
}
/// A cell on the picker's first row.
fn first_row(app: &App) -> (u16, u16) {
let (rect, _) = target(app, |it| *it == MouseTarget::ModelRow(0)).expect("a first row");
(rect.x + 2, rect.y)
}
/// The wheel over the picker walks its cursor a row a notch, and stops at the top rather than
/// wrapping to the bottom the way the arrows do.
///
/// The break this catches: no region published, so a notch fell through to the transcript behind
/// the modal and the list never moved.
#[test]
fn the_wheel_walks_the_model_picker_and_stops_at_its_ends() {
let mut app = picker_over(40);
let at = first_row(&app);
mouse(&mut app, MouseEventKind::ScrollDown, at);
mouse(&mut app, MouseEventKind::ScrollDown, at);
assert_eq!(models_cursor(&app), 2, "two notches down, two rows down");
for _ in 0..3 {
mouse(&mut app, MouseEventKind::ScrollUp, at);
}
assert_eq!(models_cursor(&app), 0, "the top holds instead of wrapping to the bottom");
}
/// A long list draws a bar in a column of its own, and a press low on the bar takes the cursor to
/// the end of the list.
#[test]
fn the_model_pickers_bar_takes_a_column_and_steers_the_cursor() {
let mut app = picker_over(40);
let region = ScrollRegionId::OverlayList(OverlayList::Models);
let (lane, _) =
target(&app, |it| matches!(it, MouseTarget::Scrollbar { region: r, .. } if *r == region))
.expect("a long list draws its bar");
let (row, _) = target(&app, |it| *it == MouseTarget::ModelRow(0)).expect("a first row");
assert!(row.right() <= lane.x, "rows stop short of the bar: {row:?} vs {lane:?}");
let bottom = (lane.x, lane.bottom() - 1);
mouse(&mut app, MouseEventKind::Down(MouseButton::Left), bottom);
mouse(&mut app, MouseEventKind::Up(MouseButton::Left), bottom);
assert_eq!(models_cursor(&app), 39, "the bottom of the bar is the end of the list");
}
/// A list that fits draws no bar, and the wheel over it still moves its cursor rather than the
/// transcript behind it.
#[test]
fn a_short_list_draws_no_bar_but_still_takes_the_wheel() {
let mut app = picker_over(4);
assert!(target(&app, |it| matches!(it, MouseTarget::Scrollbar { .. })).is_none());
let at = first_row(&app);
mouse(&mut app, MouseEventKind::ScrollDown, at);
assert_eq!(models_cursor(&app), 1);
}
/// The wheel over the theme picker previews what it lands on, as arrowing there does.
#[test]
fn the_wheel_over_the_theme_picker_previews_the_theme() {
let mut app = seeded_app("nord", FixtureScenario::ChatIdle).expect("a seeded app");
let themes = vec!["nord".to_string(), "dracula".to_string(), "gruvbox".to_string()];
app.overlays.theme_picker = Some(crate::theme_picker::ThemePickerState::open(themes, "nord"));
draw(&mut app);
let nord = app.theme_styles.accent;
let (rect, _) = target(&app, |it| *it == MouseTarget::ThemeRow(0)).expect("a theme row");
mouse(&mut app, MouseEventKind::ScrollDown, (rect.x + 2, rect.y));
assert_eq!(app.overlay_cursor(OverlayList::Themes), Some((1, 3)));
assert_ne!(app.theme_styles.accent, nord, "landing on a theme previews it");
}
/// Setup's theme step takes the wheel through the configuration surface, and repaints in the theme
/// it lands on the way the arrows do.
#[test]
fn the_wheel_over_setups_themes_previews_each_one() {
let mut wheeled = seeded_app("nord", FixtureScenario::Setup).expect("a seeded app");
draw(&mut wheeled);
let before = wheeled.theme_styles.clone();
let (rect, _) = target(&wheeled, |it| *it == MouseTarget::ConfigRow(0)).expect("a theme row");
// Two rows, since the first one down is the theme already showing
for _ in 0..2 {
mouse(&mut wheeled, MouseEventKind::ScrollDown, (rect.x + 2, rect.y));
}
let mut arrowed = seeded_app("nord", FixtureScenario::Setup).expect("a seeded app");
let down = crossterm::event::KeyEvent::new(crossterm::event::KeyCode::Down, KeyModifiers::NONE);
for _ in 0..2 {
match crate::main_loop::route_key(&mut arrowed, &down) {
crate::main_loop::RouteAction::Configuration(outcome) => {
arrowed.apply_configuration_outcome(outcome)
}
other => panic!("setup takes the arrow itself: {other:?}"),
}
}
let cursor = |app: &App| app.overlay_cursor(OverlayList::Configuration);
assert_eq!(cursor(&wheeled), cursor(&arrowed), "a notch moves as far as the arrow");
assert_ne!(wheeled.theme_styles, before, "and the app repaints");
assert_eq!(wheeled.theme_styles, arrowed.theme_styles, "in the same theme the arrow shows");
}
/// The login wizard's provider list takes the wheel too, and only while it is on that list.
#[test]
fn the_wheel_walks_the_login_providers() {
let mut app = seeded_app("nord", FixtureScenario::ChatIdle).expect("a seeded app");
crate::fixture::seed_login_wizard(&mut app, crate::fixture::LoginFixture::Providers);
draw(&mut app);
let (rect, _) =
target(&app, |it| *it == MouseTarget::AuthProviderRow(0)).expect("a provider row");
mouse(&mut app, MouseEventKind::ScrollDown, (rect.x + 2, rect.y));
assert_eq!(app.overlay_cursor(OverlayList::Providers).map(|(cursor, _)| cursor), Some(1));
let mut methods = seeded_app("nord", FixtureScenario::ChatIdle).expect("a seeded app");
crate::fixture::seed_login_wizard(&mut methods, crate::fixture::LoginFixture::Methods);
assert_eq!(methods.overlay_cursor(OverlayList::Providers), None, "a method list is not it");
}

View File

@@ -36,29 +36,30 @@ impl App {
/// The same, opening with something to say first. Args: `(note)`.
pub(crate) fn open_model_picker_with(&mut self, note: Vec<String>) {
let active = self.active_model_info.as_ref().map(|info| info.r#ref.clone());
self.open_model_picker_on(note, active);
}
/// The same, with the cursor on the first row rather than the model in use. Args: `(note)`.
pub(crate) fn open_model_picker_at_top(&mut self, note: Vec<String>) {
self.open_model_picker_on(note, None);
}
/// Opens the picker with the cursor on `start`, or the top. Args: `(note, start)`.
fn open_model_picker_on(
&mut self,
note: Vec<String>,
start: Option<luxe_core::provider::ModelRef>,
) {
if let Some(sources) = &self.model_sources {
self.model_catalog = (sources.build)().catalog;
}
if self.model_catalog.is_empty() {
match self.provider_configured() {
true => self.push_convo(ConvoBlock::System(
"No models available to switch to — add models under \"models\" in your Luxe \
config."
.to_string(),
)),
false => {
self.push_convo(ConvoBlock::System(
"No provider is configured, so there are no models to choose from yet."
.to_string(),
));
self.open_configuration();
}
}
self.explain_no_models();
return;
}
let active = self.active_model_info.as_ref().map(|info| info.r#ref.clone());
self.overlays.model_picker = Some(
crate::model_picker::ModelPickerState::open(self.model_catalog.clone(), active)
crate::model_picker::ModelPickerState::open(self.model_catalog.clone(), start)
.with_note(note),
);
// Drawn from what is on disk, then corrected by whatever a local server says when it
@@ -68,6 +69,22 @@ impl App {
self.model_sources.as_ref().is_some_and(|sources| sources.probe.is_some());
}
/// Says why there is no picker, and sends a machine with no provider to setup.
fn explain_no_models(&mut self) {
if self.provider_configured() {
self.push_convo(ConvoBlock::System(
"No models available to switch to — add models under \"models\" in your luxe \
config."
.to_string(),
));
return;
}
self.push_convo(ConvoBlock::System(
"No provider is configured, so there are no models to choose from yet.".to_string(),
));
self.open_configuration();
}
/// Apply a catalog rebuilt off the frame, leaving an open picker where the reader had it.
pub fn apply_model_catalog_refresh(&mut self, catalog: Vec<crate::model_picker::ModelEntry>) {
if catalog == self.model_catalog {
@@ -81,7 +98,7 @@ impl App {
/// Whether a turn has a model to run on.
///
/// Luxe chooses none on the reader's behalf, so a session can legitimately open with nothing
/// luxe chooses none on the reader's behalf, so a session can legitimately open with nothing
/// selected — the dashboard's first screen is one of the places you pick. The engine refuses a
/// turn either way ([`luxe_core::engine::EngineError::NoModel`]); this is what lets the UI ask
/// before the reader's message leaves the composer.

View File

@@ -1,6 +1,6 @@
//! Text-selection handling — mouse drags over the transcript, the composer and the Changes pane.
//!
//! Mouse capture takes the terminal's own click-drag selection away, so Luxe provides it: a press
//! Mouse capture takes the terminal's own click-drag selection away, so luxe provides it: a press
//! anchors, a drag extends, and a release copies (the copy-on-select behavior a terminal would
//! have given you). A press that lands twice on the same cell escalates to the word under it and
//! then to the whole line, the other two gestures capture costs. The composer keeps its selection

View File

@@ -43,7 +43,7 @@ impl App {
}
/// Write what setup gathered, and go where finishing goes: the start screen on a first run,
/// out of Luxe under `luxe init`.
/// out of luxe under `luxe init`.
pub(crate) fn finish_setup(&mut self, choices: SetupChoices) {
let mode = self.setup_mode();
if let Err(error) = write_choices(&choices) {

View File

@@ -62,7 +62,7 @@ fn printable_input_bypasses_legacy_plain_character_shortcuts() {
/// A submission with no model chosen opens the picker and keeps the draft.
///
/// Luxe picks no model for the reader, so this is a state a session can legitimately be in. The
/// luxe picks no model for the reader, so this is a state a session can legitimately be in. The
/// engine refuses such a turn anyway; the point of asking here is that the reader's message is
/// still in the composer when they come back from the picker, rather than gone into a turn that
/// was never going to run.

View File

@@ -417,7 +417,7 @@ fn the_mode_command_on_the_start_screen_stays_on_it() {
assert!(matches!(actions.as_slice(), [Action::SetMode(mode)] if mode == "plan"), "{actions:?}");
}
/// `/update` on the start screen leaves Luxe for the CLI's update, which needs the terminal, and
/// `/update` on the start screen leaves luxe for the CLI's update, which needs the terminal, and
/// starts no session on the way out.
#[test]
fn the_update_command_on_the_start_screen_leaves_to_update() {

View File

@@ -147,7 +147,7 @@ fn test_mention_picker_opens_at_start() {
/// The Files tab keeps up with the disk: opening the picker asks for a fresh read, the read lands
/// in the open picker with the cursor still on its file, and Ctrl+R asks again. A file made or
/// moved outside Luxe used to be unreachable until the session was reloaded.
/// moved outside luxe used to be unreachable until the session was reloaded.
#[test]
fn the_files_tab_reads_the_disk_again_and_keeps_its_place() {
let (tx, _rx) = mpsc::channel(8);
@@ -535,7 +535,7 @@ fn test_multi_mention_submit_does_not_panic() {
}
}
/// A mention source whose kind is one of Luxe's own tabs' — `mcp` above all, reserved after sources
/// A mention source whose kind is one of luxe's own tabs' — `mcp` above all, reserved after sources
/// existed — says why it has no tab, at startup, instead of quietly not having one.
#[test]
fn a_mention_source_on_a_reserved_kind_says_so_at_startup() {

View File

@@ -22,8 +22,8 @@ async fn a_turn_end_notifies_only_while_the_terminal_is_in_the_background() {
assert_eq!(
*calls.lock().unwrap(),
vec![
("Luxe · widget".to_string(), "Turn finished".to_string()),
("Luxe · widget".to_string(), "Turn failed: rate limited".to_string()),
("luxe · widget".to_string(), "Turn finished".to_string()),
("luxe · widget".to_string(), "Turn failed: rate limited".to_string()),
],
"the focused turn end sent nothing"
);

View File

@@ -105,13 +105,10 @@ fn command_palette_filters_and_dispatches() {
assert!(app.editor.current_input().is_empty(), "palette text must not leak to the editor");
}
/// A login has to leave the session able to run a turn, on a model that provider serves.
///
/// The suggested model is the flow's own answer and wins; without one, any model of that
/// provider beats leaving the session on whatever it launched with. What must never happen is
/// adopting *another* provider's model because the ids happened to line up.
/// A finished login opens the picker at its top row and leaves the session's model alone: which
/// model to run is the reader's call, and luxe has no favorite to land them on.
#[tokio::test]
async fn a_finished_login_lands_the_session_on_a_model_that_provider_serves() {
async fn a_finished_login_opens_the_picker_at_the_top_and_chooses_nothing() {
use crate::model_picker::{ModelEntry, ModelMenu};
use luxe_core::auth::{CredentialKind, LoginOutcome};
use luxe_core::provider::{ModelInfo, ModelRef};
@@ -127,15 +124,16 @@ async fn a_finished_login_lands_the_session_on_a_model_that_provider_serves() {
entry("openai", "gpt-5.4"),
entry("openai", "gpt-5.6"),
];
let outcome = |suggested: Option<&str>| LoginOutcome {
let outcome = || LoginOutcome {
provider_id: "openai".into(),
provider_name: "OpenAI".into(),
kind: Some(CredentialKind::ApiKey),
account: Some("acct-1".into()),
suggested_model: suggested.map(str::to_string),
notes: vec!["2 models available".into()],
advice: vec!["Enable it once in VS Code.".into()],
};
let finished = || Msg::Auth(crate::auth_wizard::AuthUiMsg::Finished(Ok(outcome())));
let picker = |app: &App| app.overlays.model_picker.as_ref().expect("the picker opens").clone();
let app_with = |catalog: Vec<ModelEntry>| {
let (tx, _rx) = mpsc::channel(8);
let mut app = App::new(
@@ -155,21 +153,20 @@ async fn a_finished_login_lands_the_session_on_a_model_that_provider_serves() {
app
};
// The flow named one, so that is the one.
// A first login: nothing chosen, the cursor on the first row, and a caption saying so
let mut app = app_with(catalog.clone());
app.update(Msg::Auth(crate::auth_wizard::AuthUiMsg::Finished(Ok(outcome(Some("gpt-5.6"))))));
assert_eq!(app.status.model, "gpt-5.6");
app.update(finished());
assert_eq!(app.status.model, "", "the login picks no model for the reader");
assert_eq!(picker(&app).cursor(), 0, "the picker starts at its top");
assert!(picker(&app).note().iter().any(|line| line.contains("Choose a model to finish")));
// It named none, so any model of *that* provider does.
// A second provider while one is in use: still the top, and Esc keeps what is running
let mut app = app_with(catalog.clone());
app.update(Msg::Auth(crate::auth_wizard::AuthUiMsg::Finished(Ok(outcome(None)))));
assert!(app.status.model.starts_with("gpt-5."), "got {}", app.status.model);
// It named one this provider does not serve, which is not a reason to leave the session on
// somebody else's model.
let mut app = app_with(vec![entry("anthropic", "claude-sonnet-5")]);
app.update(Msg::Auth(crate::auth_wizard::AuthUiMsg::Finished(Ok(outcome(Some("gpt-5.6"))))));
assert_eq!(app.status.model, "", "no model of that provider is no model");
app.apply_model_selection(catalog[2].info.clone());
app.update(finished());
assert_eq!(app.status.model, "gpt-5.6", "the session stays on what it was on");
assert_eq!(picker(&app).cursor(), 0, "not on the model in use either");
assert!(picker(&app).note().iter().any(|line| line.contains("esc to stay on gpt-5.6")));
// And the whole of what the login said survives in the transcript, where the picker's
// two-line caption cannot carry it.

View File

@@ -196,6 +196,11 @@ impl AuthWizardState {
&self.providers
}
/// How many providers the list shows, while the wizard is on that list.
pub(crate) fn provider_rows(&self) -> Option<usize> {
matches!(self.stage, Stage::Provider { .. }).then(|| self.visible_providers().len())
}
/// Highlighted row in the current list stage.
pub fn selected_row(&self) -> usize {
match &self.stage {

View File

@@ -118,7 +118,7 @@ impl AuthWizardState {
match self.scope() {
LoginScope::Any => None,
LoginScope::Subscription => {
Some("Signs in to a plan you already pay for. Luxe never sees your password.")
Some("Signs in to a plan you already pay for. luxe never sees your password.")
}
LoginScope::ApiKey => {
Some("Paste a key from the provider's console. Stored 0600 in auth.json.")

View File

@@ -51,7 +51,9 @@ impl AuthWizardState {
let rows = chunks[2].height as usize;
let selected = self.selected_row();
let start = selected.saturating_sub(rows.saturating_sub(1));
let row_width = usize::from(chunks[2].width);
let width =
crate::widgets::list_rows_width(chunks[2].width, visible.len(), chunks[2].height);
let row_width = usize::from(width);
// One window drives both the rows drawn and the rows clickable
let shown: Vec<(usize, &luxe_core::auth::ProviderOption)> = visible
.iter()
@@ -64,18 +66,21 @@ impl AuthWizardState {
.iter()
.map(|(row, option)| self.provider_row(option, *row == selected, row_width, theme))
.collect();
frame.render_widget(List::new(items), chunks[2]);
frame.render_widget(List::new(items), Rect { width, ..chunks[2] });
let mut regions = hit.borrow_mut();
for (offset, _) in &shown {
let y = chunks[2].y.saturating_add((offset - start) as u16);
if y < chunks[2].bottom() {
regions.push(
Rect::new(chunks[2].x, y, chunks[2].width, 1),
Rect::new(chunks[2].x, y, width, 1),
MouseTarget::AuthProviderRow(*offset),
);
}
}
let list = crate::mouse::OverlayList::Providers;
let window = (start, visible.len());
crate::widgets::list_scrollbar(frame, &mut regions, chunks[2], list, window, theme);
}
}

View File

@@ -193,7 +193,6 @@ fn a_finished_login_hands_the_outcome_back_and_ends_the_wizard() {
provider_name: "OpenAI".into(),
kind: Some(luxe_core::auth::CredentialKind::ApiKey),
account: None,
suggested_model: None,
notes: vec!["12 models available".into()],
advice: Vec::new(),
})));

View File

@@ -380,7 +380,7 @@ impl ChangesView {
/// The path one step from the visible file, wrapping at both ends.
///
/// Wraps because the list is short and circular movement is what every other picker in Luxe
/// Wraps because the list is short and circular movement is what every other picker in luxe
/// does; stopping dead at the last file would read as a broken key. A visible file that has
/// left the list — reverted while it was open — steps back *onto* the list rather than off it.
pub(crate) fn step(&self, forward: bool) -> Option<String> {

View File

@@ -1,4 +1,4 @@
//! commands — the one list of what Luxe can do, for the palette and the slash flyout.
//! commands — the one list of what luxe can do, for the palette and the slash flyout.
//!
//! Both doors read this registry: `Ctrl+K` lists everything that can run where you are, `/` lists
//! the ones with a slash trigger. A command is data — a name you would say out loud, a sentence
@@ -369,7 +369,7 @@ pub struct CommandRegistry {
}
impl CommandRegistry {
/// Every command Luxe knows.
/// Every command luxe knows.
pub fn all() -> Self {
Self::from_sources([built_in()])
}
@@ -383,7 +383,7 @@ impl CommandRegistry {
/// Joins lists of commands into one, the first to claim an id keeping it.
///
/// The built-ins come first, so nothing added later can take over a name Luxe already answers
/// The built-ins come first, so nothing added later can take over a name luxe already answers
/// to.
pub fn from_sources(sources: impl IntoIterator<Item = Vec<Command>>) -> Self {
let mut commands: Vec<Command> = Vec::new();

View File

@@ -1,9 +1,9 @@
//! The built-ins — every command Luxe ships.
//! The built-ins — every command luxe ships.
use super::{id, Command, Need};
use luxe_core::keymap::UiAction;
/// Every command Luxe ships, in no particular order: a menu sorts them.
/// Every command luxe ships, in no particular order: a menu sorts them.
///
/// Left out on purpose, because they are keys rather than commands and the key card lists them:
/// moving around a review or a diff, block selection, scrolling, the editor's own mechanics
@@ -17,10 +17,10 @@ pub(super) fn built_in() -> Vec<Command> {
// === Anywhere ===
Command::action(UiAction::Quit)
.with_slash("/quit")
.summary("Leaves Luxe; the session is saved as it goes, so nothing is lost.")
.summary("Leaves luxe; the session is saved as it goes, so nothing is lost.")
.keywords(&["exit", "close"]),
Command::slash(id::UPDATE, "Update Luxe", "/update")
.summary("Quits Luxe and updates it with the command for however you installed it.")
Command::slash(id::UPDATE, "Update luxe", "/update")
.summary("Quits luxe and updates it with the command for however you installed it.")
.detail(
"The same as `luxe update`: each command is shown before it runs, in this \
terminal. A copy your system's package manager owns is left to it.",
@@ -43,7 +43,7 @@ pub(super) fn built_in() -> Vec<Command> {
.needs(&[Chat])
.summary("Opens the model picker; the session carries on with whichever you choose.")
.detail(
"Every model Luxe knows for the providers it can reach, yours first. The context \
"Every model luxe knows for the providers it can reach, yours first. The context \
window, output cap, reasoning levels and pricing move with it.",
)
.keywords(&["switch", "provider", "llm"]),
@@ -402,7 +402,7 @@ pub(super) fn built_in() -> Vec<Command> {
.keywords(&["api key", "credentials"]),
Command::slash(id::LOGOUT, "Sign out", "/logout")
.needs(&[Chat])
.summary("Removes the credential Luxe stored for a provider.")
.summary("Removes the credential luxe stored for a provider.")
.detail("Bare, it lists what is signed in.")
.usage(&[("/logout <provider>", "")])
.keywords(&["credentials"]),

View File

@@ -302,7 +302,7 @@ fn filtering_a_menu_keeps_its_recent_lead_honest() {
}
/// The first list to claim an id or a slash trigger keeps it, so nothing added after the
/// built-ins can take over a name Luxe already answers to.
/// built-ins can take over a name luxe already answers to.
#[test]
fn a_later_source_cannot_take_a_built_in_id_or_trigger() {
let impostor = |id: &'static str, slash: &'static str| {

View File

@@ -1,4 +1,4 @@
//! Configuration — the surface that answers *how do I set Luxe up?*
//! Configuration — the surface that answers *how do I set luxe up?*
//!
//! One place for every way in: a subscription, a key, a server on this machine, or the files
//! themselves. It is what the dashboard's `Configuration` row opens, what `/config` reaches
@@ -10,7 +10,7 @@
//! overlays: keys in, a [`ConfigOutcome`] out, and the app owns what happens next.
//!
//! The menu asks for the **method** before the provider, which is the inverse of the wizard's own
//! order. `/login openai` knows its provider; someone who has just installed Luxe knows they have a
//! order. `/login openai` knows its provider; someone who has just installed luxe knows they have a
//! ChatGPT plan. Each row hands the wizard a [`LoginScope`], so the list it opens is short and every
//! row in it starts its flow on Enter.
@@ -38,7 +38,7 @@ pub enum ConfigChoice {
LocalOrCustom,
/// The settings pages: appearance, the conversation, layout, tools and the agent.
Settings,
/// Open one of Luxe's configuration files in an editor.
/// Open one of luxe's configuration files in an editor.
EditFiles,
}
@@ -242,6 +242,19 @@ impl ConfigurationState {
}
}
/// The cursor and the row count of whichever list is showing.
pub(crate) fn list_cursor(&self) -> (usize, usize) {
match self.stage {
Stage::Menu => (self.selected, ConfigChoice::ROWS.len()),
Stage::Files => (self.file_selected, self.files.len()),
Stage::Settings => self
.settings
.as_ref()
.map_or((0, 0), |settings| (settings.selected(), settings.selectable_count())),
Stage::Setup => self.setup.as_ref().map_or((0, 0), SetupState::step_list),
}
}
/// The configuration files on offer.
pub fn files(&self) -> &[ConfigFile] {
&self.files

View File

@@ -170,6 +170,11 @@ impl SettingsState {
self.selectable().iter().position(|row| *row == self.cursor).unwrap_or(0)
}
/// How many rows the cursor can land on.
pub(crate) fn selectable_count(&self) -> usize {
self.selectable().len()
}
/// Handle a keypress.
pub fn on_key(&mut self, key: &KeyEvent) -> ConfigOutcome {
self.notice = None;

View File

@@ -178,7 +178,8 @@ impl SettingsState {
scroll = scroll.min(rows.len().saturating_sub(height));
self.scroll.set(scroll);
let width = usize::from(list.width);
let columns = crate::widgets::list_rows_width(list.width, rows.len(), list.height);
let width = usize::from(columns);
let selectable = self.selectable();
let mut regions = hit.borrow_mut();
let lines: Vec<Line<'static>> = rows
@@ -190,16 +191,17 @@ impl SettingsState {
let selected = index == self.cursor;
if let Some(position) = selectable.iter().position(|at| *at == index) {
let y = list.y + (index - scroll) as u16;
regions.push(
Rect::new(list.x, y, list.width, 1),
MouseTarget::ConfigRow(position),
);
regions
.push(Rect::new(list.x, y, columns, 1), MouseTarget::ConfigRow(position));
}
self.row_line(*row, width, selected, theme)
})
.collect();
let shown = (scroll, rows.len());
let surface = crate::mouse::OverlayList::Configuration;
crate::widgets::list_scrollbar(f, &mut regions, list, surface, shown, theme);
drop(regions);
f.render_widget(Paragraph::new(lines), list);
f.render_widget(Paragraph::new(lines), Rect { width: columns, ..list });
}
fn row_line(
@@ -302,7 +304,7 @@ impl SettingsState {
let mut head = vec![
Span::styled(tool.name, theme.text.add_modifier(Modifier::BOLD)),
Span::styled(" tools.disabled", theme.accent),
Span::styled(" · Takes effect the next time Luxe starts", theme.muted),
Span::styled(" · Takes effect the next time luxe starts", theme.muted),
];
head.push(Span::styled(source_note(layer), layer_style(layer, theme)));
lines.push(Line::from(head));

View File

@@ -134,7 +134,7 @@ const SIGN_IN: [ConfigChoice; 3] =
impl SetupState {
/// Open on the first step, with every answer pre-set to what `config` already says.
///
/// `themes` is every theme by name; `desktop` the one the desktop is wearing, when Luxe can
/// `themes` is every theme by name; `desktop` the one the desktop is wearing, when luxe can
/// follow one; `active` the theme in force right now.
pub fn open(
mode: SetupMode,
@@ -150,7 +150,7 @@ impl SetupState {
offered.extend(themes.into_iter().map(Some));
let theme = match config.theme.as_deref() {
Some(name) => offered.iter().position(|offer| offer.as_deref() == Some(name)),
// Nothing chosen yet: the desktop's when there is one, Luxe's own otherwise
// Nothing chosen yet: the desktop's when there is one, luxe's own otherwise
None if desktop.is_some() => Some(0),
None => offered.iter().position(|offer| offer.as_deref() == Some("luxe")),
}
@@ -269,20 +269,21 @@ impl SetupState {
self.advance(configured)
}
fn step_cursor(&mut self, delta: isize) -> ConfigOutcome {
let (cursor, rows) = match self.step {
Step::Theme => (&mut self.theme, self.themes.len()),
Step::Provider => (&mut self.provider, SIGN_IN.len() + 1),
Step::Tools => (&mut self.tool, self.tools.len()),
Step::Start => (&mut self.start, StartScreen::ALL.len()),
};
*cursor = cursor.saturating_add_signed(delta).min(rows.saturating_sub(1));
/// The cursor and the row count of the step showing.
pub(crate) fn step_list(&self) -> (usize, usize) {
match self.step {
Step::Theme => ConfigOutcome::PreviewTheme(self.previewed_theme()),
_ => ConfigOutcome::Consumed,
Step::Theme => (self.theme, self.themes.len()),
Step::Provider => (self.provider, SIGN_IN.len() + 1),
Step::Tools => (self.tool, self.tools.len()),
Step::Start => (self.start, StartScreen::ALL.len()),
}
}
fn step_cursor(&mut self, delta: isize) -> ConfigOutcome {
let (cursor, rows) = self.step_list();
self.select(cursor.saturating_add_signed(delta).min(rows.saturating_sub(1)))
}
/// Enter: the provider step's sign-in rows open the wizard; everywhere else, on to the next
/// step, and from the last one, done.
fn advance(&mut self, configured: bool) -> ConfigOutcome {
@@ -350,7 +351,7 @@ mod tests {
assert_eq!(setup.choices().theme.as_deref(), Some("nord"));
let plain = fresh(None);
assert_eq!(plain.choices().theme.as_deref(), Some("luxe"), "no desktop: Luxe's own");
assert_eq!(plain.choices().theme.as_deref(), Some("luxe"), "no desktop: luxe's own");
}
#[test]

View File

@@ -21,6 +21,9 @@ pub(in crate::configuration) const PANEL_WIDTH: u16 = 112;
/// Width of the theme list and the tool list, beside what each explains.
const LIST_WIDTH: u16 = 34;
/// Which list the wheel and the bar move on a setup step: the surface's, whichever step it is on.
const SETUP_LIST: crate::mouse::OverlayList = crate::mouse::OverlayList::Configuration;
impl SetupState {
/// Rows the panel would like, which leaves the wordmark what is left.
pub fn panel_height(area: Rect) -> u16 {
@@ -37,8 +40,8 @@ impl SetupState {
configured: &[String],
) {
let title = match self.mode {
SetupMode::FirstRun => "Welcome to Luxe",
SetupMode::Init => "Set up Luxe",
SetupMode::FirstRun => "Welcome to luxe",
SetupMode::Init => "Set up luxe",
};
let block = crate::widgets::titled_panel(Icon::Config.glyph(), title, theme)
.padding(Padding::horizontal(1));
@@ -111,6 +114,9 @@ impl SetupState {
let start =
(self.theme + 1).saturating_sub(height).min(self.themes.len().saturating_sub(height));
let mut regions = hit.borrow_mut();
let shown = (start, self.themes.len());
crate::widgets::list_scrollbar(f, &mut regions, list, SETUP_LIST, shown, theme);
let rows = crate::widgets::list_rows_width(list.width, self.themes.len(), list.height);
let lines: Vec<Line<'static>> = self
.themes
.iter()
@@ -119,7 +125,7 @@ impl SetupState {
.take(height)
.map(|(index, offer)| {
regions.push(
Rect::new(list.x, list.y + (index - start) as u16, list.width, 1),
Rect::new(list.x, list.y + (index - start) as u16, rows, 1),
MouseTarget::ConfigRow(index),
);
let chosen = index == self.theme;
@@ -136,11 +142,11 @@ impl SetupState {
),
Span::styled(label, theme.label_on(chosen)),
];
selection_row(spans, usize::from(list.width), chosen, theme)
selection_row(spans, usize::from(rows), chosen, theme)
})
.collect();
drop(regions);
f.render_widget(Paragraph::new(lines), list);
f.render_widget(Paragraph::new(lines), Rect { width: rows, ..list });
let sample = Rect {
x: list.right() + 3,
@@ -234,11 +240,14 @@ impl SetupState {
hit: &std::cell::RefCell<HitRegions>,
) {
let list = Rect { width: (LIST_WIDTH + 18).min(body.width), ..body };
let width = usize::from(list.width);
let height = usize::from(list.height);
let start =
(self.tool + 1).saturating_sub(height).min(self.tools.len().saturating_sub(height));
let mut regions = hit.borrow_mut();
let shown = (start, self.tools.len());
crate::widgets::list_scrollbar(f, &mut regions, list, SETUP_LIST, shown, theme);
let rows = crate::widgets::list_rows_width(list.width, self.tools.len(), list.height);
let width = usize::from(rows);
let lines: Vec<Line<'static>> = self
.tools
.iter()
@@ -247,7 +256,7 @@ impl SetupState {
.take(height)
.map(|(index, (tool, enabled))| {
regions.push(
Rect::new(list.x, list.y + (index - start) as u16, list.width, 1),
Rect::new(list.x, list.y + (index - start) as u16, rows, 1),
MouseTarget::ConfigRow(index),
);
let chosen = index == self.tool;
@@ -270,7 +279,7 @@ impl SetupState {
})
.collect();
drop(regions);
f.render_widget(Paragraph::new(lines), list);
f.render_widget(Paragraph::new(lines), Rect { width: rows, ..list });
let side = Rect {
x: list.right() + 3,
@@ -319,7 +328,7 @@ impl SetupState {
) {
f.render_widget(
Paragraph::new(Line::from(Span::styled(
"What Luxe opens on when you run it in a project.",
"What luxe opens on when you run it in a project.",
theme.muted,
))),
Rect { height: 1, ..body },

View File

@@ -117,7 +117,7 @@ fn the_cursor_stops_at_both_ends_of_each_list() {
}
/// "Configured" and "signed in" are not the same claim: an environment variable is the user's
/// shell rather than something Luxe stored, and the summary has to say which.
/// shell rather than something luxe stored, and the summary has to say which.
#[test]
fn the_summary_names_every_credential_and_where_it_came_from() {
let providers = vec![

View File

@@ -10,7 +10,7 @@
//! so a project carrying forty skills has a long list rather than rows nobody can reach. Past that
//! what it wants is a filter box — still not a submenu.
//!
//! It sits beside [`crate::configuration`] rather than inside it on purpose. Those are Luxe's own
//! It sits beside [`crate::configuration`] rather than inside it on purpose. Those are luxe's own
//! settings — a theme, a credential, a keymap. These belong to the *project*: a different author,
//! a different lifecycle, and they travel with the repository rather than the machine.
//!
@@ -277,7 +277,7 @@ impl ContextFilesState {
/// dashboard disagree with the prompt.
///
/// `cwd` is the project root, which paths are shown relative to; `instructions_from` is where the
/// instruction walk starts, which is where Luxe was launched — the same directory the prompt walks
/// instruction walk starts, which is where luxe was launched — the same directory the prompt walks
/// from, or the list would come up short of what a turn reads.
pub fn discover(cwd: &Path, instructions_from: &Path) -> Vec<ContextFileRow> {
let found = luxe_core::instructions::context_files(instructions_from);

View File

@@ -31,6 +31,11 @@ impl FilesTree {
wanted
}
/// How many listings have been asked for and not yet answered.
pub fn in_flight(&self) -> usize {
self.listings.values().filter(|listing| listing.request.is_some()).count()
}
/// Records that `folder`'s listing was asked for under `request`.
pub fn requested(&mut self, folder: &str, request: ListingRequestId) {
self.generation += 1;

View File

@@ -60,8 +60,8 @@ pub use workspace::seed_plan_usage;
/// A light palette, for the light-mode paths no built-in reaches any more.
///
/// Luxe ships dark themes only, but a reader's own theme file can be light, and the code that picks
/// ink for a light canvas still has to be right for them. This is Catppuccin Latte as Luxe shipped
/// luxe ships dark themes only, but a reader's own theme file can be light, and the code that picks
/// ink for a light canvas still has to be right for them. This is Catppuccin Latte as luxe shipped
/// it until the light themes were retired, kept so those paths keep a test that can fail.
pub const LIGHT_THEME_JSON: &str = include_str!("fixture/light-theme.json");

View File

@@ -65,7 +65,7 @@ impl luxe_core::auth::AuthService for FixtureAuth {
CredentialStatus::Env("ANTHROPIC_API_KEY".into()),
Some(
"API key only. Anthropic's terms forbid using a Claude Pro/Max subscription \
from a third-party harness, so Luxe does not offer that sign-in.",
from a third-party harness, so luxe does not offer that sign-in.",
),
),
option(
@@ -272,7 +272,6 @@ pub fn seed_login_wizard(app: &mut App, which: LoginFixture) {
provider_name: "OpenAI".into(),
kind: Some(CredentialKind::ApiKey),
account: None,
suggested_model: Some("gpt-5.6".into()),
notes: vec!["47 models available (gpt-4.1, gpt-5, gpt-5-mini, …)".into()],
advice: Vec::new(),
}))));

View File

@@ -6,7 +6,7 @@
//! So each icon is declared once in the `icons!` table below, by *meaning*, with all three of its
//! renderings beside it:
//!
//! - [`GlyphTier::Nerd`] — Material Design icons from a patched font, the look Luxe ships with.
//! - [`GlyphTier::Nerd`] — Material Design icons from a patched font, the look luxe ships with.
//! - [`GlyphTier::Unicode`] — Geometric Shapes, Arrows and two Dingbats: no private use anywhere,
//! nothing newer than Unicode 1.1 outside a couple of shapes, and every entry one cell wide.
//! - [`GlyphTier::Ascii`] — plain punctuation, for SSH into a minimal box, a CI log, or a terminal
@@ -66,7 +66,8 @@ pub use format::{configured_glyph, icon_cells, icon_gap, icon_label, icon_prefix
pub use spinner::spinner;
#[cfg(test)]
pub(crate) use spinner::spinner_ticks_per_frame;
pub use state::{braille, resolve_vocabulary, set_braille, set_tier, tier};
pub use state::RECENT_BRANDS;
pub use state::{braille, brands, resolve_vocabulary, set_braille, set_brands, set_tier, tier};
use unicode_width::UnicodeWidthStr;
#[cfg(test)]
use {
@@ -171,6 +172,20 @@ icons! {
Model => ["\u{f06a9}", "●", "%"],
/// Model reasoning
Thinking => ["\u{f0335}", "●", "~"],
/// Who serves the model, when it has no mark of its own (`md-cloud_outline`)
Provider => ["\u{f0163}", "○", "@"],
/// Google, serving Gemini (`md-google`)
ProviderGoogle => ["\u{f02ad}", "○", "@"],
/// Microsoft Azure, serving Foundry (`md-microsoft_azure`)
ProviderAzure => ["\u{f0805}", "○", "@"],
/// Amazon Bedrock (`md-aws`)
ProviderAws => ["\u{f0e0f}", "○", "@"],
/// OpenAI (`cod-openai`), one of the [`RECENT_BRANDS`]
ProviderOpenAi => ["\u{ec81}", "○", "@"],
/// Anthropic (`cod-claude`), one of the [`RECENT_BRANDS`]
ProviderAnthropic => ["\u{ec82}", "○", "@"],
/// GitHub Copilot (`cod-copilot`), one of the [`RECENT_BRANDS`]
ProviderCopilot => ["\u{ec1e}", "○", "@"],
// === Dashboard menu ===
Find => ["\u{f021e}", "○", "/"],
NewSession => ["\u{f0214}", "►", "+"],

View File

@@ -1,7 +1,7 @@
//! Glyph detection — what the terminal and its fonts can draw: braille, Nerd Font icons, kitty.
use super::spinner::SPINNER_BRAILLE;
use super::{GlyphTier, EVERY_ICON};
use super::{GlyphTier, EVERY_ICON, RECENT_BRANDS};
/// Whether the terminal in front of the reader can draw the braille sweep.
///
@@ -109,8 +109,20 @@ pub(super) fn nerd_icons_available() -> bool {
return true;
}
// Derived from the table, so an icon added in a range nothing else uses extends the probe
// rather than slipping past it.
fontconfig_has_all(EVERY_ICON.iter().filter_map(|icon| icon.at(GlyphTier::Nerd).chars().next()))
// rather than slipping past it. The recent brands are asked about on their own
let probed = EVERY_ICON.iter().filter(|icon| !RECENT_BRANDS.contains(icon));
fontconfig_has_all(probed.filter_map(|icon| icon.at(GlyphTier::Nerd).chars().next()))
}
/// Whether one installed font has every recent brand mark, which only Nerd Fonts 3.5 and later do.
///
/// fontconfig is the only way to ask, so without it (stock macOS, Windows) the answer is no and
/// each brand falls back to a mark every v3 font has. Not kitty's shortcut either: the symbol font
/// it bundles is as old as the kitty.
pub(super) fn brands_available() -> bool {
fontconfig_has_all(
RECENT_BRANDS.iter().filter_map(|icon| icon.at(GlyphTier::Nerd).chars().next()),
)
}
/// Whether this is kitty — the one terminal that answers the question above by itself.

View File

@@ -1,7 +1,7 @@
//! Glyph state — the vocabulary and braille switch every glyph call reads, set once at startup.
use super::detect::braille_available;
use super::GlyphTier;
use super::detect::{braille_available, brands_available};
use super::{GlyphTier, Icon};
use luxe_core::config::GlyphStyle;
use std::sync::atomic::{AtomicU8, Ordering};
@@ -21,8 +21,30 @@ static BRAILLE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::n
/// and `/reload`. Setting the tier and forgetting the sweep is the mistake this exists to make
/// impossible.
pub fn resolve_vocabulary(preference: GlyphStyle) {
set_tier(GlyphTier::resolve(preference));
let tier = GlyphTier::resolve(preference);
set_tier(tier);
set_braille(braille_available());
set_brands(matches!(tier, GlyphTier::Nerd | GlyphTier::NerdWide) && brands_available());
}
/// Brand marks newer than the rest of the vocabulary: OpenAI's and Claude's arrived in Nerd Fonts
/// 3.5, Copilot's after 3.0. They stay out of the nerd-tier probe, so an older font keeps every
/// other icon, and are drawn only when [`brands`] says a font on the machine has them.
pub const RECENT_BRANDS: &[Icon] =
&[Icon::ProviderOpenAi, Icon::ProviderAnthropic, Icon::ProviderCopilot];
/// Whether the [`RECENT_BRANDS`] may be drawn. Off by default for the same reason as [`BRAILLE`]:
/// a test or a site asset draws the same on any machine.
static BRANDS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// Whether the recent brand marks are drawn, rather than the mark each falls back to.
pub fn brands() -> bool {
BRANDS.load(Ordering::Relaxed)
}
/// Turns the recent brand marks on or off. Exposed for tests and for the startup probe.
pub fn set_brands(available: bool) {
BRANDS.store(available, Ordering::Relaxed);
}
/// Whether the spinner is currently drawing its braille sweep.

View File

@@ -501,7 +501,7 @@ fn each_sweep_keeps_the_cadence_it_was_drawn_for() {
/// The process tier is what the ~150 render sites read, so moving it has to move them.
#[test]
fn the_process_tier_selects_the_vocabulary() {
assert_eq!(tier(), GlyphTier::Nerd, "the default is the look Luxe ships with");
assert_eq!(tier(), GlyphTier::Nerd, "the default is the look luxe ships with");
for at in TIERS {
set_tier(at);
assert_eq!(tier(), at, "{at:?} does not survive the round trip");

View File

@@ -226,7 +226,7 @@ fn the_text_tier_paints_nothing_and_admits_it() {
assert!(!store.paint_row(&mut buf, (0, 0), &ImageKey::new("missing"), fit, 0, Color::Reset));
}
/// Ids are global to the terminal, so two Luxe windows must not hand out the same one from the
/// Ids are global to the terminal, so two luxe windows must not hand out the same one from the
/// first frame and quietly replace each other's images.
#[test]
fn image_ids_stay_inside_the_protocols_range() {

View File

@@ -25,7 +25,7 @@ pub(crate) struct FindingDraft {
carried_fix: Option<String>,
/// The real editor backing the comment.
///
/// This is the one place a reviewer writes prose, so it reuses Luxe's composer wholesale and
/// This is the one place a reviewer writes prose, so it reuses luxe's composer wholesale and
/// behaves like every other text input: a cursor, arrow keys, word operations.
editor: crate::editor::Editor,
/// Why the last save was rejected, cleared by the next edit. Shown on screen, or `Ctrl+Enter`

View File

@@ -1,10 +1,10 @@
//! herdr — the agent's state, reported to herdr when Luxe runs in one of its panes.
//! herdr — the agent's state, reported to herdr when luxe runs in one of its panes.
//!
//! herdr is a terminal workspace manager for coding agents. It shows each agent's state in its
//! sidebar, rolls it up to tabs and workspaces, and raises its own notification when an agent
//! finishes or needs a decision. That last part matters here: herdr emulates the terminal in each
//! pane and keeps an `OSC 9` for itself, so the desktop notification Luxe writes through the
//! terminal never leaves the pane. Reporting the state is how a reader inside herdr hears from Luxe.
//! pane and keeps an `OSC 9` for itself, so the desktop notification luxe writes through the
//! terminal never leaves the pane. Reporting the state is how a reader inside herdr hears from luxe.
//!
//! The state is derived from the app on every pass of the loop ([`crate::app::App::agent_state`])
//! rather than pushed from each place it changes, and only a change is sent: `working` while a turn
@@ -54,7 +54,7 @@ impl AgentState {
}
}
/// The pane Luxe runs in, and the herdr that owns it.
/// The pane luxe runs in, and the herdr that owns it.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Pane {
/// `$HERDR_BIN_PATH`: the binary of the herdr that owns the pane, which may not be on `PATH`
@@ -63,7 +63,7 @@ struct Pane {
id: String,
}
/// The pane herdr says Luxe runs in, or `None` outside herdr.
/// The pane herdr says luxe runs in, or `None` outside herdr.
///
/// All of it or nothing: herdr's own guidance is to report only when `HERDR_ENV=1` and the rest
/// are set, so a shell that merely inherited one variable reports nowhere.
@@ -128,7 +128,7 @@ fn release_args(pane: &str, seq: u64) -> Vec<String> {
args
}
/// Whether a session id can travel in a resume command: what Luxe writes, nothing a shell or herdr
/// Whether a session id can travel in a resume command: what luxe writes, nothing a shell or herdr
/// would read as more than one plain word.
fn resumable(id: &str) -> bool {
!id.is_empty() && id.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))
@@ -148,7 +148,7 @@ fn message_text(message: &str) -> String {
}
}
/// Report numbers: rising across reports, and across restarts of Luxe, which a clock gives for free.
/// Report numbers: rising across reports, and across restarts of luxe, which a clock gives for free.
#[derive(Debug, Default)]
struct Sequence {
last: u64,
@@ -164,7 +164,7 @@ impl Sequence {
}
}
/// Reports the agent's state to the herdr pane Luxe runs in.
/// Reports the agent's state to the herdr pane luxe runs in.
pub struct Reporter {
pane: Pane,
/// What was last handed to the worker, so an unchanged state is not sent again

View File

@@ -1,11 +1,11 @@
//! Launcher — a key that hands the terminal to another program and takes it back.
//!
//! gh-dash, lazygit, anything that takes over a terminal. Luxe gives the terminal up whole — the
//! gh-dash, lazygit, anything that takes over a terminal. luxe gives the terminal up whole — the
//! alternate screen, raw mode, mouse, the keyboard protocol — and stops reading it, so every key is
//! the program's; the engine keeps running underneath, a turn included, and what it reports is
//! applied without drawing. When the program exits, Luxe takes the terminal back and redraws it.
//! applied without drawing. When the program exits, luxe takes the terminal back and redraws it.
//! Text the program writes to the file `$LUXE_HANDOFF` names lands in the composer, which is how a
//! gh-dash command sends `#123 look at this` into Luxe.
//! gh-dash command sends `#123 look at this` into luxe.
use crossterm::event::{EventStream, KeyEvent};
use luxe_core::config::Launcher;

View File

@@ -1,4 +1,4 @@
//! Luxe TUI — ratatui front-end for the Luxe agent.
//! luxe TUI — ratatui front-end for the luxe agent.
//!
//! This crate wraps the headless core in an interactive terminal UI. It is a thin
//! subscriber to the core `Event` stream: it holds no business logic, only rendering

View File

@@ -50,7 +50,7 @@ pub const ANIMATION_TICK: Duration = Duration::from_millis(33);
/// Why the TUI returned control to the CLI.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TuiExit {
/// The user quit Luxe.
/// The user quit luxe.
Quit,
/// Open a file in the reader's editor, then come back.
///
@@ -72,7 +72,7 @@ pub enum TuiExit {
///
/// Args: `(launch)` — the session, and the draft and mode the reader carries into it.
ResumeSession(ResumeLaunch),
/// Leave Luxe and run `luxe update`, which needs the terminal for the package manager.
/// Leave luxe and run `luxe update`, which needs the terminal for the package manager.
Update,
}
@@ -149,18 +149,30 @@ pub(crate) fn startup_surface(
}
}
/// Whether this is the first launch on the machine: no `config.json` yet, and someone at the
/// keyboard to ask.
/// Whether this is the first launch on the machine: no `config.json` and no stored login yet, and
/// someone at the keyboard to ask.
///
/// Strict on purpose. A question asked of a terminal nobody is watching stops a container or a CI
/// job until something answers it, so anything not interactive never sees it — and skipping it
/// writes the file, so it is asked once.
fn is_first_run(headless: bool) -> bool {
use std::io::IsTerminal;
!headless
&& std::io::stdin().is_terminal()
&& std::io::stdout().is_terminal()
&& !luxe_core::config::Config::global_path().exists()
let interactive =
!headless && std::io::stdin().is_terminal() && std::io::stdout().is_terminal();
first_run_from(
interactive,
luxe_core::config::Config::global_path().exists(),
luxe_core::user_dirs::luxe_config_file("auth.json").exists(),
)
}
/// [`is_first_run`] over what it found. A stored login counts as having run before: a build that
/// never wrote `config.json` (one from before setup existed, or one quit mid-setup) still signed
/// someone in, and walking them through setup again after an update reads as a lost install.
///
/// Args: `(interactive, config file exists, auth file exists)`.
fn first_run_from(interactive: bool, config_exists: bool, login_exists: bool) -> bool {
interactive && !config_exists && !login_exists
}
/// Run the TUI event loop.

View File

@@ -306,6 +306,9 @@ pub(super) fn wheel(app: &App, col: u16, row: u16, up: bool) -> RouteAction {
RouteAction::msg(Msg::ScrollChanges { up, lines: crate::changes::SCROLL_STEP })
}
Some(ScrollRegionId::ContextFiles) => RouteAction::msg(Msg::ScrollContextFiles { up }),
Some(ScrollRegionId::OverlayList(list)) => {
RouteAction::msg(Msg::ScrollOverlayList { list, up })
}
// Their bars steer them, but their wheel is still the view's
Some(ScrollRegionId::ReviewFeedback | ScrollRegionId::PullRequestBody) | None => {
scroll_for_view(app, up)

View File

@@ -65,7 +65,7 @@ pub fn route_key(app: &mut App, key: &KeyEvent) -> RouteAction {
let routed = match app.current_view {
// A surface opened *from* the dashboard owns the keys while it is up, and Esc closes it
// rather than quitting Luxe — the surface underneath is what the reader came from.
// rather than quitting luxe — the surface underneath is what the reader came from.
ViewMode::Dashboard if !app.dashboard_owns_input() => None,
ViewMode::Dashboard => dashboard_key(app, key),
// The model picker is the last step of setting a provider up, so while it is open it owns
@@ -253,7 +253,7 @@ pub(crate) fn collect_exit_for_tests(app: &mut App, exit: &mut TuiExit) {
/// A surface that picked a file to edit cannot run the editor itself — it needs the terminal back,
/// and only this loop can hand it over — and a worktree cannot be removed while the process stands
/// in it. Collected after engine events as well as keys: the removal is decided by the engine's
/// answer, and one that waited for the next key press left Luxe running until something was typed.
/// answer, and one that waited for the next key press left luxe running until something was typed.
pub(super) fn collect_exit(app: &mut App, exit: &mut TuiExit) {
if let Some(parked) = app.outbox.exit() {
*exit = parked;

View File

@@ -184,6 +184,19 @@ fn setup_takes_the_screen_only_when_no_dashboard_can_point_at_it() {
);
}
/// The first-run questions are for a new machine. Each sign of an earlier install, on its own,
/// keeps them away; so does a terminal nobody is watching.
#[test]
fn the_first_run_is_skipped_by_any_sign_of_an_earlier_install() {
assert!(first_run_from(true, false, false), "a fresh, watched terminal is asked");
assert!(!first_run_from(true, true, false), "a config file means it ran before");
assert!(
!first_run_from(true, false, true),
"a stored login means it ran before, config file or not"
);
assert!(!first_run_from(false, false, false), "nobody is there to answer");
}
/// Every Configuration row is the app's to apply except the editor handoff, which needs the
/// terminal back — so that one, and only that one, ends the TUI.
#[test]

View File

@@ -65,7 +65,7 @@ fn framed_fence(
let ends_at = rendered.iter().map(Line::width).max().unwrap_or(0);
// The language the fence declared, if it declared one worth naming. An
// unlabeled fence gets a rule with nothing on its left rather than the word
// "text", which would be Luxe guessing on the author's behalf.
// "text", which would be luxe guessing on the author's behalf.
let lead = fence_language(code_lang)
.map(|language| {
// The language's own mark where the terminal can draw one, and the bare

View File

@@ -328,6 +328,11 @@ impl MentionFlyoutState {
self.nav.select(filtered_index);
}
/// The cursor's row among the filtered items.
pub(crate) fn cursor(&self) -> usize {
self.nav.selected()
}
/// Get the current query.
pub fn query(&self) -> &str {
self.nav.query()

View File

@@ -30,8 +30,7 @@ pub fn render_mention_flyout(
let empty = match (tab, listed) {
(MentionTab::Files, _) => "No matching files",
(MentionTab::Skills, Some(Listed { entries, .. })) if entries.is_empty() => {
"No skills yet: one is a folder holding a SKILL.md, in ~/.config/luxe/skills/ or the \
project's .luxe/skills/"
"No skills found · add <name>/SKILL.md to ~/.config/luxe/skills/ or .luxe/skills/"
}
(MentionTab::Skills, _) => "No matching skills",
(MentionTab::Mcp, _) => "No matching servers",
@@ -96,6 +95,7 @@ pub fn render_mention_flyout(
detail: None,
// The same height on every tab, so switching tabs never moves the frame
rows: Some(crate::picker::TABBED_ROWS),
list: crate::mouse::OverlayList::Mention,
},
);
}

View File

@@ -186,7 +186,7 @@ fn the_skills_tab_says_what_its_empty_means() {
state
};
let none = drawn(&open(Vec::new()));
assert!(none.contains("No skills yet: one is a folder holding a SKILL.md"), "{none}");
assert!(none.contains("No skills found · add <name>/SKILL.md"), "{none}");
let bare = luxe_core::skills::SkillDoc {
name: "tidy".into(),
description: String::new(),
@@ -196,7 +196,7 @@ fn the_skills_tab_says_what_its_empty_means() {
assert_eq!(state.selected_candidate().unwrap().detail, None, "no description, no detail");
state.set_query("zzzq");
let unmatched = drawn(&state);
assert!(unmatched.contains("No matching skills") && !unmatched.contains("No skills yet"));
assert!(unmatched.contains("No matching skills") && !unmatched.contains("No skills found"));
}
fn server(id: &str, tools: Option<&[&str]>, signed_in: Option<bool>) -> luxe_core::McpServerStatus {
@@ -387,7 +387,7 @@ fn an_empty_tab_says_so_in_the_middle() {
first_list_row + crate::picker::TABBED_ROWS - 1 - said[said.len() - 1],
);
assert!(above.abs_diff(below) <= 1, "centered down: {above} above, {below} below");
assert!(rows.iter().any(|row| row.contains("No skills yet")), "{rows:#?}");
assert!(rows.iter().any(|row| row.contains("No skills found")), "{rows:#?}");
}
/// A match lights where it landed: a skill's name or its description, a GitHub row's title or

View File

@@ -19,6 +19,9 @@ use ratatui::{
};
use unicode_width::UnicodeWidthStr;
mod meta;
use meta::meta_suffix;
/// Panel label, shared by the rendered title and the modal-width computation.
const TITLE: &str = "Select model";
@@ -136,6 +139,12 @@ impl ModelPickerState {
self
}
/// What the picker says above its list.
#[cfg(test)]
pub(crate) fn note(&self) -> &[String] {
&self.note
}
/// Rows the note costs: its lines plus the blank one under them.
fn note_rows(&self) -> u16 {
match self.note.is_empty() {
@@ -215,6 +224,11 @@ impl ModelPickerState {
self.items.get(self.nav.selected_item_index()?)
}
/// The cursor's row among the visible matches.
pub(crate) fn cursor(&self) -> usize {
self.nav.selected()
}
/// Number of visible matches.
pub fn match_count(&self) -> usize {
self.nav.match_count()
@@ -384,18 +398,21 @@ impl ModelPickerState {
.saturating_add(1)
.saturating_sub(capacity)
.min(self.nav.filtered_indices().len().saturating_sub(capacity));
let end = start.saturating_add(capacity).min(self.nav.filtered_indices().len());
let available =
area.width.saturating_sub(2 + crate::widgets::SELECTION_FRAME as u16) as usize;
let total = self.nav.filtered_indices().len();
let end = start.saturating_add(capacity).min(total);
let width = crate::widgets::list_rows_width(area.width, total, area.height);
let available = width.saturating_sub(2 + crate::widgets::SELECTION_FRAME as u16) as usize;
{
let mut regions = hit.borrow_mut();
for offset in 0..end.saturating_sub(start) {
let row_y = area.y.saturating_add(offset as u16);
regions.push(
Rect::new(area.x, row_y, area.width, 1),
Rect::new(area.x, row_y, width, 1),
crate::mouse::MouseTarget::ModelRow(start + offset),
);
}
let list = crate::mouse::OverlayList::Models;
crate::widgets::list_scrollbar(frame, &mut regions, area, list, (start, total), theme);
}
let items: Vec<ListItem> = self.nav.filtered_indices()[start..end]
@@ -438,45 +455,13 @@ impl ModelPickerState {
}
ListItem::new(crate::widgets::selection_row(
spans,
usize::from(area.width),
usize::from(width),
selected,
theme,
))
})
.collect();
frame.render_widget(List::new(items), area);
}
}
/// The parenthesized metadata suffix for a model row (` (200k ctx · reasoning · catalog)`),
/// or empty when the model carries none. Shared by the row renderer and the width calculation
/// so the fitted modal width matches what is drawn.
fn meta_suffix(entry: &ModelEntry) -> String {
let mut meta = Vec::new();
if entry.info.context_window > 0 {
meta.push(format!("{} ctx", human_tokens(entry.info.context_window)));
}
if entry.info.reasoning {
meta.push("reasoning".to_string());
}
match (entry.configured, entry.unverified) {
(_, true) => meta.push("unverified".to_string()),
(false, false) => meta.push("catalog".to_string()),
(true, false) => {}
}
if meta.is_empty() {
String::new()
} else {
format!(" ({})", meta.join(" · "))
}
}
/// `1.0M` / `200k` / `8192` — million-token windows read badly as `1000k`.
fn human_tokens(tokens: u32) -> String {
match tokens {
t if t >= 1_000_000 => format!("{:.1}M", t as f64 / 1_000_000.0),
t if t >= 10_000 => format!("{}k", t / 1_000),
t => t.to_string(),
frame.render_widget(List::new(items), Rect { width, ..area });
}
}

View File

@@ -0,0 +1,35 @@
//! Model row metadata — the context window, reasoning and source notes after a model's name.
use super::ModelEntry;
/// The parenthesized metadata suffix for a model row (` (200k ctx · reasoning · catalog)`),
/// or empty when the model carries none. Shared by the row renderer and the width calculation
/// so the fitted modal width matches what is drawn.
pub(super) fn meta_suffix(entry: &ModelEntry) -> String {
let mut meta = Vec::new();
if entry.info.context_window > 0 {
meta.push(format!("{} ctx", human_tokens(entry.info.context_window)));
}
if entry.info.reasoning {
meta.push("reasoning".to_string());
}
match (entry.configured, entry.unverified) {
(_, true) => meta.push("unverified".to_string()),
(false, false) => meta.push("catalog".to_string()),
(true, false) => {}
}
if meta.is_empty() {
String::new()
} else {
format!(" ({})", meta.join(" · "))
}
}
/// `1.0M` / `200k` / `8192` — million-token windows read badly as `1000k`.
fn human_tokens(tokens: u32) -> String {
match tokens {
t if t >= 1_000_000 => format!("{:.1}M", t as f64 / 1_000_000.0),
t if t >= 10_000 => format!("{}k", t / 1_000),
t => t.to_string(),
}
}

View File

@@ -22,7 +22,7 @@ pub fn icon(mode: &str) -> Icon {
/// The color a mode's composer border and title wear.
///
/// Plan wears its own; every other mode, a custom one included, wears the border accent every
/// other panel does, as its icon is build's, so a session that never plans looks the way Luxe
/// other panel does, as its icon is build's, so a session that never plans looks the way luxe
/// always has.
pub(crate) fn accent(mode: &str, styles: &ThemeStyles) -> Style {
match mode {
@@ -61,7 +61,7 @@ mod tests {
assert_eq!(accent(luxe_core::mode::BUILD, &theme), theme.border_accent);
}
/// A mode Luxe does not know looks like one thing, not half build and half plan.
/// A mode luxe does not know looks like one thing, not half build and half plan.
///
/// The break this catches: the icon fell back to build and the color to plan, so a custom
/// mode wore build's icon in plan's color.

View File

@@ -97,6 +97,31 @@ pub enum ScrollRegionId {
ReviewFeedback,
/// The pull request opening's description.
PullRequestBody,
/// A modal list whose window follows its cursor (walks its rows).
///
/// Args: which list.
OverlayList(OverlayList),
}
/// A modal list whose window follows its cursor, which its wheel and its bar both move.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OverlayList {
/// The model picker
Models,
/// The login wizard's providers
Providers,
/// The command palette
Palette,
/// The theme picker
Themes,
/// The session picker
Sessions,
/// The `/` flyout, its commands or a command's forms
Slash,
/// The `@` flyout's open tab
Mention,
/// Whichever list the configuration surface is showing: settings, or a setup step
Configuration,
}
/// A clickable target, resolved from the cursor position to an action on left-click.

View File

@@ -119,21 +119,21 @@ fn a_notifier_exists_only_when_notifications_are_on_and_knows_about_tmux() {
fn the_sequence_reaches_a_terminal_and_never_a_redirected_stream() {
let notifier = TerminalNotifier { protocol: Protocol::Osc9, tmux: false };
let mut sink = Vec::new();
notifier.write_to(&mut sink, false, "Luxe", "done");
notifier.write_to(&mut sink, false, "luxe", "done");
assert!(sink.is_empty(), "not a terminal: nothing written");
notifier.write_to(&mut sink, true, "Luxe", "done");
assert_eq!(sink, b"\x1b]9;Luxe: done\x07");
notifier.write_to(&mut sink, true, "luxe", "done");
assert_eq!(sink, b"\x1b]9;luxe: done\x07");
}
#[test]
fn each_protocol_is_written_as_its_terminals_expect() {
assert_eq!(
sequence(Protocol::Osc9, false, "Luxe · app", "Turn finished"),
"\x1b]9;Luxe · app: Turn finished\x07"
sequence(Protocol::Osc9, false, "luxe · app", "Turn finished"),
"\x1b]9;luxe · app: Turn finished\x07"
);
assert_eq!(
sequence(Protocol::Osc777, false, "Luxe; app", "Turn failed: a; b"),
"\x1b]777;notify;Luxe, app;Turn failed: a; b\x07",
sequence(Protocol::Osc777, false, "luxe; app", "Turn failed: a; b"),
"\x1b]777;notify;luxe, app;Turn failed: a; b\x07",
"the title cannot carry the field separator; the last field can"
);
}
@@ -141,8 +141,8 @@ fn each_protocol_is_written_as_its_terminals_expect() {
#[test]
fn inside_tmux_the_sequence_is_wrapped_for_passthrough() {
assert_eq!(
sequence(Protocol::Osc9, true, "Luxe", "done"),
"\x1bPtmux;\x1b\x1b]9;Luxe: done\x07\x1b\\"
sequence(Protocol::Osc9, true, "luxe", "done"),
"\x1bPtmux;\x1b\x1b]9;luxe: done\x07\x1b\\"
);
}
@@ -151,10 +151,10 @@ fn inside_tmux_the_sequence_is_wrapped_for_passthrough() {
#[test]
fn outside_text_cannot_end_the_sequence_or_start_its_own() {
let hostile = "boom\x07\x1b]52;c;cHduZWQ=\x07\nsecond line\r\u{9b}31m";
let written = sequence(Protocol::Osc9, false, "Luxe", hostile);
let written = sequence(Protocol::Osc9, false, "luxe", hostile);
let inner = &written["\x1b]9;".len()..written.len() - 1];
assert!(!inner.chars().any(char::is_control), "{written:?}");
assert_eq!(inner, "Luxe: boom ]52;c;cHduZWQ= second line 31m");
assert_eq!(inner, "luxe: boom ]52;c;cHduZWQ= second line 31m");
}
#[test]

View File

@@ -6,11 +6,12 @@
//! name, slash trigger and keywords; the rule under the recent lead is drawn only while the query
//! is empty, because once you type, order is the matcher's.
use crate::glyphs::Icon;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use crate::commands::{Command, Menu, MenuEntry};
use crate::picker::{Slot, Split, Window};
mod render;
pub use render::render_palette;
/// Outcome of a palette keypress.
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -124,6 +125,11 @@ impl PaletteState {
self.selected
}
/// How many entries the query leaves.
pub(crate) fn match_count(&self) -> usize {
self.filtered.len()
}
/// The filtered position the rule under the recent lead follows, while one is drawn.
///
/// Only unfiltered, and only with something on both sides of it.
@@ -192,308 +198,5 @@ impl PaletteState {
}
}
// === Rendering ===
/// Panel label, shared by the rendered title and the modal-width computation.
const TITLE: &str = "Command palette";
/// Rows the list shows before it scrolls.
const MAX_ROWS: usize = 14;
/// The narrowest the detail pane may be and still read as prose rather than a column of words.
const DETAIL_MIN: u16 = 34;
/// The prose width the pane is sized for when there is room, and the list's half matches it.
const DETAIL_WIDTH: u16 = 50;
/// How wide the modal is, and whether it splits for a pane, decided once per frame.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Layout {
modal_width: u16,
/// `None` when there is no room for the pane and the selected summary gets a row instead
split: Option<Split>,
}
/// How many rows the list wants, which with a pane beside it is as many as the longest story any
/// command tells.
fn list_rows(
state: &PaletteState,
layout: &Layout,
theme: &crate::theme::styles::ThemeStyles,
) -> usize {
match layout.split {
// With a pane beside it the modal is as tall as the longest story any command tells, so
// nothing is clipped and it does not jump as the cursor moves from three lines to twelve
Some(Split { pane: width, .. }) => state
.menu
.entries
.iter()
.map(|entry| {
crate::picker::wrapped_rows(
&crate::command_detail::lines(entry, theme),
width.into(),
)
})
.max()
.unwrap_or(0)
.max(MAX_ROWS),
None => state.filtered.len().clamp(1, MAX_ROWS) + usize::from(state.divider().is_some()),
}
}
/// The search field and its rule, with the cursor at the end of the query.
fn render_search(
frame: &mut ratatui::Frame,
area: ratatui::layout::Rect,
state: &PaletteState,
theme: &crate::theme::styles::ThemeStyles,
) {
use ratatui::{
style::Modifier,
text::{Line, Span},
widgets::{Block, Borders, Paragraph},
};
use unicode_width::UnicodeWidthStr;
let search = Paragraph::new(Line::from(vec![
Span::styled(" Search: ", theme.accent.add_modifier(Modifier::BOLD)),
Span::styled(state.query.clone(), theme.text),
]))
.block(Block::default().borders(Borders::BOTTOM).border_style(theme.border_muted));
frame.render_widget(search, area);
let cursor_x = area
.x
.saturating_add(9)
.saturating_add(UnicodeWidthStr::width(state.query.as_str()) as u16)
.min(area.right().saturating_sub(1));
frame.set_cursor_position((cursor_x, area.y));
}
/// Renders the searchable command palette as a centered modal.
pub fn render_palette(
frame: &mut ratatui::Frame,
area: ratatui::layout::Rect,
state: &PaletteState,
theme: &crate::theme::styles::ThemeStyles,
hit: &std::cell::RefCell<crate::mouse::HitRegions>,
) {
use ratatui::{
layout::{Constraint, Direction, Rect},
widgets::{Clear, Paragraph},
};
if area.width < 28 || area.height < 8 {
return;
}
let layout = layout(state, area.width);
let rows = list_rows(state, &layout, theme);
let summary_rows = u16::from(layout.split.is_none());
// Borders, the search field and its rule, the list, the summary when there is no pane, the
// footer
let desired_height = rows as u16 + 4 + summary_rows + crate::widgets::FOOTER_ROWS;
let modal_height = desired_height.max(9).min(area.height.saturating_sub(2));
let modal_area = Rect::new(
area.x + area.width.saturating_sub(layout.modal_width) / 2,
area.y + area.height.saturating_sub(modal_height) / 2,
layout.modal_width,
modal_height,
);
frame.render_widget(Clear, modal_area);
let block = crate::widgets::titled_panel(Icon::Palette.glyph(), TITLE, theme);
let inner = block.inner(modal_area);
frame.render_widget(block, modal_area);
let chunks = ratatui::layout::Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(2),
Constraint::Min(1),
Constraint::Length(summary_rows),
Constraint::Length(crate::widgets::FOOTER_ROWS),
])
.split(inner);
render_search(frame, chunks[0], state, theme);
let body = chunks[1];
let list_area = Rect { width: layout.split.map_or(body.width, |split| split.list), ..body };
render_list(frame, list_area, state, theme, hit);
match (layout.split, state.selected_entry()) {
(Some(split), Some(entry)) => crate::picker::render_pane(
frame,
body,
split.list,
split.pane,
&crate::command_detail::lines(entry, theme),
theme,
),
(Some(split), None) => {
crate::picker::render_pane(frame, body, split.list, split.pane, &[], theme)
}
(None, Some(entry)) => frame.render_widget(
Paragraph::new(crate::command_detail::summary_line(entry, theme)),
chunks[2],
),
(None, None) => {}
}
let count = format!(
"{}/{}",
state.selected.saturating_add(1).min(state.filtered.len()),
state.filtered.len()
);
crate::widgets::render_footer(
frame,
chunks[3],
"enter run · ↑/↓ choose · esc close",
Some(&count),
theme,
);
}
/// The list: a window of rows around the cursor, with the rule under the recent lead when one is
/// drawn, each row a click target for its filtered position.
fn render_list(
frame: &mut ratatui::Frame,
area: ratatui::layout::Rect,
state: &PaletteState,
theme: &crate::theme::styles::ThemeStyles,
hit: &std::cell::RefCell<crate::mouse::HitRegions>,
) {
use ratatui::{
layout::Rect,
text::{Line, Span},
widgets::{List, ListItem, Paragraph},
};
if state.filtered.is_empty() {
frame.render_widget(Paragraph::new(" No matching commands").style(theme.muted), area);
return;
}
let divider = state.divider();
let window = Window::new(state.filtered.len(), divider, state.selected, area.height as usize);
let row_width = usize::from(area.width);
let mut items = Vec::new();
for (offset, slot) in window.slots().enumerate() {
let row_y = area.y.saturating_add(offset as u16);
match slot {
Slot::Rule => items.push(ListItem::new(Line::from(Span::styled(
"─".repeat(row_width),
theme.border_muted,
)))),
Slot::Row(position) => {
hit.borrow_mut().push(
Rect::new(area.x, row_y, area.width, 1),
crate::mouse::MouseTarget::PaletteRow(position),
);
let entry = state.entry_at(position).expect("the window stays inside the list");
let selected = position == state.selected;
items.push(ListItem::new(row(
entry,
&state.matched_at(position),
selected,
row_width,
theme,
)));
}
}
}
frame.render_widget(List::new(items), area);
}
/// One command row: the cursor, the name, its slash trigger, and its key pushed to the right edge.
///
/// Matched characters take the accent in the name and the trigger alike, since both are searched —
/// a row found through its `/auth` must not draw with nothing lit at all.
fn row(
entry: &MenuEntry,
matched: &std::collections::HashSet<usize>,
selected: bool,
row_width: usize,
theme: &crate::theme::styles::ThemeStyles,
) -> ratatui::text::Line<'static> {
use ratatui::{style::Modifier, text::Span};
use unicode_width::UnicodeWidthStr;
let lit = theme.accent.add_modifier(Modifier::BOLD);
let paint = |text: &str, offset: usize, base| -> Vec<Span<'static>> {
text.chars()
.enumerate()
.map(|(index, character)| {
let style = if matched.contains(&(offset + index)) { lit } else { base };
Span::styled(character.to_string(), style)
})
.collect()
};
let name = entry.command.name.as_ref();
let name_chars = name.chars().count();
let mut spans =
vec![Span::styled(crate::glyphs::Mark::Cursor.gutter(selected), theme.accent_on(selected))];
spans.extend(paint(name, 0, theme.label_on(selected)));
let mut used = UnicodeWidthStr::width(name);
if let Some(slash) = entry.command.slash_name() {
spans.push(Span::raw(" "));
// The haystack carries the trigger without its slash, so the slash itself is never lit
// and the trigger's first letter is the character after the name's trailing space
spans.push(Span::styled("/", theme.muted));
spans.extend(paint(slash.trim_start_matches('/'), name_chars + 1, theme.muted));
used += 2 + UnicodeWidthStr::width(slash);
}
let room = row_width.saturating_sub(crate::widgets::SELECTION_FRAME + 2);
if let Some(chord) = entry.chord.as_deref() {
let chord_width = UnicodeWidthStr::width(chord);
if used + 2 + chord_width <= room {
spans.push(Span::raw(" ".repeat(room - used - chord_width)));
spans.push(Span::styled(chord.to_owned(), theme.muted));
}
}
crate::widgets::selection_row(spans, row_width, selected, theme)
}
/// The natural width of a row: its frame, the cursor column, the name, the trigger and the key.
fn row_width(entry: &MenuEntry) -> usize {
use unicode_width::UnicodeWidthStr;
crate::widgets::SELECTION_FRAME
+ 2
+ UnicodeWidthStr::width(entry.command.name.as_ref())
+ entry.command.slash_name().map_or(0, |slash| 2 + UnicodeWidthStr::width(slash))
+ entry.chord.as_deref().map_or(0, |chord| 2 + UnicodeWidthStr::width(chord))
}
/// How wide the modal is, and where it splits, given `available` terminal columns.
///
/// Measured over every entry, not the filtered ones, so the modal holds still as the query
/// narrows. With room for a pane the modal is two equal halves — each as wide as the longest row
/// or a comfortable line of prose, whichever is more — so the rule sits on its middle column, as
/// it does in the slash flyout. The pane appears only when both halves fit.
fn layout(state: &PaletteState, available: u16) -> Layout {
use unicode_width::UnicodeWidthStr;
let widest_row = state.menu.entries.iter().map(row_width).max().unwrap_or(0) as u16;
let total = state.menu.entries.len();
let footer = UnicodeWidthStr::width(
format!(" {total}/{total} · enter run · ↑/↓ choose · esc close ").as_str(),
) as u16;
let title = crate::widgets::panel_title_width(Icon::Palette.glyph(), TITLE) as u16;
let max_width = available.saturating_sub(4).max(28);
// The pane's half carries its gap, its text and a cell before the frame
let half = widest_row.max(title).max(DETAIL_WIDTH + PANE_SPACING);
let fits = |half: u16| Split::around(half).saturating_add(2) <= max_width;
let half = if fits(half) { half } else { max_width.saturating_sub(3) / 2 };
let inner = Split::around(half);
let split = Split::of(inner);
if split.list >= widest_row && split.pane >= DETAIL_MIN {
let modal_width = inner.saturating_add(2).max(footer + 2);
return Layout { modal_width, split: Some(split) };
}
let natural = widest_row.max(footer).max(title);
// Borders, and one cell of breathing room on the right
let modal_width = natural.saturating_add(3).clamp(28, max_width);
Layout { modal_width, split: None }
}
/// What the pane's half spends besides its text: the gap after the rule, and a cell before the
/// frame.
const PANE_SPACING: u16 = crate::picker::PANE_GUTTER;
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,315 @@
//! Palette rendering — the modal, its search field, the list and the detail pane beside it.
//!
//! Reads [`PaletteState`] and draws it; the click targets and the scrollbar it publishes are how
//! the mouse reaches back into the state.
use super::PaletteState;
use crate::commands::MenuEntry;
use crate::glyphs::Icon;
use crate::picker::{Slot, Split, Window};
/// Panel label, shared by the rendered title and the modal-width computation.
const TITLE: &str = "Command palette";
/// Rows the list shows before it scrolls.
const MAX_ROWS: usize = 14;
/// The narrowest the detail pane may be and still read as prose rather than a column of words.
const DETAIL_MIN: u16 = 34;
/// The prose width the pane is sized for when there is room, and the list's half matches it.
const DETAIL_WIDTH: u16 = 50;
/// How wide the modal is, and whether it splits for a pane, decided once per frame.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Layout {
modal_width: u16,
/// `None` when there is no room for the pane and the selected summary gets a row instead
split: Option<Split>,
}
/// How many rows the list wants, which with a pane beside it is as many as the longest story any
/// command tells.
fn list_rows(
state: &PaletteState,
layout: &Layout,
theme: &crate::theme::styles::ThemeStyles,
) -> usize {
match layout.split {
// With a pane beside it the modal is as tall as the longest story any command tells, so
// nothing is clipped and it does not jump as the cursor moves from three lines to twelve
Some(Split { pane: width, .. }) => state
.menu
.entries
.iter()
.map(|entry| {
crate::picker::wrapped_rows(
&crate::command_detail::lines(entry, theme),
width.into(),
)
})
.max()
.unwrap_or(0)
.max(MAX_ROWS),
None => state.filtered.len().clamp(1, MAX_ROWS) + usize::from(state.divider().is_some()),
}
}
/// The search field and its rule, with the cursor at the end of the query.
fn render_search(
frame: &mut ratatui::Frame,
area: ratatui::layout::Rect,
state: &PaletteState,
theme: &crate::theme::styles::ThemeStyles,
) {
use ratatui::{
style::Modifier,
text::{Line, Span},
widgets::{Block, Borders, Paragraph},
};
use unicode_width::UnicodeWidthStr;
let search = Paragraph::new(Line::from(vec![
Span::styled(" Search: ", theme.accent.add_modifier(Modifier::BOLD)),
Span::styled(state.query.clone(), theme.text),
]))
.block(Block::default().borders(Borders::BOTTOM).border_style(theme.border_muted));
frame.render_widget(search, area);
let cursor_x = area
.x
.saturating_add(9)
.saturating_add(UnicodeWidthStr::width(state.query.as_str()) as u16)
.min(area.right().saturating_sub(1));
frame.set_cursor_position((cursor_x, area.y));
}
/// Renders the searchable command palette as a centered modal.
pub fn render_palette(
frame: &mut ratatui::Frame,
area: ratatui::layout::Rect,
state: &PaletteState,
theme: &crate::theme::styles::ThemeStyles,
hit: &std::cell::RefCell<crate::mouse::HitRegions>,
) {
use ratatui::{
layout::{Constraint, Direction, Rect},
widgets::{Clear, Paragraph},
};
if area.width < 28 || area.height < 8 {
return;
}
let layout = layout(state, area.width);
let rows = list_rows(state, &layout, theme);
let summary_rows = u16::from(layout.split.is_none());
// Borders, the search field and its rule, the list, the summary when there is no pane, the
// footer
let desired_height = rows as u16 + 4 + summary_rows + crate::widgets::FOOTER_ROWS;
let modal_height = desired_height.max(9).min(area.height.saturating_sub(2));
let modal_area = Rect::new(
area.x + area.width.saturating_sub(layout.modal_width) / 2,
area.y + area.height.saturating_sub(modal_height) / 2,
layout.modal_width,
modal_height,
);
frame.render_widget(Clear, modal_area);
let block = crate::widgets::titled_panel(Icon::Palette.glyph(), TITLE, theme);
let inner = block.inner(modal_area);
frame.render_widget(block, modal_area);
let chunks = ratatui::layout::Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(2),
Constraint::Min(1),
Constraint::Length(summary_rows),
Constraint::Length(crate::widgets::FOOTER_ROWS),
])
.split(inner);
render_search(frame, chunks[0], state, theme);
let body = chunks[1];
let list_area = Rect { width: layout.split.map_or(body.width, |split| split.list), ..body };
render_list(frame, list_area, state, theme, hit);
match (layout.split, state.selected_entry()) {
(Some(split), Some(entry)) => crate::picker::render_pane(
frame,
body,
split.list,
split.pane,
&crate::command_detail::lines(entry, theme),
theme,
),
(Some(split), None) => {
crate::picker::render_pane(frame, body, split.list, split.pane, &[], theme)
}
(None, Some(entry)) => frame.render_widget(
Paragraph::new(crate::command_detail::summary_line(entry, theme)),
chunks[2],
),
(None, None) => {}
}
let count = format!(
"{}/{}",
state.selected.saturating_add(1).min(state.filtered.len()),
state.filtered.len()
);
crate::widgets::render_footer(
frame,
chunks[3],
"enter run · ↑/↓ choose · esc close",
Some(&count),
theme,
);
}
/// The list: a window of rows around the cursor, with the rule under the recent lead when one is
/// drawn, each row a click target for its filtered position.
fn render_list(
frame: &mut ratatui::Frame,
area: ratatui::layout::Rect,
state: &PaletteState,
theme: &crate::theme::styles::ThemeStyles,
hit: &std::cell::RefCell<crate::mouse::HitRegions>,
) {
use ratatui::{
layout::Rect,
text::{Line, Span},
widgets::{List, ListItem, Paragraph},
};
if state.filtered.is_empty() {
frame.render_widget(Paragraph::new(" No matching commands").style(theme.muted), area);
return;
}
let divider = state.divider();
let window = Window::new(state.filtered.len(), divider, state.selected, area.height as usize);
let lines = Window::lines(state.filtered.len(), divider);
let width = crate::widgets::list_rows_width(area.width, lines, area.height);
let row_width = usize::from(width);
let mut items = Vec::new();
for (offset, slot) in window.slots().enumerate() {
let row_y = area.y.saturating_add(offset as u16);
match slot {
Slot::Rule => items.push(ListItem::new(Line::from(Span::styled(
"─".repeat(row_width),
theme.border_muted,
)))),
Slot::Row(position) => {
hit.borrow_mut().push(
Rect::new(area.x, row_y, width, 1),
crate::mouse::MouseTarget::PaletteRow(position),
);
let entry = state.entry_at(position).expect("the window stays inside the list");
let selected = position == state.selected;
items.push(ListItem::new(row(
entry,
&state.matched_at(position),
selected,
row_width,
theme,
)));
}
}
}
frame.render_widget(List::new(items), Rect { width, ..area });
let list = crate::mouse::OverlayList::Palette;
let shown = (window.top(), lines);
crate::widgets::list_scrollbar(frame, &mut hit.borrow_mut(), area, list, shown, theme);
}
/// One command row: the cursor, the name, its slash trigger, and its key pushed to the right edge.
///
/// Matched characters take the accent in the name and the trigger alike, since both are searched —
/// a row found through its `/auth` must not draw with nothing lit at all.
pub(super) fn row(
entry: &MenuEntry,
matched: &std::collections::HashSet<usize>,
selected: bool,
row_width: usize,
theme: &crate::theme::styles::ThemeStyles,
) -> ratatui::text::Line<'static> {
use ratatui::{style::Modifier, text::Span};
use unicode_width::UnicodeWidthStr;
let lit = theme.accent.add_modifier(Modifier::BOLD);
let paint = |text: &str, offset: usize, base| -> Vec<Span<'static>> {
text.chars()
.enumerate()
.map(|(index, character)| {
let style = if matched.contains(&(offset + index)) { lit } else { base };
Span::styled(character.to_string(), style)
})
.collect()
};
let name = entry.command.name.as_ref();
let name_chars = name.chars().count();
let mut spans =
vec![Span::styled(crate::glyphs::Mark::Cursor.gutter(selected), theme.accent_on(selected))];
spans.extend(paint(name, 0, theme.label_on(selected)));
let mut used = UnicodeWidthStr::width(name);
if let Some(slash) = entry.command.slash_name() {
spans.push(Span::raw(" "));
// The haystack carries the trigger without its slash, so the slash itself is never lit
// and the trigger's first letter is the character after the name's trailing space
spans.push(Span::styled("/", theme.muted));
spans.extend(paint(slash.trim_start_matches('/'), name_chars + 1, theme.muted));
used += 2 + UnicodeWidthStr::width(slash);
}
let room = row_width.saturating_sub(crate::widgets::SELECTION_FRAME + 2);
if let Some(chord) = entry.chord.as_deref() {
let chord_width = UnicodeWidthStr::width(chord);
if used + 2 + chord_width <= room {
spans.push(Span::raw(" ".repeat(room - used - chord_width)));
spans.push(Span::styled(chord.to_owned(), theme.muted));
}
}
crate::widgets::selection_row(spans, row_width, selected, theme)
}
/// The natural width of a row: its frame, the cursor column, the name, the trigger and the key.
fn row_width(entry: &MenuEntry) -> usize {
use unicode_width::UnicodeWidthStr;
crate::widgets::SELECTION_FRAME
+ 2
+ UnicodeWidthStr::width(entry.command.name.as_ref())
+ entry.command.slash_name().map_or(0, |slash| 2 + UnicodeWidthStr::width(slash))
+ entry.chord.as_deref().map_or(0, |chord| 2 + UnicodeWidthStr::width(chord))
}
/// How wide the modal is, and where it splits, given `available` terminal columns.
///
/// Measured over every entry, not the filtered ones, so the modal holds still as the query
/// narrows. With room for a pane the modal is two equal halves — each as wide as the longest row
/// or a comfortable line of prose, whichever is more — so the rule sits on its middle column, as
/// it does in the slash flyout. The pane appears only when both halves fit.
fn layout(state: &PaletteState, available: u16) -> Layout {
use unicode_width::UnicodeWidthStr;
let widest_row = state.menu.entries.iter().map(row_width).max().unwrap_or(0) as u16;
let total = state.menu.entries.len();
let footer = UnicodeWidthStr::width(
format!(" {total}/{total} · enter run · ↑/↓ choose · esc close ").as_str(),
) as u16;
let title = crate::widgets::panel_title_width(Icon::Palette.glyph(), TITLE) as u16;
let max_width = available.saturating_sub(4).max(28);
// The pane's half carries its gap, its text and a cell before the frame
let half = widest_row.max(title).max(DETAIL_WIDTH + PANE_SPACING);
let fits = |half: u16| Split::around(half).saturating_add(2) <= max_width;
let half = if fits(half) { half } else { max_width.saturating_sub(3) / 2 };
let inner = Split::around(half);
let split = Split::of(inner);
if split.list >= widest_row && split.pane >= DETAIL_MIN {
let modal_width = inner.saturating_add(2).max(footer + 2);
return Layout { modal_width, split: Some(split) };
}
let natural = widest_row.max(footer).max(title);
// Borders, and one cell of breathing room on the right
let modal_width = natural.saturating_add(3).clamp(28, max_width);
Layout { modal_width, split: None }
}
/// What the pane's half spends besides its text: the gap after the rule, and a cell before the
/// frame.
const PANE_SPACING: u16 = crate::picker::PANE_GUTTER;

View File

@@ -1,5 +1,7 @@
use super::render::row;
use super::*;
use crate::commands::{CommandContext, CommandRegistry, Surface};
use crate::picker::{Slot, Window};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use luxe_core::keymap::KeyMap;

View File

@@ -100,6 +100,16 @@ impl Window {
Self { divider, start, end: (start + capacity).min(lines) }
}
/// The first line on screen, for the bar beside the window.
pub(crate) fn top(self) -> usize {
self.start
}
/// Every line the list has, a rule included, for the bar beside the window.
pub(crate) fn lines(len: usize, divider: Option<usize>) -> usize {
len + usize::from(divider.is_some())
}
/// Each line on screen, top to bottom.
pub(crate) fn slots(self) -> impl Iterator<Item = Slot> {
(self.start..self.end).map(move |line| match self.divider {

View File

@@ -273,6 +273,7 @@ fn render_picker_draws_title_rows_selection_and_hit_regions() {
divider: None,
detail: None,
rows: None,
list: crate::mouse::OverlayList::Slash,
},
);
})
@@ -343,6 +344,7 @@ fn a_row_too_long_for_the_flyout_clips_rather_than_losing_its_cap() {
divider: None,
detail: None,
rows: None,
list: crate::mouse::OverlayList::Slash,
},
);
})
@@ -400,6 +402,7 @@ fn tabs_sit_above_the_list_and_move_it_down() {
divider: None,
detail: None,
rows: None,
list: crate::mouse::OverlayList::Slash,
},
)
})
@@ -450,6 +453,7 @@ fn tabs_sit_above_the_list_and_move_it_down() {
divider: None,
detail: None,
rows: None,
list: crate::mouse::OverlayList::Slash,
},
)
})

View File

@@ -65,6 +65,8 @@ where
/// Rows the list keeps whatever it holds, so moving between tabs never moves the frame, with
/// an empty or loading message in the middle of them; `None` fits the list to its rows
pub rows: Option<usize>,
/// Which list the wheel and the bar move
pub list: crate::mouse::OverlayList,
}
/// Rows a picker with tabs keeps. Odd, so an empty tab's message has a middle row to sit on; nine,
@@ -127,19 +129,23 @@ pub fn render_picker<Row, Hit>(
};
let capacity = flyout_height.saturating_sub(2 + tab_rows + footer_rows) as usize;
let window = Window::new(view.item_count, divider, view.selected, capacity);
let lines = Window::lines(view.item_count, divider);
let rows_width = crate::widgets::list_rows_width(list_width, lines, capacity as u16);
let items = build_picker_window(
&view,
&window,
hit,
(flyout_area, list_width, pane_width, tab_rows),
(flyout_area, rows_width, pane_width, tab_rows),
theme,
);
let body = render_picker_header(f, flyout_area, &view, theme);
let list_area = Rect { width: list_width.min(body.width), ..body };
match (view.item_count, view.rows) {
(0, Some(_)) => render_centered(f, list_area, view.empty_message, theme),
_ => f.render_widget(List::new(items), list_area),
_ => f.render_widget(List::new(items), Rect { width: rows_width.min(body.width), ..body }),
}
let shown = (window.top(), lines);
crate::widgets::list_scrollbar(f, &mut hit.borrow_mut(), list_area, view.list, shown, theme);
if let (Some(detail), Some(width)) = (view.detail, pane_width) {
render_pane(f, body, list_width, width, &detail(view.selected), theme);
}

View File

@@ -52,7 +52,7 @@ pub(crate) fn wants_attention(pr: &PullRequestStatus) -> bool {
pub(crate) fn report(presence: &PullRequestPresence) -> String {
match presence {
PullRequestPresence::Unknown => {
"Luxe has not heard from GitHub about this branch yet; it is asking now.".into()
"luxe has not heard from GitHub about this branch yet; it is asking now.".into()
}
PullRequestPresence::None => "This branch has no pull request on GitHub.".into(),
PullRequestPresence::Unavailable { reason } => reason.clone(),

View File

@@ -89,7 +89,7 @@ impl FileRefProvider {
/// list was given rather than read.
///
/// Read again off the render thread whenever the picker opens, since a file created or moved
/// outside Luxe never produces a workspace snapshot and would stay impossible to mention.
/// outside luxe never produces a workspace snapshot and would stay impossible to mention.
pub fn set_listing(&mut self, files: Vec<String>) {
if !self.given {
self.set_files(files);

View File

@@ -1,6 +1,6 @@
//! Text selection — grid selection shared by the transcript and the composer.
//!
//! Capturing the mouse means the terminal's own click-drag selection never fires, so Luxe draws
//! Capturing the mouse means the terminal's own click-drag selection never fires, so luxe draws
//! and owns the selection itself: a drag records an anchor and a moving cursor over a surface's
//! rendered lines, the view paints the covered cells, and releasing copies the text out. Positions
//! are `(line, column)` in *terminal cells*, matching what the user actually sees, so wide glyphs

View File

@@ -112,6 +112,11 @@ impl SessionPickerState {
self.nav.query()
}
/// The cursor's row among the visible matches.
pub(crate) fn cursor(&self) -> usize {
self.nav.selected()
}
/// Returns the number of visible matches.
pub fn match_count(&self) -> usize {
self.nav.match_count()
@@ -354,19 +359,23 @@ impl SessionPickerState {
.saturating_add(1)
.saturating_sub(capacity)
.min(self.nav.filtered_indices().len().saturating_sub(capacity));
let end = start.saturating_add(capacity).min(self.nav.filtered_indices().len());
let total = self.nav.filtered_indices().len();
let end = start.saturating_add(capacity).min(total);
let width = crate::widgets::list_rows_width(area.width, total, area.height);
// Two cells for the cursor column, and the frame the selected row is cut with.
let available_width =
area.width.saturating_sub(4 + crate::widgets::SELECTION_FRAME as u16) as usize;
width.saturating_sub(4 + crate::widgets::SELECTION_FRAME as u16) as usize;
{
let mut regions = hit.borrow_mut();
for offset in 0..end.saturating_sub(start) {
let row_y = area.y.saturating_add(offset as u16);
regions.push(
Rect::new(area.x, row_y, area.width, 1),
Rect::new(area.x, row_y, width, 1),
crate::mouse::MouseTarget::SessionRow(start + offset),
);
}
let list = crate::mouse::OverlayList::Sessions;
crate::widgets::list_scrollbar(frame, &mut regions, area, list, (start, total), theme);
}
let items: Vec<ListItem> = self.nav.filtered_indices()[start..end]
@@ -392,13 +401,13 @@ impl SessionPickerState {
Span::styled(gap, background),
Span::styled(session.age.clone(), theme.muted.patch(background)),
],
usize::from(area.width),
usize::from(width),
selected,
theme,
))
})
.collect();
frame.render_widget(List::new(items), area);
frame.render_widget(List::new(items), Rect { width, ..area });
}
/// Renders a multi-line preview of the selected session: a heading, the session title + age,

View File

@@ -130,14 +130,14 @@ pub(crate) fn fill(trigger: &str, words: &[Word<'_>], typed: &str) -> Option<Str
/// What a lit stretch of the composer is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Mark {
/// A slash trigger Luxe answers to: `/diff`
/// A slash trigger luxe answers to: `/diff`
Command,
/// A word one of its forms spells out: the `pr` in `/diff pr 12`
Keyword,
}
/// The stretches of `draft` to light: a known trigger at its start, and the words after it that one
/// of the command's forms spells out. A trigger Luxe does not know lights nothing, which is the cue
/// of the command's forms spells out. A trigger luxe does not know lights nothing, which is the cue
/// that it was mistyped; values (`12`, a path) stay in the text's own color.
///
/// Only the first line: a command is one line, and whatever follows a newline is prose.

View File

@@ -276,6 +276,11 @@ impl SlashFlyoutState {
self.nav.select(filtered_index);
}
/// The cursor's row among the filtered items.
pub(crate) fn cursor(&self) -> usize {
self.nav.selected()
}
/// Get the selected command (if any).
pub fn selected_command(&self) -> Option<&Command> {
if let Some(arguments) = self.arguments.as_ref() {
@@ -361,6 +366,7 @@ pub fn render_slash_flyout(
divider: state.divider(),
detail: Some(&detail),
rows: None,
list: crate::mouse::OverlayList::Slash,
},
);
}
@@ -406,6 +412,7 @@ fn render_arguments(
divider: None,
detail: None,
rows: None,
list: crate::mouse::OverlayList::Slash,
},
);
}

View File

@@ -21,7 +21,7 @@ pub(super) fn fit_segments(
) {
// Least actionable first. Token counts are trivia next to the percentage that says whether the
// window is about to run out; a path repeats the project name; and of the two identities, the
// project is the one that tells two Luxe windows apart, so the branch goes first.
// project is the one that tells two luxe windows apart, so the branch goes first.
let removal_order: &[SegmentKind] = if context_replacement {
&[
SegmentKind::Cwd,

View File

@@ -340,7 +340,7 @@ fn right_segment(module: StatuslineModule, app: &App, palette: Palette) -> Optio
))
}
// The bar's right anchor is where a reader looks to see what is answering, so it answers
// either way. Luxe chooses no model on the reader's behalf, and a module that simply
// either way. luxe chooses no model on the reader's behalf, and a module that simply
// vanished would leave the one session where that matters with nothing to explain a
// refused turn.
StatuslineModule::Model => {

View File

@@ -16,7 +16,7 @@ fn model_and_reasoning_icons_come_from_the_shared_catalog() {
/// A session with no model chosen says so where a session with one names it.
///
/// Luxe picks none on the reader's behalf, so this is a state the bar has to report. It used to
/// luxe picks none on the reader's behalf, so this is a state the bar has to report. It used to
/// drop the module entirely, which left the one reader who needed an explanation — their turn
/// is about to be refused — looking at a bar with nothing on its right-hand end.
#[test]

View File

@@ -1,4 +1,4 @@
//! Tab stops — how wide a tab is, everywhere Luxe draws one.
//! Tab stops — how wide a tab is, everywhere luxe draws one.
//!
//! A tab is the one character the two halves of a render disagree about. `unicode-width` scores it
//! zero, ratatui's buffer drops it, and the terminal would advance the cursor to its own stop if it
@@ -12,7 +12,7 @@
use unicode_width::UnicodeWidthChar;
/// Cells a tab advances to, everywhere Luxe draws one.
/// Cells a tab advances to, everywhere luxe draws one.
///
/// Four rather than eight because a diff already spends cells on two line-number columns and a
/// sign, and a Go or Make file indented four levels at eight cells apiece has nothing left for the

View File

@@ -87,6 +87,16 @@ impl ThemePickerState {
}
}
/// The cursor's row.
pub(crate) fn cursor(&self) -> usize {
self.selected
}
/// How many themes the list holds.
pub(crate) fn len(&self) -> usize {
self.themes.len()
}
/// Move the cursor to `index`, previewing what lands under it.
pub fn select(&mut self, index: usize) -> Option<String> {
(index < self.themes.len() && index != self.selected).then(|| {
@@ -164,6 +174,8 @@ impl ThemePickerState {
self.selected,
usize::from(chunks[0].height),
);
let total = self.themes.len();
let width = crate::widgets::list_rows_width(chunks[0].width, total, chunks[0].height);
let shown: Vec<usize> = window
.slots()
.filter_map(|slot| match slot {
@@ -188,7 +200,7 @@ impl ThemePickerState {
}
ListItem::new(crate::widgets::selection_row(
spans,
usize::from(chunks[0].width),
usize::from(width),
selected,
theme,
))
@@ -200,12 +212,15 @@ impl ThemePickerState {
for (row, &index) in shown.iter().enumerate() {
let row_y = chunks[0].y.saturating_add(row as u16);
regions.push(
Rect::new(chunks[0].x, row_y, chunks[0].width, 1),
Rect::new(chunks[0].x, row_y, width, 1),
crate::mouse::MouseTarget::ThemeRow(index),
);
}
let list = crate::mouse::OverlayList::Themes;
let window = (window.top(), total);
crate::widgets::list_scrollbar(frame, &mut regions, chunks[0], list, window, theme);
}
frame.render_widget(List::new(items), chunks[0]);
frame.render_widget(List::new(items), Rect { width, ..chunks[0] });
crate::widgets::render_footer(frame, chunks[1], FOOTER, None, theme);
}
}

View File

@@ -1,4 +1,4 @@
//! View — ratatui rendering for Luxe's TUI surfaces.
//! View — ratatui rendering for luxe's TUI surfaces.
//!
//! [`render`] routes a frame to the surface the app is on. The chat frame is measured first
//! (`frame_layout`), then drawn back to front: the dock and the conversation, the composer and

View File

@@ -129,7 +129,7 @@ pub(super) fn lines(block: &ConvoBlock, ctx: &BlockContext<'_>) -> Vec<MarkdownL
ConvoBlock::User { text, attached, chips } => user_lines(text, attached, chips, style, ctx),
ConvoBlock::Image { key, .. } => image_lines(key, ctx, style),
ConvoBlock::Assistant(text) => {
// What the agent wrote for Luxe — a remediation report, a draft — is shown where it lands
// What the agent wrote for luxe — a remediation report, a draft — is shown where it lands
let text = &*luxe_core::briefs::for_the_reader(text);
if text.trim().is_empty() {
return Vec::new();

View File

@@ -46,8 +46,8 @@ use {
plan::{plan_follow, plan_row_grants, subject_rows, todo_lines, PLAN_LOOKAHEAD},
plan::{PLAN_ROWS_MAX, PLAN_WRAP_ROWS},
ratatui::style::Modifier,
telemetry::TELEMETRY_LABEL_WIDTH,
telemetry::{telemetry_label_width, telemetry_lines, telemetry_value_width, token_value},
telemetry::{TELEMETRY_LABEL_WIDTH, WIDEST_TELEMETRY_LABEL},
tree::tree_row_line,
};

View File

@@ -225,7 +225,7 @@ fn external_row_line(
///
/// The branch is not decoration here. A worktree's row lists everything Git reports there,
/// including changes this session did not make, and naming the branch is what tells a reader they
/// are looking at another repository's whole working tree rather than at a list of Luxe's edits.
/// are looking at another repository's whole working tree rather than at a list of luxe's edits.
/// A folded place trades it for the count, which is what a heading standing alone has to say, and
/// recedes, since folded reads as dealt with. A branch never takes more than a third of the row:
/// the place is what the row is for.

View File

@@ -45,7 +45,7 @@ pub(super) fn files_row_cap(available_height: usize, reserved: usize) -> usize {
/// reader loses a review they were about to open — the counts and the markers all disappear at
/// once, with nothing left saying there was anything to see.
///
/// The turn's own baseline outlives the commit (Luxe retains the before and after content on disk,
/// The turn's own baseline outlives the commit (luxe retains the before and after content on disk,
/// not a Git range), so the way in is still open; only the sign of it was missing.
fn committed_notice(app: &App) -> Option<Vec<Line<'static>>> {
if !app.worktree_emptied || app.review.last_turn.is_none() {

View File

@@ -60,20 +60,24 @@ pub(super) fn footer_lines(
if lines.len() == 1 {
lines.clear();
}
let rows = telemetry_start
.map(|start| {
vec![
(start + MODEL_ROW, crate::mouse::MouseTarget::DockModelRow),
(start + MODE_ROW, crate::mouse::MouseTarget::DockModeRow),
]
})
.unwrap_or_default();
let rows = telemetry_start.map(clickable_rows).unwrap_or_default();
(lines, rows)
}
/// Where the model and mode rows sit in [`telemetry_lines`], under its heading.
const MODEL_ROW: usize = 1;
const MODE_ROW: usize = 3;
/// The telemetry rows a click lands on, for a block starting at line `start`. The provider and the
/// model are one choice in the picker, so both rows open it.
fn clickable_rows(start: usize) -> Vec<(usize, crate::mouse::MouseTarget)> {
vec![
(start + PROVIDER_ROW, crate::mouse::MouseTarget::DockModelRow),
(start + MODEL_ROW, crate::mouse::MouseTarget::DockModelRow),
(start + MODE_ROW, crate::mouse::MouseTarget::DockModeRow),
]
}
/// Where the provider, model and mode rows sit in [`telemetry_lines`], under its heading.
const PROVIDER_ROW: usize = 1;
const MODEL_ROW: usize = 2;
const MODE_ROW: usize = 4;
/// Builds the live activity line (spinner + label + elapsed) for the dock footer.
///
@@ -108,34 +112,29 @@ fn activity_line(app: &App, presentation: DockPresentation) -> Option<Line<'stat
Some(Line::from(spans))
}
/// The widest label the telemetry blocks draw: a cost breakdown's `cache warming`.
///
/// Every label is one of ours, so the column is sized to them. The provider is a value now, on its
/// own row, so a gateway's long id elides in the value column instead of widening the grid.
pub(super) const WIDEST_TELEMETRY_LABEL: usize = 13;
/// Narrowest the label column in the telemetry blocks gets: its width on the default rail.
///
/// Wide enough to clear the section badge above it, so no value sits under the closing cap of the
/// heading that introduces it, and wide enough for the one label that is not ours: the provider
/// serving the model takes this column, and a provider can be named anything (`foundry-anthropic`
/// is seventeen cells).
/// The widest label and two cells of air, which also clears the section badge above it, so no
/// value sits under the closing cap of the heading that introduces it. Every cell not spent here
/// goes to the values, and the model's name is the one that needs them.
///
/// The room comes out of the value column, and the MODEL row spends what is left on a model's
/// name — so this number is a **split**, cell for cell, between two things that both elide. Across
/// the models.dev snapshot each cell returned to the name fits about three percent more display
/// names, while provider ids cluster well under nineteen and only a gateway prefix pushes one past
/// it. Nineteen is where a `foundry-`-prefixed provider still reads in full and the name keeps the
/// rest.
///
/// Every other value is bounded by what it reports — a percentage, a level, a price — or truncates
/// itself, as the token row does ([`token_value`]). `every_telemetry_row_fits_the_rail` holds every
/// end of that.
///
/// All of that is arithmetic about a forty-cell rail. A rail dragged wider has cells to spare, so
/// [`telemetry_label_width`] grows the column from here rather than holding it.
pub(super) const TELEMETRY_LABEL_WIDTH: usize = 19;
/// Every value is bounded by what it reports — a percentage, a level, a price — or truncates
/// itself, as the token row does ([`token_value`]) and the provider and model names do.
/// `every_telemetry_row_fits_the_rail` holds every end of that. A rail dragged wider has cells to
/// spare, so [`telemetry_label_width`] grows the column from here rather than holding it.
pub(super) const TELEMETRY_LABEL_WIDTH: usize = WIDEST_TELEMETRY_LABEL + 2;
/// The label column for a `row`-wide dock whose longest label is `widest` cells.
///
/// The floor on the default rail, so that rail reads as it always has. Wider, the column grows to
/// seat a provider the floor would cut, and the gap before the values grows with the rail: two
/// cells of air read as a pair at forty cells and as a crowd at eighty. Never past two fifths of
/// the row, which is what keeps the model's name the thing a wide rail spends its room on.
/// The floor on the default rail. Wider, the gap before the values grows with the rail: two cells
/// of air read as a pair at forty cells and as a crowd at eighty. Never past two fifths of the
/// row, which is what keeps the model's name the thing a wide rail spends its room on.
pub(super) fn telemetry_label_width(row: usize, widest: usize) -> usize {
let gap = match row {
0..48 => 2,
@@ -189,27 +188,21 @@ pub(super) fn token_value(totals: &luxe_core::usage::UsageTotals, room: usize) -
/// and its row is the pointer's way into the picker; SESSION waits for a turn to measure, so an
/// idle, pre-turn dock stays short.
pub(super) fn telemetry_lines(app: &App) -> Vec<Line<'static>> {
let status = &app.status;
// Who is serving it takes the label column the rest of the block uses, so MODEL reads as one
// grid with SESSION rather than as a headline with rows under it — and it is the one thing
// about the model that its name does not say. Until the engine has announced a model there
// is no provider to name, so the row falls back to saying what it is; leaving the column
// empty would put the value somewhere no other row's value sits.
let served_by = if status.provider.is_empty() { "model" } else { status.provider.as_str() };
let row = row_width(app);
let column = telemetry_label_width(row, served_by.width());
let mut lines = model_telemetry(app, served_by, row, column);
let column = telemetry_label_width(row, WIDEST_TELEMETRY_LABEL);
let mut lines = model_telemetry(app, row, column);
lines.extend(session_telemetry(app, row, column));
lines
}
/// The MODEL block: who serves it, the model, its thinking level, the mode, and auto-approval.
fn model_telemetry(app: &App, served_by: &str, row: usize, column: usize) -> Vec<Line<'static>> {
fn model_telemetry(app: &App, row: usize, column: usize) -> Vec<Line<'static>> {
let styles = &app.theme_styles;
let status = &app.status;
let mut lines: Vec<Line<'static>> = Vec::new();
lines.push(section_heading_line(Section::Model, app));
lines.push(provider_row(app, row, column));
let room = telemetry_value_width(row, column).saturating_sub(icon_cells(Icon::Model.glyph()));
// Nothing chooses a model for the reader, so this row says which it is either way — and stays
// the affordance that opens the picker, which is the whole reason a reader with none needs it.
@@ -218,7 +211,7 @@ fn model_telemetry(app: &App, served_by: &str, row: usize, column: usize) -> Vec
false => (truncate_cells(&status.model, room), styles.text),
};
lines.push(telemetry_affordance(
served_by,
"model",
icon_label(Icon::Model.glyph(), &name),
ink,
column,
@@ -261,6 +254,27 @@ fn model_telemetry(app: &App, served_by: &str, row: usize, column: usize) -> Vec
lines
}
/// Who serves the model, wearing that provider's mark. Always drawn, so the rows under it keep
/// their place: before the engine names a provider it says `none`, dimmed.
fn provider_row(app: &App, row: usize, column: usize) -> Line<'static> {
let styles = &app.theme_styles;
let provider = app.status.provider.as_str();
let icon = crate::widgets::provider_icon(provider).glyph();
let room = telemetry_value_width(row, column).saturating_sub(icon_cells(icon));
let (name, ink) = match provider.is_empty() {
true => ("none".to_string(), styles.dim),
false => (truncate_cells(provider, room), styles.text),
};
telemetry_affordance(
"provider",
icon_label(icon, &name),
ink,
column,
app,
&crate::mouse::MouseTarget::DockModelRow,
)
}
/// The SESSION block, once a turn has something to measure or someone has joined: the window,
/// tokens, cost, what the review and compaction spent of it, and who's joined.
fn session_telemetry(app: &App, row: usize, column: usize) -> Vec<Line<'static>> {

View File

@@ -233,7 +233,7 @@ fn every_telemetry_value_opens_on_one_column_clear_of_the_badge() {
.unwrap_or_else(|| panic!("no {label} row in {rendered:?}"));
UnicodeWidthStr::width(&row[..row.len() - row.trim_start_matches(label).trim_start().len()])
};
for label in ["anthropic", "thinking", "context", "tokens", "cost", "compaction"] {
for label in ["provider", "model", "thinking", "context", "tokens", "cost", "compaction"] {
assert_eq!(value_at(label), TELEMETRY_LABEL_WIDTH, "{label} in {rendered:?}");
}
@@ -275,10 +275,13 @@ fn the_token_row_sheds_its_footnote_rather_than_the_rail() {
"a session with room keeps its footnote: {large}"
);
// At the top of the range the footnote goes, and the counts never do.
let vast = token_value(&totals(999_900_000, 999_900_000, 999_900_000), room);
assert_eq!(vast, "↑999.9M ↓999.9M", "the two counts are the row");
assert!(vast.width() <= room, "{vast} still overruns");
// The default rail now seats all three even at the top of the range
let vast = totals(999_900_000, 999_900_000, 999_900_000);
assert!(token_value(&vast, room).width() <= room, "the widest still overruns");
// In a tighter row the footnote goes, and the counts never do
let tight = "↑999.9M ↓999.9M ↺999.9M".width() - 1;
assert_eq!(token_value(&vast, tight), "↑999.9M ↓999.9M", "the two counts are the row");
// Nothing to report is not the same as no room to report it.
assert_eq!(token_value(&totals(900_000, 42_000, 0), room), "↑900k ↓42k");
@@ -317,74 +320,85 @@ fn every_telemetry_row_fits_the_rail() {
);
}
// The other end of the same budget: the column has to seat the longest provider anyone has
// put in front of it, or this is all arithmetic about nothing.
assert!(
TELEMETRY_LABEL_WIDTH > "foundry-anthropic".width(),
"a gateway-prefixed provider is cut, which is the whole reason for the column's width"
);
// A gateway-prefixed provider reads in full as a value on the default rail
app.status.provider = "foundry-anthropic".into();
app.status.model = "Claude Fable 5.1 (EU)".into();
let rendered: Vec<String> = telemetry_lines(&app).iter().map(text).collect();
assert!(
rendered.iter().any(|row| row.starts_with("foundry-anthropic ")),
rendered
.iter()
.any(|row| row.starts_with("provider") && row.ends_with("foundry-anthropic")),
"the provider is elided: {rendered:?}"
);
// And the third end: the label column is a split, so taking a cell from the value is
// taking it from a model's name. Both of these elide, and a column that seated every
// provider id ever written would leave the names — where the variety actually is — paying
// for it on every row of every session.
// The label column is paid for out of a model's name, so a routine one fits whole
let name_room = telemetry_value_width(DEFAULT_ROW, TELEMETRY_LABEL_WIDTH)
.saturating_sub(icon_cells(Icon::Model.glyph()));
assert!(
name_room >= "Claude Sonnet 4.6".width(),
name_room >= "Claude Sonnet 4.6 (EU)".width(),
"a routine model name does not fit in {name_room} cells"
);
}
/// The model row is a row like the others: who serves it on the left, what it is on the right.
///
/// It used to be the block's headline — the one line in MODEL and SESSION with no label column,
/// so its icon sat where every other row's *label* starts and the grid broke at the top. The
/// provider is what the column was missing: the one fact about the model its name does not say.
/// The column is sized to our own labels, so it has to seat the widest of them, a cost source's.
#[test]
fn the_model_row_is_labeled_by_who_serves_it() {
fn the_label_column_seats_every_label() {
use luxe_core::usage::UsageSource;
let sources = [UsageSource::Agent, UsageSource::Review, UsageSource::Compaction];
let labels = sources.iter().map(|source| source.label()).chain([
UsageSource::CacheWarm.label(),
"provider",
"approvals",
]);
for label in labels {
assert!(label.width() <= WIDEST_TELEMETRY_LABEL, "{label} is wider than the column");
}
}
/// The provider is a row of its own, label left and value right like every other row, directly
/// above the model it serves, and wears its own mark.
#[test]
fn the_provider_is_its_own_row_above_the_model() {
let mut app = app();
app.status.model = "claude-sonnet-5".into();
app.status.provider = "anthropic".into();
let rendered: Vec<String> = telemetry_lines(&app).iter().map(text).collect();
let model = rendered.iter().find(|row| row.contains("claude-sonnet-5")).expect("a model");
assert!(model.starts_with("anthropic"), "{model:?}");
let model = rendered.iter().position(|row| row.contains("claude-sonnet-5")).expect("a model");
assert!(rendered[model].starts_with("model "), "{:?}", rendered[model]);
assert!(
model.ends_with(&crate::glyphs::icon_label(Icon::Model.glyph(), "claude-sonnet-5")),
"the value keeps its own mark: {model:?}"
rendered[model]
.ends_with(&crate::glyphs::icon_label(Icon::Model.glyph(), "claude-sonnet-5")),
"the value keeps its own mark: {:?}",
rendered[model]
);
let provider = &rendered[model - 1];
let mark = crate::widgets::provider_icon("anthropic").glyph();
assert!(provider.starts_with("provider "), "{provider:?}");
assert!(provider.ends_with(&crate::glyphs::icon_label(mark, "anthropic")), "{provider:?}");
}
/// A provider longer than the column is cut rather than allowed to shove the value out of it —
/// provider ids are whatever a config names them, and the grid is the whole point of the block.
/// A provider longer than its value column is cut at the rail's edge, and keeps the column.
#[test]
fn a_long_provider_is_cut_to_its_column() {
fn a_long_provider_is_cut_in_its_value_column() {
let mut app = app();
app.status.model = "claude-sonnet-5".into();
app.status.provider = "a-self-hosted-gateway".into();
app.status.provider = "a-self-hosted-gateway-with-a-very-long-name".into();
let rendered: Vec<String> = telemetry_lines(&app).iter().map(text).collect();
let model = rendered.iter().find(|row| row.contains(Icon::Model.glyph())).expect("a model");
let opens_at = model.find(Icon::Model.glyph()).expect("the value's mark");
let provider = rendered.iter().find(|row| row.starts_with("provider")).expect("a provider");
let value = provider.trim_start_matches("provider").trim_start();
assert_eq!(
UnicodeWidthStr::width(&model[..opens_at]),
UnicodeWidthStr::width(&provider[..provider.len() - value.len()]),
TELEMETRY_LABEL_WIDTH,
"the value moved off its column: {model:?}"
"the value moved off its column: {provider:?}"
);
assert!(UnicodeWidthStr::width(provider.as_str()) <= DEFAULT_ROW, "{provider:?} overruns");
assert!(!provider.contains("very-long-name"), "nothing was cut: {provider:?}");
}
/// A rail dragged wide gives the grid air and the provider its whole name; the default rail
/// keeps the column it has always had.
/// A rail dragged wide gives the grid air; the default rail keeps its floor.
#[test]
fn a_wide_rail_widens_the_grid_and_seats_a_long_provider() {
fn a_wide_rail_widens_the_grid() {
let mut app = app();
app.status.model = "claude-opus-5".into();
app.status.provider = "foundry-anthropic".into();
@@ -393,7 +407,7 @@ fn a_wide_rail_widens_the_grid_and_seats_a_long_provider() {
telemetry_lines(app)
.iter()
.map(text)
.filter(|row| row.starts_with("foundry-anthropic") || row.starts_with("context"))
.filter(|row| row.starts_with("provider") || row.starts_with("context"))
.map(|row| {
let label = row.split_whitespace().next().unwrap_or_default().to_string();
let value = row[label.len()..].trim_start();
@@ -401,42 +415,35 @@ fn a_wide_rail_widens_the_grid_and_seats_a_long_provider() {
})
.collect()
};
assert_eq!(value_column(&app), [TELEMETRY_LABEL_WIDTH; 2], "the default rail is unchanged");
assert_eq!(value_column(&app), [TELEMETRY_LABEL_WIDTH; 2], "the default rail is the floor");
app.dock_rail.set(crate::workspace_layout::DOCK_MAX_WIDTH);
let wide = value_column(&app);
assert_eq!(wide, [21; 2], "seventeen cells of provider, four of air, one grid: {wide:?}");
app.status.provider = "a-self-hosted-gateway-provider".into();
let rendered: Vec<String> = telemetry_lines(&app).iter().map(text).collect();
assert!(
rendered.iter().any(|row| row.starts_with("a-self-hosted-gateway-provider ")),
"a wide rail seats the whole name: {rendered:?}"
);
for row in &rendered {
assert!(UnicodeWidthStr::width(row.as_str()) <= row_width(&app), "{row:?} overruns");
}
assert_eq!(wide, [WIDEST_TELEMETRY_LABEL + 4; 2], "four cells of air, one grid: {wide:?}");
}
#[test]
fn the_label_column_grows_only_where_there_is_room() {
assert_eq!(telemetry_label_width(40, 17), TELEMETRY_LABEL_WIDTH);
assert_eq!(telemetry_label_width(40, 30), TELEMETRY_LABEL_WIDTH, "cut, as it always was");
let widest = WIDEST_TELEMETRY_LABEL;
assert_eq!(telemetry_label_width(40, widest), TELEMETRY_LABEL_WIDTH);
assert_eq!(telemetry_label_width(40, 30), 16, "never past two fifths of the row");
assert_eq!(telemetry_label_width(78, 8), TELEMETRY_LABEL_WIDTH, "short labels keep the floor");
assert_eq!(telemetry_label_width(78, 17), 21);
assert_eq!(telemetry_label_width(78, widest), widest + 4);
assert_eq!(telemetry_label_width(78, 60), 31, "never past two fifths of the row");
}
/// Before the engine has said anything there is no provider to name, and a blank label column
/// would leave the value sitting where no other row's value sits.
/// Before the engine has said anything there is no provider to name, so the row says `none`
/// rather than vanishing and moving every row under it.
#[test]
fn a_model_with_no_provider_yet_still_labels_its_row() {
fn a_model_with_no_provider_yet_keeps_its_rows() {
let mut app = app();
app.status.model = "claude-sonnet-5".into();
let rendered: Vec<String> = telemetry_lines(&app).iter().map(text).collect();
let model = rendered.iter().find(|row| row.contains("claude-sonnet-5")).expect("a model");
assert!(model.starts_with("model"), "{model:?}");
let model = rendered.iter().position(|row| row.contains("claude-sonnet-5")).expect("a model");
assert!(rendered[model].starts_with("model"), "{:?}", rendered[model]);
assert!(rendered[model - 1].starts_with("provider"), "{rendered:?}");
assert!(rendered[model - 1].ends_with("none"), "{rendered:?}");
}
/// One block for what the session consumed, so the window is not a section of its own.

Some files were not shown because too many files have changed in this diff Show More