Initial public release

Luxe 0.1.0: a coding agent harness for the terminal. See README.md to get started and CHANGELOG.md for releases.
This commit is contained in:
Evan Whittaker
2026-10-17 12:08:30 -05:00
commit 09a7de2520
1730 changed files with 412952 additions and 0 deletions

View File

@@ -0,0 +1,356 @@
//! Configuration rendering — the logotype, and one panel under it.
//!
//! The frame is the surface's contribution: it measures what is about to be shown, gives the
//! logotype whatever height is left, and centers the pair. Everything that appears in the panel —
//! this module's menu, the login wizard, the model picker — is handed the same region, so a row
//! that opens a list does not make the screen jump.
use ratatui::{
layout::{Constraint, Direction, Layout, Rect},
style::Modifier,
text::{Line, Span},
widgets::{Padding, Paragraph, Wrap},
Frame,
};
use unicode_width::UnicodeWidthStr;
use super::{ConfigFile, ConfigurationState, SettingsState, SetupState, Stage};
use crate::glyphs::Icon;
use crate::mouse::{HitRegions, MouseTarget};
use crate::theme::styles::ThemeStyles;
use crate::widgets::{
centered_rect, render_wordmark, selection_block, truncate_end, BannerClock, Wordmark,
SELECTION_FRAME,
};
/// Width of the panel, matching the login wizard's so a row that opens one keeps the same frame.
const PANEL_WIDTH: u16 = 76;
/// Rows an entry occupies: what it is, and what choosing it reaches.
const ENTRY_ROWS: u16 = 2;
/// Narrowest panel worth drawing; below this the terminal is too small for the surface.
const MIN_WIDTH: u16 = 34;
/// Shortest terminal the surface draws in at all.
const MIN_HEIGHT: u16 = 10;
/// Rows of air between the logotype and the panel.
const BANNER_GAP: u16 = 2;
/// The gap a short terminal falls back to, rather than spend a whole logotype size on air.
const TIGHT_BANNER_GAP: u16 = 1;
/// Where the logotype and the panel go, for one draw.
#[derive(Debug, Clone, Copy)]
pub struct SurfaceFrame {
/// The logotype's row band. Zero-height when the terminal has no room for one.
pub banner: Rect,
/// Which drawing of the logotype fits.
pub size: Wordmark,
/// The panel's exact rectangle — not a region to center in.
pub panel: Rect,
}
impl SurfaceFrame {
/// Whether there is a logotype to draw.
pub fn has_banner(self) -> bool {
self.banner.height > 0
}
}
/// Measure the surface for a panel `panel_height` rows tall.
///
/// The panel is the fixed thing here and the logotype gives way to it: a login transcript that
/// grows takes its rows from the mark above it, which is the opposite of the dashboard's rule
/// because this surface is being *used* rather than looked at.
pub fn frame(area: Rect, panel_height: u16) -> SurfaceFrame {
frame_with_width(area, PANEL_WIDTH, panel_height)
}
/// [`frame`] for a panel `panel_width` wide, as the settings pages are.
pub fn frame_with_width(area: Rect, panel_width: u16, panel_height: u16) -> SurfaceFrame {
let width = panel_width.min(area.width.saturating_sub(2)).max(MIN_WIDTH).min(area.width);
let panel_height = panel_height.min(area.height);
let room = |gap: u16| area.height.saturating_sub(panel_height + gap);
let fit = |height: u16| match crate::glyphs::tier() == crate::glyphs::GlyphTier::Ascii {
// The drawn logotype is block elements all the way down, so a terminal promised nothing
// beyond ASCII gets the letter-spaced line, which is plain text.
true => Wordmark::Line,
false => Wordmark::fit(area.width, height),
};
// A row of air is worth having, but not at the price of a whole logotype size — so the gap is
// measured both ways and only tightens when that buys a bigger drawing.
let (size, gap) = match (fit(room(BANNER_GAP)), fit(room(TIGHT_BANNER_GAP))) {
_ if room(TIGHT_BANNER_GAP) == 0 => (Wordmark::Line, 0),
(roomy, tight) if roomy == tight => (roomy, BANNER_GAP),
(_, tight) => (tight, TIGHT_BANNER_GAP),
};
let banner_height = match gap {
0 => 0,
_ => size.height().min(room(gap)),
};
let banner_width = if banner_height > 0 { size.width() } else { 0 };
let block_width = width.max(banner_width).min(area.width);
let block = centered_rect(block_width, banner_height + gap + panel_height, area);
SurfaceFrame {
banner: Rect::new(block.x, block.y, block_width, banner_height),
size,
panel: Rect::new(
block.x + block_width.saturating_sub(width) / 2,
block.y + banner_height + gap,
width,
panel_height,
),
}
}
/// Draw the logotype, when the frame left room for one.
///
/// The same light the dashboard shows, on the same clock: setup is where most people meet the
/// product, and walking here from an animated dashboard should not put the light out mid-stride,
/// which reads as something broken. `banner_animation = false` stills both, in one place.
pub fn render_banner(
f: &mut Frame,
surface: SurfaceFrame,
theme: &ThemeStyles,
clock: BannerClock,
) {
if !surface.has_banner() {
return;
}
render_wordmark(f, surface.banner, theme, surface.size, clock);
}
/// Whether the terminal can hold the surface at all.
pub fn fits(area: Rect) -> bool {
area.width >= MIN_WIDTH && area.height >= MIN_HEIGHT
}
/// What a terminal too small for the surface says instead. Open `settings` hold their keys, since
/// their controls are not drawn either.
pub fn render_too_small(
f: &mut Frame,
area: Rect,
theme: &ThemeStyles,
settings: Option<&SettingsState>,
) {
settings.inspect(|settings| settings.mark_undrawn());
f.render_widget(
Paragraph::new("Resize to continue")
.style(theme.muted)
.alignment(ratatui::layout::Alignment::Center),
centered_rect(area.width.min(18), 1, area),
);
}
impl ConfigurationState {
/// Draw the surface: the logotype, and the menu (or the file list) under it.
pub fn view(
&self,
f: &mut Frame,
area: Rect,
theme: &ThemeStyles,
hit: &std::cell::RefCell<HitRegions>,
clock: BannerClock,
) {
self.note_drawn(fits(area));
if !fits(area) {
render_too_small(f, area, theme, self.settings());
return;
}
if let Some(setup) = self.setup() {
let surface = frame_with_width(
area,
super::setup::render::PANEL_WIDTH,
SetupState::panel_height(area),
);
render_banner(f, surface, theme, clock);
setup.view(f, surface.panel, theme, hit, self.configured());
return;
}
if let (Stage::Settings, Some(settings)) = (self.stage, self.settings()) {
let width = super::settings::render::PANEL_WIDTH;
let surface = frame_with_width(area, width, SettingsState::panel_height(area));
render_banner(f, surface, theme, clock);
settings.view(f, surface.panel, theme, hit);
return;
}
let surface = frame(area, self.panel_height());
render_banner(f, surface, theme, clock);
self.render_panel(f, surface.panel, theme, hit);
}
/// Rows the panel needs: its chrome, a row per list entry and its detail line.
pub fn panel_height(&self) -> u16 {
// Borders (2) + the summary and the blank under it (2) + the footer (2).
const CHROME: u16 = 6;
let rows = match self.stage {
Stage::Menu | Stage::Settings | Stage::Setup => self.choices().len(),
Stage::Files => self.files().len(),
} as u16;
CHROME + rows * ENTRY_ROWS
}
/// The panel itself: what is configured, the list, and how to drive it.
///
/// Nothing here takes typed input, so no cursor position is set — and a frame that sets none
/// leaves the cursor hidden, which is what a menu wants. The wizard parks a block in its corner
/// instead, because it owns a text field and something has to claim the cursor every frame.
fn render_panel(
&self,
f: &mut Frame,
panel: Rect,
theme: &ThemeStyles,
hit: &std::cell::RefCell<HitRegions>,
) {
let block = crate::widgets::titled_panel(Icon::Config.glyph(), self.title(), theme)
.padding(Padding::horizontal(1));
let inner = crate::widgets::render_footed(f, block, panel, self.hint(), None, theme);
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Length(2), Constraint::Min(1)])
.split(inner);
f.render_widget(
Paragraph::new(self.summary_line(theme)).wrap(Wrap { trim: true }),
chunks[0],
);
let rows: Vec<(String, String)> = match self.stage {
Stage::Menu | Stage::Settings | Stage::Setup => self
.choices()
.iter()
.map(|choice| (choice.label().to_string(), choice.detail().to_string()))
.collect(),
Stage::Files => self
.files()
.iter()
.map(|file| (file.name.to_string(), file.detail.to_string()))
.collect(),
};
let selected = self.selected_row();
let mut lines: Vec<Line<'static>> = Vec::new();
let mut regions = hit.borrow_mut();
for (index, (label, detail)) in rows.iter().enumerate() {
let row_y = chunks[1].y.saturating_add(lines.len() as u16);
if row_y < chunks[1].bottom() {
regions.push(
Rect::new(
chunks[1].x,
row_y,
chunks[1].width,
ENTRY_ROWS.min(chunks[1].bottom() - row_y),
),
MouseTarget::ConfigRow(index),
);
}
// One slab for the whole entry rather than one per line: a label and what it reaches
// are a single choice, and two rows capped at the same column read as two of them.
lines.extend(selection_block(
vec![
menu_row(label, index + 1, index == selected, chunks[1].width, theme),
detail_row(detail, chunks[1].width, theme),
],
usize::from(chunks[1].width),
index == selected,
theme,
));
}
drop(regions);
f.render_widget(Paragraph::new(lines), chunks[1]);
}
/// Panel title — the file list is a step inside the surface, and says so.
fn title(&self) -> &'static str {
match self.stage {
Stage::Menu | Stage::Settings | Stage::Setup => "Configuration",
Stage::Files => "Configuration files",
}
}
/// The bottom row: the keys that drive whichever list is showing.
fn hint(&self) -> &'static str {
match self.stage {
Stage::Menu | Stage::Settings | Stage::Setup => "enter open · ↑/↓ choose · esc back",
Stage::Files => "enter open in your editor · ↑/↓ choose · esc back",
}
}
/// The line above the list: what is configured, or where the files are.
fn summary_line(&self, theme: &ThemeStyles) -> Line<'static> {
match self.stage {
// Nothing configured is the one state worth a color: it is the reason this surface
// opened, and every row under it is an answer to it.
Stage::Menu | Stage::Settings | Stage::Setup => match self.is_configured() {
true => Line::from(Span::styled(self.summary(), theme.muted)),
false => Line::from(Span::styled(self.summary(), theme.warning)),
},
Stage::Files => Line::from(Span::styled(files_summary(self.files()), theme.muted)),
}
}
}
/// Where the files are, when they share a directory — the row labels are bare names, so something
/// has to say which directory they are names in.
fn files_summary(files: &[ConfigFile]) -> String {
let mut directories = files.iter().filter_map(|file| file.path.parent());
let shared = directories.next().filter(|first| directories.all(|next| next == *first));
match shared {
Some(directory) => {
format!("Opens in your editor · {}", luxe_core::paths::home_relative(directory))
}
None => "Opens in your editor".to_string(),
}
}
/// Cells an entry's line may fill: the panel, less the slab's own frame.
fn room(width: u16) -> usize {
usize::from(width).saturating_sub(SELECTION_FRAME)
}
/// An entry's first line: the cursor, the label, and the number that runs it.
fn menu_row(
label: &str,
number: usize,
selected: bool,
width: u16,
theme: &ThemeStyles,
) -> Vec<Span<'static>> {
let shortcut = format!("[{number}]");
// The shortcut is the part that has to survive a narrow panel — it is how the row is run — so
// the label gives way to it, keeping a cell of gap between the two.
let label = truncate_end(label, room(width).saturating_sub(2 + shortcut.width() + 1));
let used = 2 + UnicodeWidthStr::width(label.as_str()) + shortcut.width();
let gap = room(width).saturating_sub(used).max(1);
vec![
Span::styled(
crate::glyphs::Mark::Cursor.gutter(selected),
theme.accent.add_modifier(Modifier::BOLD),
),
Span::styled(label, theme.label_on(selected)),
Span::raw(" ".repeat(gap)),
Span::styled(
shortcut,
if selected { theme.text.add_modifier(Modifier::BOLD) } else { theme.muted },
),
]
}
/// The line under a label: what choosing it actually reaches.
///
/// Clipped rather than wrapped. The panel is sized to two rows an entry, so a third line here would
/// push every entry below it out through the bottom border.
fn detail_row(detail: &str, width: u16, theme: &ThemeStyles) -> Vec<Span<'static>> {
// Under the label, which the cursor gutter alone sets in.
const INDENT: usize = 2;
vec![
Span::raw(" ".repeat(INDENT)),
Span::styled(truncate_end(detail, room(width).saturating_sub(INDENT)), theme.muted),
]
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,230 @@
#![allow(clippy::unwrap_used)]
use super::super::tests::{files, key, provider, state};
use super::*;
use crossterm::event::KeyCode;
use luxe_core::auth::CredentialStatus;
use ratatui::{backend::TestBackend, Terminal};
fn theme() -> ThemeStyles {
let registry = luxe_core::theme::ThemeRegistry::new();
let resolved = registry.resolve("nord").expect("nord resolves");
ThemeStyles::from_resolved(&resolved, "nord")
}
fn render_at(state: &ConfigurationState, width: u16, height: u16) -> String {
let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
let theme = theme();
let hit = std::cell::RefCell::new(HitRegions::default());
let clock = BannerClock::new(false);
terminal.draw(|frame| state.view(frame, frame.area(), &theme, &hit, clock)).unwrap();
terminal
.backend()
.buffer()
.content()
.chunks(width as usize)
.map(|row| row.iter().map(|cell| cell.symbol()).collect::<String>())
.collect::<Vec<_>>()
.join("\n")
}
fn render(state: &ConfigurationState) -> String {
render_at(state, 100, 34)
}
/// The logotype on the same clock as the dashboard's. Setup used to hold a still, so walking
/// here from an animated dashboard put the light out.
#[test]
fn the_logotype_moves_on_the_surface_that_is_most_peoples_first_screen() {
let colors = |clock: BannerClock| {
let mut terminal = Terminal::new(TestBackend::new(100, 34)).unwrap();
let theme = theme();
let hit = std::cell::RefCell::new(HitRegions::default());
terminal.draw(|frame| state().view(frame, frame.area(), &theme, &hit, clock)).unwrap();
terminal
.backend()
.buffer()
.content()
.iter()
.filter(|cell| cell.symbol() == "█")
.map(|cell| cell.fg)
.collect::<Vec<_>>()
};
let mid_pass = colors(BannerClock::default().with_tick(24));
assert!(!mid_pass.is_empty(), "the logotype is on screen at all");
assert_ne!(
mid_pass,
colors(BannerClock::default().with_tick(crate::widgets::SHINE_SWEEP_TICKS + 8)),
"the shine has to cross these letters too"
);
// And a reader who turned it off gets the still, on every surface that draws the mark.
assert_eq!(
colors(BannerClock::new(false)),
colors(BannerClock::new(false).with_tick(24)),
"banner_animation = false is one answer for the whole product"
);
}
#[test]
fn the_menu_offers_every_way_in_and_says_what_each_reaches() {
let screen = render(&state());
assert!(screen.contains("Configuration"), "{screen}");
assert!(screen.contains("Sign in to a subscription"), "{screen}");
assert!(screen.contains("ChatGPT Plus or Pro"), "{screen}");
assert!(screen.contains("Add an API key"));
assert!(screen.contains("Connect a local or custom model"));
assert!(screen.contains("Settings"), "{screen}");
assert!(screen.contains("Edit configuration files"));
assert!(screen.contains("[5]"), "the rows are numbered: {screen}");
assert!(screen.contains("enter open"));
}
/// The reason the surface exists has to be on it: someone sent here by the dashboard should not
/// have to infer that nothing is set up.
#[test]
fn an_unconfigured_machine_is_told_so_and_a_configured_one_is_told_what_it_has() {
assert!(render(&state()).contains("No provider is configured yet"));
let signed_in = ConfigurationState::open(
&[provider("openai", CredentialStatus::Env("OPENAI_API_KEY".into()))],
files(),
);
let screen = render(&signed_in);
assert!(screen.contains("Configured: OPENAI"), "{screen}");
// A local server is connected rather than signed in to, and the line that names both
// has one verb to spend — so it spends a true one.
let local = ConfigurationState::open(
&[provider("lmstudio", CredentialStatus::Local("http://127.0.0.1:1234/v1".into()))],
files(),
);
let screen = render(&local);
assert!(screen.contains("local — http://127.0.0.1:1234/v1"), "{screen}");
assert!(!screen.contains("Signed in"), "nothing was signed in to: {screen}");
}
#[test]
fn the_file_list_names_the_files_and_the_directory_they_are_in() {
let mut config = state();
config.on_key(&key(KeyCode::Char('5')));
let screen = render(&config);
assert!(screen.contains("Configuration files"), "{screen}");
assert!(screen.contains("config.json"));
assert!(screen.contains("models.json"));
assert!(screen.contains("auth.json"));
assert!(screen.contains(".config/luxe"), "the bare names need a directory: {screen}");
assert!(screen.contains("enter open in your editor"));
}
/// The logotype is the part that gives way: the panel is what the reader came for.
#[test]
fn the_logotype_takes_whatever_height_the_panel_leaves() {
let state = state();
let tall = frame(Rect::new(0, 0, 100, 40), state.panel_height());
assert!(tall.has_banner(), "a tall terminal has room for the mark");
assert!(
tall.banner.bottom() <= tall.panel.y,
"the mark and the panel must not overlap: {tall:?}"
);
let short = frame(Rect::new(0, 0, 100, state.panel_height()), state.panel_height());
assert!(!short.has_banner(), "a terminal with room for one thing draws the panel");
assert_eq!(short.panel.height, state.panel_height());
}
/// A panel wider than the terminal would draw its right border off screen, and the whole
/// surface with it.
#[test]
fn a_narrow_terminal_still_gets_a_whole_panel() {
let screen = render_at(&state(), 44, 24);
assert!(screen.contains("Sign in to a subscription"), "{screen}");
for row in screen.lines().filter(|row| row.contains('│')) {
assert_eq!(row.matches('│').count() % 2, 0, "an unbalanced border row: {row:?}");
}
}
#[test]
fn a_terminal_too_small_for_the_surface_says_so() {
let screen = render_at(&state(), 20, 6);
assert!(screen.contains("Resize"), "{screen}");
}
/// The cell each of a row's two chamfers sits on, for whichever row carries `needle`.
fn edges(screen: &str, needle: &str) -> (usize, usize) {
let (open, close) = (crate::widgets::Cap::Open.glyph(), crate::widgets::Cap::Close.glyph());
let row = screen.lines().find(|row| row.contains(needle)).expect("the row is on screen");
let at = |cut: Option<usize>| UnicodeWidthStr::width(&row[..cut.expect("a cut")]);
(at(row.find(open)), at(row.rfind(close)))
}
/// The cell `needle` starts on, wherever it is.
fn column(screen: &str, needle: &str) -> usize {
let row = screen.lines().find(|row| row.contains(needle)).expect("the row is on screen");
UnicodeWidthStr::width(&row[..row.find(needle).expect("found above")])
}
/// An entry is a label and what choosing it reaches — one choice, so one slab, capped on the
/// same two columns and with the detail sitting under the label it explains.
#[test]
fn a_chosen_entry_is_cut_as_one_slab() {
crate::glyphs::set_tier(crate::glyphs::GlyphTier::Nerd);
let screen = render(&state());
let (label_open, label_close) = edges(&screen, "Sign in to a subscription");
let (detail_open, detail_close) = edges(&screen, "ChatGPT Plus or Pro");
assert_eq!(label_open, detail_open, "one leading column");
assert_eq!(label_close, detail_close, "one trailing column");
assert_eq!(
column(&screen, "ChatGPT Plus or Pro"),
column(&screen, "Sign in to a subscription"),
"the detail opens on the label's column"
);
}
/// The frame is spent on every entry, chosen or not, so the list holds its columns as the
/// cursor travels rather than stepping sideways under it.
#[test]
fn moving_the_cursor_does_not_move_a_single_column() {
crate::glyphs::set_tier(crate::glyphs::GlyphTier::Nerd);
let resting = render(&state());
let mut moved = state();
moved.on_key(&key(KeyCode::Down));
let moved = render(&moved);
for needle in [
"Sign in to a subscription",
"ChatGPT Plus or Pro",
"Add an API key",
"OpenAI, Anthropic",
"[4]",
] {
assert_eq!(column(&resting, needle), column(&moved, needle), "{needle} moved");
}
}
/// The panel is sized at two rows an entry, so a line that overran its row would wrap and push
/// every entry below it out through the bottom border. Both lines clip, and the slab keeps the
/// closing cap that says where the choice ends.
#[test]
fn a_narrow_panel_clips_an_entry_rather_than_overrunning_it() {
crate::glyphs::set_tier(crate::glyphs::GlyphTier::Nerd);
let mut config = state();
// Onto the longest label on the surface, which is the one with something to clip.
config.on_key(&key(KeyCode::Down));
config.on_key(&key(KeyCode::Down));
let screen = render_at(&config, 44, 24);
assert!(screen.contains('\u{2026}'), "the overrun is marked as clipped: {screen}");
assert!(screen.contains("[3]"), "the number that runs it survives the clip: {screen}");
let (open, close) = edges(&screen, "[3]");
assert!(open < close, "the chosen row is cut at both ends: {screen}");
// Two lines and no more: a wrapped row would put a third between this entry and the next.
let rows: Vec<usize> = screen
.lines()
.enumerate()
.filter(|(_, row)| row.contains(crate::widgets::Cap::Close.glyph()))
.map(|(index, _)| index)
.collect();
assert_eq!(rows.len(), 2, "one slab, two lines: {rows:?}");
assert_eq!(rows[1], rows[0] + 1, "and they are consecutive: {rows:?}");
}

View File

@@ -0,0 +1,406 @@
//! Settings — the Configuration surface's pages of controls over `config.json`.
//!
//! Down the left, the pages ([`luxe_core::settings::Page`]); on the right, the settings on the open
//! one, each with its value and where that value came from. Keys in, a [`ConfigOutcome`] out: the
//! surface never writes a file itself, it asks the app to ([`SettingChange`]), and the app hands it
//! back fresh [`ConfigLayers`] afterwards. That keeps it pure, and it keeps the one place that
//! touches the reader's files in one place.
//!
//! The file stays the source of truth. Every row names its key, `e` opens the file, and a value the
//! project's `.luxe/config.json` sets is shown and explained but not changed from here — writes go
//! to the reader's own file, and a project override would quietly win over them.
pub(super) mod render;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use luxe_core::config::{ConfigLayers, Layer};
use luxe_core::settings::{Control, Page, Setting};
use luxe_core::tool_catalog::{CatalogTool, ToolGroup};
use serde_json::Value;
use std::cell::Cell;
use std::path::PathBuf;
use super::ConfigOutcome;
/// A change the surface asks the app to write to the global config.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SettingChange {
/// Set a key to a value
Set {
/// The key, as a path into the file
path: &'static [&'static str],
/// What to write
value: Value,
},
/// Remove a key, so its default applies again
Reset {
/// The key, as a path into the file
path: &'static [&'static str],
},
/// Turn one tool on or off in `tools.disabled`
Tool {
/// The tool's name
name: &'static str,
/// Whether it should be registered
enabled: bool,
},
}
impl SettingChange {
/// The setting this change is to, when it is one of the table's.
pub fn setting(&self) -> Option<&'static Setting> {
match self {
Self::Set { path, .. } | Self::Reset { path } => luxe_core::settings::find(path),
Self::Tool { .. } => None,
}
}
}
/// One line of a page.
#[derive(Debug, Clone, Copy, PartialEq)]
enum Row {
/// A group's heading, which the cursor steps over
Heading(&'static str),
/// Air between groups
Blank,
/// The tools that cannot be turned off, named once
Essentials,
Setting(&'static Setting),
Tool(&'static CatalogTool),
}
impl Row {
fn selectable(self) -> bool {
matches!(self, Self::Setting(_) | Self::Tool(_))
}
}
/// The line under the list after a change: what happened, or why nothing did.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Notice {
/// What to say
pub text: String,
/// Whether it is a refusal or a failure rather than news
pub warning: bool,
}
/// The settings pages' state.
#[derive(Debug)]
pub struct SettingsState {
page: usize,
/// Index into [`Self::rows`], always on a selectable row when there is one
cursor: usize,
/// First row drawn, kept by the renderer so the cursor stays on screen
scroll: Cell<usize>,
layers: ConfigLayers,
/// The theme in force, by name — the file may not name one, and the desktop may decide it
theme: String,
/// Where writes go, for the header and for `e`
path: PathBuf,
notice: Option<Notice>,
/// Text typed after `/`, filtering every page at once
query: Option<String>,
/// The panel was too small to draw and its notice stood in, so only esc may act
too_small: Cell<bool>,
}
impl SettingsState {
/// Open on the first page.
pub fn open(layers: ConfigLayers, theme: String, path: PathBuf) -> Self {
let mut state = Self {
page: 0,
cursor: 0,
scroll: Cell::new(0),
layers,
theme,
path,
notice: None,
query: None,
too_small: Cell::new(false),
};
state.settle();
state
}
/// Open on `page`.
pub fn open_on(mut self, page: Page) -> Self {
self.select_page(Page::ALL.iter().position(|candidate| *candidate == page).unwrap_or(0));
self
}
/// Take the files as they are now, after a write or a theme change, keeping the reader's place.
pub fn refresh(&mut self, layers: ConfigLayers, theme: String) {
self.layers = layers;
self.theme = theme;
}
/// Say something under the list until the next keypress.
pub fn set_notice(&mut self, notice: Notice) {
self.notice = Some(notice);
}
/// Whether a search is open, which Esc closes before it leaves the pages.
pub fn searching(&self) -> bool {
self.query.is_some()
}
/// The page showing.
pub fn page(&self) -> Page {
Page::ALL[self.page]
}
/// Show page `index`, cursor on its first setting.
pub fn select_page(&mut self, index: usize) {
self.page = index.min(Page::ALL.len() - 1);
self.query = None;
self.cursor = 0;
self.scroll.set(0);
self.settle();
}
/// Put the cursor on the `index`th selectable row (a click, or the pointer passing over it).
pub fn select(&mut self, index: usize) {
if let Some(row) = self.selectable().get(index) {
self.cursor = *row;
}
}
/// The cursor's position among the selectable rows.
pub fn selected(&self) -> usize {
self.selectable().iter().position(|row| *row == self.cursor).unwrap_or(0)
}
/// Handle a keypress.
pub fn on_key(&mut self, key: &KeyEvent) -> ConfigOutcome {
self.notice = None;
// the controls are not drawn, so none of them may change anything
if self.too_small.get() && key.code != KeyCode::Esc {
return ConfigOutcome::Consumed;
}
let plain = key.modifiers.is_empty() || key.modifiers == KeyModifiers::SHIFT;
if let Some(query) = self.query.as_mut() {
match key.code {
KeyCode::Esc => {
self.query = None;
self.cursor = 0;
self.settle();
return ConfigOutcome::Consumed;
}
KeyCode::Backspace => {
query.pop();
self.cursor = 0;
self.settle();
return ConfigOutcome::Consumed;
}
KeyCode::Char(character) if plain && character != ' ' => {
query.push(character);
self.cursor = 0;
self.settle();
return ConfigOutcome::Consumed;
}
_ => {}
}
}
match key.code {
KeyCode::Up | KeyCode::Char('k') if plain => self.step(-1),
KeyCode::Down | KeyCode::Char('j') if plain => self.step(1),
KeyCode::Tab => self.select_page((self.page + 1) % Page::ALL.len()),
KeyCode::BackTab => {
self.select_page((self.page + Page::ALL.len() - 1) % Page::ALL.len())
}
KeyCode::Enter | KeyCode::Char(' ') | KeyCode::Right | KeyCode::Char('l') => {
return self.activate_forward(true)
}
KeyCode::Left | KeyCode::Char('h') => return self.activate_forward(false),
KeyCode::Char('r') if plain => return self.reset(),
KeyCode::Char('e') if plain => return ConfigOutcome::EditFile(self.path.clone()),
KeyCode::Char('/') if plain => {
self.query = Some(String::new());
self.cursor = 0;
self.settle();
}
KeyCode::Char(digit @ '1'..='9') if plain => {
let index = digit as usize - '1' as usize;
if index < Page::ALL.len() {
self.select_page(index);
}
}
_ => {}
}
ConfigOutcome::Consumed
}
/// Change the setting under the cursor the way Enter does (a click lands here too).
pub fn activate(&mut self) -> ConfigOutcome {
self.activate_forward(true)
}
fn activate_forward(&mut self, forward: bool) -> ConfigOutcome {
match self.rows().get(self.cursor).copied() {
Some(Row::Setting(setting)) => {
// checked before the theme row opens its picker, so it is guarded here like the rest
let (layer, current) = setting.current(&self.layers);
if layer == Layer::Project {
return self.refuse_project(setting.label);
}
if setting.control == Control::Theme {
return ConfigOutcome::PickTheme;
}
let Some(value) = setting.stepped(&current, forward) else {
return ConfigOutcome::Consumed;
};
// Back to the default is the key gone, so the file says only what was chosen
let change = match value == setting.default_value() {
true => SettingChange::Reset { path: setting.path },
false => {
SettingChange::Set { path: setting.path, value: setting.file_value(value) }
}
};
ConfigOutcome::Write(change)
}
Some(Row::Tool(tool)) => {
let (layer, enabled) = self.tool_state(tool);
if layer == Layer::Project {
return self.refuse_project(tool.name);
}
ConfigOutcome::Write(SettingChange::Tool { name: tool.name, enabled: !enabled })
}
_ => ConfigOutcome::Consumed,
}
}
/// `r`: put the default back by removing what the reader's own file says.
fn reset(&mut self) -> ConfigOutcome {
let layer = match self.rows().get(self.cursor).copied() {
Some(Row::Setting(setting)) => {
let (layer, _) = setting.current(&self.layers);
if layer == Layer::Global {
return ConfigOutcome::Write(SettingChange::Reset { path: setting.path });
}
layer
}
Some(Row::Tool(tool)) => {
let (layer, _) = self.tool_state(tool);
if layer == Layer::Global {
return ConfigOutcome::Write(SettingChange::Tool {
name: tool.name,
enabled: true,
});
}
layer
}
_ => return ConfigOutcome::Consumed,
};
let text = match layer {
Layer::Project => "This project's .luxe/config.json sets it; change it there.",
_ => "Already the default.",
};
self.notice = Some(Notice { text: text.into(), warning: false });
ConfigOutcome::Consumed
}
fn refuse_project(&mut self, what: &str) -> ConfigOutcome {
self.notice = Some(Notice {
text: format!(
"{what} is set by this project's .luxe/config.json, which wins over yours. \
Change it there."
),
warning: true,
});
ConfigOutcome::Consumed
}
/// Whether `tool` is on, and which file said so.
///
/// `tools.disabled` is a union of the two files rather than an override, so a tool either file
/// turns off is off; the project's word is reported first because only that one cannot be
/// undone from here.
fn tool_state(&self, tool: &CatalogTool) -> (Layer, bool) {
let lists = |document: &Option<Value>| {
document
.as_ref()
.and_then(|document| luxe_core::config::value_at(document, &["tools", "disabled"]))
.and_then(Value::as_array)
.is_some_and(|list| list.iter().any(|entry| entry.as_str() == Some(tool.name)))
};
match (lists(&self.layers.project), lists(&self.layers.global)) {
(true, _) => (Layer::Project, false),
(false, true) => (Layer::Global, false),
(false, false) => (Layer::Default, true),
}
}
/// The lines of the page showing, or every match when a search is open.
fn rows(&self) -> Vec<Row> {
if let Some(query) = &self.query {
return search(query);
}
let page = self.page();
let mut rows = Vec::new();
if page == Page::Tools {
rows.push(Row::Essentials);
for group in ToolGroup::OFFERED {
rows.push(Row::Blank);
rows.push(Row::Heading(group.heading()));
rows.extend(
luxe_core::tool_catalog::toggleable()
.into_iter()
.filter(|tool| tool.group == group)
.map(Row::Tool),
);
}
rows.push(Row::Blank);
rows.push(Row::Heading("OPTIONS"));
}
rows.extend(luxe_core::settings::on(page).map(Row::Setting));
rows
}
/// Indexes into [`Self::rows`] the cursor may rest on.
fn selectable(&self) -> Vec<usize> {
self.rows().iter().enumerate().filter(|(_, row)| row.selectable()).map(|(i, _)| i).collect()
}
fn step(&mut self, delta: isize) {
let selectable = self.selectable();
let Some(at) = selectable.iter().position(|row| *row == self.cursor) else {
self.settle();
return;
};
let next = at.saturating_add_signed(delta).min(selectable.len().saturating_sub(1));
self.cursor = selectable[next];
}
/// Move the cursor onto a selectable row, the first one from where it is.
fn settle(&mut self) {
let selectable = self.selectable();
if !selectable.contains(&self.cursor) {
self.cursor = selectable
.iter()
.copied()
.find(|row| *row >= self.cursor)
.unwrap_or(selectable.first().copied().unwrap_or(0));
}
}
}
/// Every setting and tool whose name, label or key holds `query`, across all pages.
fn search(query: &str) -> Vec<Row> {
let wanted = query.to_lowercase();
let hits = |text: &str| text.to_lowercase().contains(&wanted);
let mut rows: Vec<Row> = luxe_core::settings::SETTINGS
.iter()
.filter(|setting| hits(setting.label) || hits(&setting.key()))
.map(Row::Setting)
.collect();
rows.extend(
luxe_core::tool_catalog::toggleable()
.into_iter()
.filter(|tool| hits(tool.name) || hits(tool.summary))
.map(Row::Tool),
);
rows
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,428 @@
//! Settings rendering — the pages down the left, the controls on the right, and what the one under
//! the cursor does underneath.
use ratatui::{
layout::Rect,
style::{Modifier, Style},
text::{Line, Span},
widgets::{Padding, Paragraph, Wrap},
Frame,
};
use unicode_width::UnicodeWidthStr;
use super::{Row, SettingsState};
use crate::glyphs::{Icon, Mark};
use crate::mouse::{HitRegions, MouseTarget};
use crate::theme::styles::{Depth, ThemeStyles};
use crate::widgets::{badge, selection_row, truncate_end, SELECTION_FRAME};
use luxe_core::config::Layer;
use luxe_core::settings::{Control, Page, Setting};
/// Width of the page list, its own frame included.
const NAV_WIDTH: u16 = 24;
/// Rows under the list for the one under the cursor: a rule, its name and source, its words.
const DETAIL_ROWS: u16 = 5;
/// Cells the label column takes before the value.
const LABEL_WIDTH: usize = 32;
/// Cells the value takes at the right, before the source.
const VALUE_WIDTH: usize = 16;
/// Cells the source takes at the margin: `default`, `global`, `project`.
const SOURCE_WIDTH: usize = 7;
/// Widest the panel grows.
pub(in crate::configuration) const PANEL_WIDTH: u16 = 124;
/// The keys, for the footer.
const HINT: &str = "space change · ←/→ step · r reset · e open the file · / search · tab pages · \
esc back";
impl SettingsState {
/// Rows the panel would like: the whole screen, less the one-line wordmark and its gap.
pub fn panel_height(area: Rect) -> u16 {
area.height.saturating_sub(3).min(44)
}
/// The surface had no room for the panel at all, so its keys wait like a too-small panel's.
pub(crate) fn mark_undrawn(&self) {
self.too_small.set(true);
}
/// Draw the panel into exactly `panel`.
pub fn view(
&self,
f: &mut Frame,
panel: Rect,
theme: &ThemeStyles,
hit: &std::cell::RefCell<HitRegions>,
) {
let block = crate::widgets::titled_panel(Icon::Config.glyph(), "Settings", theme)
.padding(Padding::horizontal(1));
let inner = crate::widgets::render_footed(f, block, panel, HINT, None, theme);
let too_small = inner.width < NAV_WIDTH + 30 || inner.height < 8;
self.too_small.set(too_small);
if too_small {
// said, rather than an empty box whose controls still answer keys nobody can see
let notice = vec![
Line::from(Span::styled("Make the window bigger", theme.error)),
Line::from(Span::styled("Only esc acts until it fits", theme.muted)),
];
let at = Rect { height: inner.height.min(2), ..inner };
let centered = Paragraph::new(notice).alignment(ratatui::layout::Alignment::Center);
f.render_widget(centered, at);
return;
}
let nav = Rect { width: NAV_WIDTH, ..inner };
self.render_nav(f, nav, theme, hit);
let rule_x = nav.right() + 1;
f.render_widget(
Paragraph::new(vec![Line::from("│"); usize::from(inner.height)])
.style(theme.border_muted),
Rect::new(rule_x, inner.y, 1, inner.height),
);
let body =
Rect::new(rule_x + 2, inner.y, inner.right().saturating_sub(rule_x + 2), inner.height);
self.render_body(f, body, theme, hit);
}
fn render_nav(
&self,
f: &mut Frame,
nav: Rect,
theme: &ThemeStyles,
hit: &std::cell::RefCell<HitRegions>,
) {
let mut lines = vec![Line::default()];
let mut regions = hit.borrow_mut();
for (index, page) in Page::ALL.iter().enumerate() {
let chosen = self.query.is_none() && index == self.page;
let y = nav.y + lines.len() as u16;
if y < nav.bottom() {
regions.push(Rect::new(nav.x, y, nav.width, 1), MouseTarget::ConfigPage(index));
}
let spans = vec![
Span::styled(page_icon(*page), if chosen { theme.accent } else { theme.muted }),
Span::raw(crate::glyphs::icon_gap()),
Span::styled(
page.label(),
if chosen { theme.accent.add_modifier(Modifier::BOLD) } else { theme.text },
),
Span::styled(format!(" {}", index + 1), theme.dim),
];
lines.push(selection_row(spans, usize::from(nav.width), chosen, theme));
}
drop(regions);
f.render_widget(Paragraph::new(lines), nav);
}
fn render_body(
&self,
f: &mut Frame,
body: Rect,
theme: &ThemeStyles,
hit: &std::cell::RefCell<HitRegions>,
) {
let width = usize::from(body.width);
let canvas = theme.background.bg.unwrap_or(theme.slab.canvas);
// The heading: the page, or the search, and where writes go
let mut heading = match &self.query {
Some(query) => {
let mut spans = badge("SEARCH", Depth::Hero, canvas, theme);
spans.push(Span::styled(format!(" {query}"), theme.text));
spans.push(Span::styled(" ", Style::new().bg(theme.text.fg.unwrap_or_default())));
spans
}
None => badge(page_heading(self.page()), Depth::Hero, canvas, theme),
};
let path = luxe_core::paths::home_relative(&self.path);
let pad = width.saturating_sub(spans_width(&heading) + path.width());
heading.push(Span::raw(" ".repeat(pad)));
heading.push(Span::styled(path, theme.dim));
f.render_widget(Paragraph::new(Line::from(heading)), Rect { height: 1, ..body });
let list =
Rect { y: body.y + 2, height: body.height.saturating_sub(2 + DETAIL_ROWS), ..body };
self.render_rows(f, list, theme, hit);
self.render_detail(
f,
Rect { y: list.bottom(), height: body.bottom().saturating_sub(list.bottom()), ..body },
theme,
);
}
fn render_rows(
&self,
f: &mut Frame,
list: Rect,
theme: &ThemeStyles,
hit: &std::cell::RefCell<HitRegions>,
) {
let rows = self.rows();
if rows.is_empty() {
f.render_widget(Paragraph::new(Span::styled(" Nothing matches.", theme.muted)), list);
return;
}
let height = usize::from(list.height).max(1);
// Keep the cursor in view with a row of context either side where there is one
let mut scroll = self.scroll.get().min(rows.len().saturating_sub(1));
if self.cursor < scroll + 1 {
scroll = self.cursor.saturating_sub(1);
} else if self.cursor + 2 > scroll + height {
scroll = (self.cursor + 2).saturating_sub(height);
}
scroll = scroll.min(rows.len().saturating_sub(height));
self.scroll.set(scroll);
let width = usize::from(list.width);
let selectable = self.selectable();
let mut regions = hit.borrow_mut();
let lines: Vec<Line<'static>> = rows
.iter()
.enumerate()
.skip(scroll)
.take(height)
.map(|(index, row)| {
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),
);
}
self.row_line(*row, width, selected, theme)
})
.collect();
drop(regions);
f.render_widget(Paragraph::new(lines), list);
}
fn row_line(
&self,
row: Row,
width: usize,
selected: bool,
theme: &ThemeStyles,
) -> Line<'static> {
let canvas = theme.background.bg.unwrap_or(theme.slab.canvas);
match row {
Row::Blank => Line::default(),
Row::Heading(label) => {
let mut spans = vec![Span::raw(" ")];
spans.extend(badge(label, Depth::Recessed, canvas, theme));
Line::from(spans)
}
Row::Essentials => {
let names = luxe_core::config::ESSENTIAL_TOOLS.join(" · ");
let mut spans = vec![Span::raw(" "), Span::styled(names, theme.muted)];
let tail = "always on";
// Where a control row's value lands, its frame's inset included
let at = value_column(width) + crate::widgets::SELECTION_INSET;
let pad = at.saturating_sub(spans_width(&spans));
spans.push(Span::raw(" ".repeat(pad)));
spans.push(Span::styled(tail, theme.muted));
Line::from(spans)
}
Row::Setting(setting) => {
let (layer, value) = setting.current(&self.layers);
let label = Span::styled(setting.label.to_string(), label_style(selected, theme));
let control = self.setting_value(setting, &value, selected, theme);
control_row(label, None, control, layer, width, selected, theme)
}
Row::Tool(tool) => {
let (layer, enabled) = self.tool_state(tool);
let label = Span::styled(tool.name.to_string(), label_style(selected, theme));
let summary = Span::styled(tool.summary.to_string(), theme.muted);
control_row(
label,
Some(summary),
toggle(enabled, theme),
layer,
width,
selected,
theme,
)
}
}
}
fn setting_value(
&self,
setting: &Setting,
value: &serde_json::Value,
selected: bool,
theme: &ThemeStyles,
) -> Vec<Span<'static>> {
match setting.control {
Control::Toggle { .. } => toggle(value.as_bool().unwrap_or(false), theme),
Control::Choice { .. } | Control::StartScreen => {
let text = value.as_str().unwrap_or_default().replace('_', " ");
let arrows = if selected { theme.accent } else { theme.dim };
vec![
Span::styled("‹ ", arrows),
Span::styled(text, theme.text),
Span::styled(" ›", arrows),
]
}
Control::Theme => vec![
Span::styled(self.theme.clone(), theme.text),
Span::styled(" ›", if selected { theme.accent } else { theme.dim }),
],
}
}
/// What the row under the cursor is, what it does, and when a change is felt.
fn render_detail(&self, f: &mut Frame, area: Rect, theme: &ThemeStyles) {
if area.height == 0 {
return;
}
let width = usize::from(area.width);
let mut lines = vec![Line::from(Span::styled("─".repeat(width), theme.border_muted))];
match self.rows().get(self.cursor).copied() {
Some(Row::Setting(setting)) => {
let (layer, _) = setting.current(&self.layers);
lines.push(Line::from(vec![
Span::styled(setting.label, theme.text.add_modifier(Modifier::BOLD)),
Span::styled(format!(" {}", setting.key()), theme.accent),
Span::styled(format!(" · {}", setting.applies.note()), theme.muted),
Span::styled(source_note(layer), layer_style(layer, theme)),
]));
lines.push(Line::from(Span::styled(
setting.description().unwrap_or_default().to_string(),
theme.text,
)));
}
Some(Row::Tool(tool)) => {
let (layer, _) = self.tool_state(tool);
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),
];
head.push(Span::styled(source_note(layer), layer_style(layer, theme)));
lines.push(Line::from(head));
let mut words = tool.detail.to_string();
if let Some(needs) = tool.needs {
words.push_str(&format!(" Registers only where there is {needs}."));
}
lines.push(Line::from(Span::styled(words, theme.text)));
}
_ => {}
}
let mut paragraph_lines = lines;
if let Some(notice) = &self.notice {
// The notice replaces the description's last line, so a write is acknowledged where
// the reader is already looking
let style = if notice.warning { theme.warning } else { theme.success };
paragraph_lines.truncate(2);
paragraph_lines.push(Line::from(Span::styled(notice.text.clone(), style)));
}
f.render_widget(Paragraph::new(paragraph_lines).wrap(Wrap { trim: true }), area);
}
}
/// One control: label (and a summary for a tool), the value, and where the value came from.
fn control_row(
label: Span<'static>,
summary: Option<Span<'static>>,
value: Vec<Span<'static>>,
layer: Layer,
width: usize,
selected: bool,
theme: &ThemeStyles,
) -> Line<'static> {
let cursor = Span::styled(
if selected { Mark::Cursor.glyph() } else { " " },
theme.accent.add_modifier(Modifier::BOLD),
);
let at = value_column(width);
let mut spans = vec![cursor, Span::raw(" ")];
let label_width = match summary {
Some(_) => 18,
None => LABEL_WIDTH.min(at.saturating_sub(4)),
};
let label_text = truncate_end(&label.content, label_width.saturating_sub(1));
let label_pad = label_width.saturating_sub(label_text.width());
spans.push(Span::styled(label_text, label.style));
spans.push(Span::raw(" ".repeat(label_pad)));
if let Some(summary) = summary {
let room = at.saturating_sub(spans_width(&spans) + 2);
spans.push(Span::styled(truncate_end(&summary.content, room), summary.style));
}
let pad = at.saturating_sub(spans_width(&spans));
spans.push(Span::raw(" ".repeat(pad)));
let value_width = spans_width(&value);
spans.extend(value);
spans.push(Span::raw(" ".repeat(VALUE_WIDTH.saturating_sub(value_width) + 1)));
let (source, style) = match layer {
Layer::Default => ("default", theme.dim),
Layer::Global => ("global", theme.text),
Layer::Project => ("project", theme.warning),
};
spans.push(Span::styled(source, style));
selection_row(spans, width, selected, theme)
}
/// Where the value column starts, measured inside a row's frame.
fn value_column(width: usize) -> usize {
width.saturating_sub(SELECTION_FRAME + VALUE_WIDTH + 1 + SOURCE_WIDTH)
}
fn toggle(on: bool, theme: &ThemeStyles) -> Vec<Span<'static>> {
match on {
true => vec![Span::styled("● on", theme.success)],
false => vec![Span::styled("○ off", theme.muted)],
}
}
fn label_style(selected: bool, theme: &ThemeStyles) -> Style {
match selected {
true => theme.accent.add_modifier(Modifier::BOLD),
false => theme.text,
}
}
fn layer_style(layer: Layer, theme: &ThemeStyles) -> Style {
match layer {
Layer::Project => theme.warning,
_ => theme.muted,
}
}
/// Where the value came from, said once in the detail.
fn source_note(layer: Layer) -> &'static str {
match layer {
Layer::Default => " · the default",
Layer::Global => " · set in your config.json",
Layer::Project => " · set by this project's .luxe/config.json",
}
}
fn page_heading(page: Page) -> &'static str {
match page {
Page::Appearance => "APPEARANCE",
Page::Conversation => "CONVERSATION",
Page::Layout => "DOCK & STATUSLINE",
Page::Tools => "TOOLS",
Page::Agent => "AGENT",
}
}
fn page_icon(page: Page) -> &'static str {
match page {
Page::Appearance => Icon::Thinking.glyph(),
Page::Conversation => Icon::Conversation.glyph(),
Page::Layout => Icon::Context.glyph(),
Page::Tools => Icon::ToolGeneric.glyph(),
Page::Agent => Icon::ModeBuild.glyph(),
}
}
fn spans_width(spans: &[Span<'_>]) -> usize {
spans.iter().map(|span| span.content.width()).sum()
}

View File

@@ -0,0 +1,189 @@
#![allow(clippy::unwrap_used)]
use super::*;
fn key(code: KeyCode) -> KeyEvent {
KeyEvent::new(code, KeyModifiers::NONE)
}
fn state(global: Value, project: Option<Value>) -> SettingsState {
SettingsState::open(
ConfigLayers { global: Some(global), project },
"luxe".into(),
PathBuf::from("/home/dev/.config/luxe/config.json"),
)
}
fn cursor_on(state: &mut SettingsState, wanted: Row) {
let rows = state.rows();
let at = rows.iter().position(|row| *row == wanted).expect("the row is on this page");
state.cursor = at;
}
#[test]
fn a_toggle_writes_its_flip_and_a_flip_back_to_the_default_removes_the_key() {
let mut settings = state(serde_json::json!({}), None).open_on(Page::Layout);
let mouse = luxe_core::settings::find(&["mouse"]).unwrap();
cursor_on(&mut settings, Row::Setting(mouse));
assert_eq!(
settings.on_key(&key(KeyCode::Enter)),
ConfigOutcome::Write(SettingChange::Set { path: &["mouse"], value: false.into() })
);
settings.refresh(
ConfigLayers { global: Some(serde_json::json!({ "mouse": false })), project: None },
"luxe".into(),
);
assert_eq!(
settings.on_key(&key(KeyCode::Char(' '))),
ConfigOutcome::Write(SettingChange::Reset { path: &["mouse"] })
);
}
#[test]
fn a_choice_steps_both_ways_from_the_value_in_force() {
let mut settings =
state(serde_json::json!({ "dock": { "mode": "shown" } }), None).open_on(Page::Layout);
let dock = luxe_core::settings::find(&["dock", "mode"]).unwrap();
cursor_on(&mut settings, Row::Setting(dock));
assert_eq!(
settings.on_key(&key(KeyCode::Right)),
ConfigOutcome::Write(SettingChange::Set {
path: &["dock", "mode"],
value: "hidden".into()
})
);
assert_eq!(
settings.on_key(&key(KeyCode::Left)),
ConfigOutcome::Write(SettingChange::Reset { path: &["dock", "mode"] }),
"auto is the default, so stepping back to it removes the key"
);
}
/// A project override would quietly win over anything written here, so the surface refuses
/// and says where the value lives instead of writing a change nobody would see.
#[test]
fn a_value_the_project_sets_is_explained_rather_than_changed() {
let project = serde_json::json!({ "bell": true, "tools": { "disabled": ["debug"] } });
let mut settings = state(serde_json::json!({}), Some(project)).open_on(Page::Agent);
cursor_on(&mut settings, Row::Setting(luxe_core::settings::find(&["bell"]).unwrap()));
assert_eq!(settings.on_key(&key(KeyCode::Enter)), ConfigOutcome::Consumed);
assert!(settings.notice.as_ref().unwrap().text.contains(".luxe/config.json"));
settings.select_page(3);
let debug = luxe_core::tool_catalog::get("debug").unwrap();
cursor_on(&mut settings, Row::Tool(debug));
assert_eq!(settings.on_key(&key(KeyCode::Enter)), ConfigOutcome::Consumed);
assert_eq!(settings.tool_state(debug), (Layer::Project, false));
}
#[test]
fn a_tool_toggles_and_reset_turns_one_the_reader_disabled_back_on() {
let global = serde_json::json!({ "tools": { "disabled": ["screenshot"] } });
let mut settings = state(global, None).open_on(Page::Tools);
let screenshot = luxe_core::tool_catalog::get("screenshot").unwrap();
cursor_on(&mut settings, Row::Tool(screenshot));
assert_eq!(settings.tool_state(screenshot), (Layer::Global, false));
assert_eq!(
settings.on_key(&key(KeyCode::Char('r'))),
ConfigOutcome::Write(SettingChange::Tool { name: "screenshot", enabled: true })
);
let grep = luxe_core::tool_catalog::get("grep").unwrap();
cursor_on(&mut settings, Row::Tool(grep));
assert_eq!(
settings.on_key(&key(KeyCode::Enter)),
ConfigOutcome::Write(SettingChange::Tool { name: "grep", enabled: false })
);
}
/// The essentials are named on the page so their absence from the toggles is not a mystery,
/// and the cursor never rests on them or on a heading.
#[test]
fn the_tools_page_names_the_essentials_and_the_cursor_skips_what_is_not_a_control() {
let mut settings = state(serde_json::json!({}), None).open_on(Page::Tools);
assert_eq!(settings.rows().first(), Some(&Row::Essentials));
for _ in 0..40 {
assert!(settings.rows()[settings.cursor].selectable());
settings.on_key(&key(KeyCode::Down));
}
let last = settings.rows().len() - 1;
assert_eq!(settings.cursor, last, "the cursor stops on the last control");
}
#[test]
fn tab_moves_through_the_pages_and_wraps() {
let mut settings = state(serde_json::json!({}), None);
assert_eq!(settings.page(), Page::Appearance);
settings.on_key(&key(KeyCode::Tab));
assert_eq!(settings.page(), Page::Conversation);
settings.on_key(&KeyEvent::new(KeyCode::BackTab, KeyModifiers::SHIFT));
settings.on_key(&KeyEvent::new(KeyCode::BackTab, KeyModifiers::SHIFT));
assert_eq!(settings.page(), Page::Agent, "back from the first page is the last");
settings.on_key(&key(KeyCode::Char('4')));
assert_eq!(settings.page(), Page::Tools, "the pages are numbered");
}
#[test]
fn searching_finds_settings_and_tools_across_pages() {
let mut settings = state(serde_json::json!({}), None);
for code in [KeyCode::Char('/'), KeyCode::Char('w'), KeyCode::Char('r'), KeyCode::Char('a')] {
settings.on_key(&key(code));
}
let rows = settings.rows();
let wrap = luxe_core::settings::find(&["diff", "word_wrap"]).unwrap();
assert!(rows.contains(&Row::Setting(wrap)), "a setting from another page");
assert!(rows.iter().all(|row| row.selectable()), "a search is a flat list");
settings.on_key(&key(KeyCode::Esc));
assert_eq!(settings.page(), Page::Appearance, "esc puts the page back");
assert!(settings.query.is_none());
}
#[test]
fn the_theme_opens_its_picker_and_e_opens_the_file() {
let mut settings = state(serde_json::json!({}), None);
assert_eq!(settings.on_key(&key(KeyCode::Enter)), ConfigOutcome::PickTheme);
assert_eq!(
settings.on_key(&key(KeyCode::Char('e'))),
ConfigOutcome::EditFile(PathBuf::from("/home/dev/.config/luxe/config.json"))
);
}
/// A theme the project sets is explained like any other project-set value, not opened in a picker
/// whose choice the project would quietly override; the reader's own theme still opens it.
#[test]
fn a_project_set_theme_is_explained_rather_than_picked() {
let theme = Row::Setting(luxe_core::settings::find(&["theme"]).unwrap());
let project = serde_json::json!({ "theme": "nord" });
let mut settings = state(serde_json::json!({}), Some(project)).open_on(Page::Appearance);
cursor_on(&mut settings, theme);
assert_eq!(settings.on_key(&key(KeyCode::Enter)), ConfigOutcome::Consumed);
assert!(settings.notice.as_ref().unwrap().text.contains(".luxe/config.json"));
let mut own = state(serde_json::json!({ "theme": "nord" }), None).open_on(Page::Appearance);
cursor_on(&mut own, theme);
assert_eq!(own.on_key(&key(KeyCode::Enter)), ConfigOutcome::PickTheme);
}
/// Too small to draw, the panel says so, and its unseen controls change nothing until it fits.
#[test]
fn a_panel_too_small_to_draw_says_so_and_holds_its_keys() {
use ratatui::{backend::TestBackend, Terminal};
let mut settings = state(serde_json::json!({}), None).open_on(Page::Layout);
let mouse = luxe_core::settings::find(&["mouse"]).unwrap();
cursor_on(&mut settings, Row::Setting(mouse));
let styles = crate::theme::styles::ThemeStyles::from_resolved(
&luxe_core::theme::ThemeRegistry::new().resolve("nord").unwrap(),
"nord",
);
let hit = std::cell::RefCell::new(crate::mouse::HitRegions::default());
let draw = |settings: &SettingsState, height: u16| {
let mut terminal = Terminal::new(TestBackend::new(80, height)).unwrap();
terminal.draw(|f| settings.view(f, f.area(), &styles, &hit)).unwrap();
terminal.backend().buffer().content.iter().map(|c| c.symbol()).collect::<String>()
};
let text = draw(&settings, 9);
assert!(text.contains("Make the window bigger"), "{text}");
assert_eq!(settings.on_key(&key(KeyCode::Enter)), ConfigOutcome::Consumed, "no write");
draw(&settings, 20);
assert!(matches!(settings.on_key(&key(KeyCode::Enter)), ConfigOutcome::Write(_)), "fits again");
}

View File

@@ -0,0 +1,443 @@
//! Setup — the four questions a first run, and `luxe init`, ask: a look, a provider, the tools,
//! and the start screen.
//!
//! A stage of the Configuration surface rather than a surface of its own, because the provider
//! step *is* that surface's job: its sign-in rows open the same login wizard, drawn in the same
//! region, and a finished login hands to the same model picker. Everything else here only gathers
//! choices. Nothing is written until the last step — or until the reader skips, which writes a
//! file that chooses nothing, so the questions are asked once.
//!
//! Keys in, a [`ConfigOutcome`] out, like the rest of the surface; the app writes the file.
pub(super) mod render;
use crossterm::event::{KeyCode, KeyEvent};
use luxe_core::config::{Config, DashboardSetting, DashboardStyle};
use luxe_core::tool_catalog::CatalogTool;
use super::{ConfigChoice, ConfigOutcome};
/// Why setup is on screen, which decides where finishing it goes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SetupMode {
/// The first launch on a machine with no `config.json`: finishing lands on the start screen
FirstRun,
/// `luxe init`: finishing writes the file and leaves
Init,
}
/// One step.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Step {
Theme,
Provider,
Tools,
Start,
}
impl Step {
const ALL: [Self; 4] = [Self::Theme, Self::Provider, Self::Tools, Self::Start];
fn label(self) -> &'static str {
match self {
Self::Theme => "Theme",
Self::Provider => "Provider",
Self::Tools => "Tools",
Self::Start => "Start",
}
}
fn index(self) -> usize {
Self::ALL.iter().position(|step| *step == self).unwrap_or(0)
}
}
/// The start screen's three answers, in the order they are offered.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StartScreen {
Launcher,
Minimal,
Off,
}
impl StartScreen {
const ALL: [Self; 3] = [Self::Launcher, Self::Minimal, Self::Off];
fn of(config: &Config) -> Self {
match (config.dashboard_shown(), config.dashboard_style()) {
(false, _) => Self::Off,
(true, DashboardStyle::Minimal) => Self::Minimal,
_ => Self::Launcher,
}
}
/// What `dashboard` should hold, or `None` for the default (the key removed).
pub fn setting(self) -> Option<DashboardSetting> {
match self {
Self::Launcher => None,
Self::Minimal => Some(DashboardSetting::Styled { style: DashboardStyle::Minimal }),
Self::Off => Some(DashboardSetting::Enabled(false)),
}
}
fn label(self) -> &'static str {
match self {
Self::Launcher => "The launcher",
Self::Minimal => "Just the prompt",
Self::Off => "Straight into a conversation",
}
}
fn detail(self) -> &'static str {
match self {
Self::Launcher => "A prompt, with your sessions and commands listed under it",
Self::Minimal => "The same prompt, with the list folded away until you press ↓",
Self::Off => "No start screen: a new session every launch",
}
}
}
/// What the reader chose, for the app to write.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SetupChoices {
/// A theme by name, or `None` to follow the desktop (or take the default)
pub theme: Option<String>,
/// Tools to leave unregistered
pub disabled_tools: Vec<String>,
/// The start screen
pub start: StartScreen,
}
/// The setup flow's state.
#[derive(Debug)]
pub struct SetupState {
mode: SetupMode,
step: Step,
/// Every theme on offer, `None` standing for "follow the desktop" when there is one to follow
themes: Vec<Option<String>>,
theme: usize,
/// The theme in force when setup opened, put back when it is skipped
opened_with: String,
/// The desktop's theme, which the "follow the desktop" row previews in
desktop: Option<String>,
/// The provider step's rows: three ways to sign in, then on
provider: usize,
tools: Vec<(&'static CatalogTool, bool)>,
tool: usize,
start: usize,
}
/// The provider step's sign-in rows; the step's last row moves on.
const SIGN_IN: [ConfigChoice; 3] =
[ConfigChoice::Subscription, ConfigChoice::ApiKey, ConfigChoice::LocalOrCustom];
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
/// follow one; `active` the theme in force right now.
pub fn open(
mode: SetupMode,
config: &Config,
themes: Vec<String>,
desktop: Option<String>,
active: String,
) -> Self {
let mut offered: Vec<Option<String>> = Vec::new();
if desktop.is_some() {
offered.push(None);
}
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
None if desktop.is_some() => Some(0),
None => offered.iter().position(|offer| offer.as_deref() == Some("luxe")),
}
.unwrap_or(0);
let tools = luxe_core::tool_catalog::toggleable()
.into_iter()
.map(|tool| (tool, config.tools.is_enabled(tool.name)))
.collect();
let start = StartScreen::ALL
.iter()
.position(|start| *start == StartScreen::of(config))
.unwrap_or(0);
Self {
mode,
step: Step::Theme,
themes: offered,
theme,
opened_with: active,
provider: 0,
tools,
tool: 0,
start,
desktop,
}
}
/// Why setup is showing.
pub fn mode(&self) -> SetupMode {
self.mode
}
/// The step showing.
pub fn step(&self) -> Step {
self.step
}
/// The theme the cursor is on, by the name a preview repaints in.
pub fn previewed_theme(&self) -> String {
match self.themes.get(self.theme).cloned().flatten() {
Some(name) => name,
None => self.desktop.clone().unwrap_or_else(|| self.opened_with.clone()),
}
}
/// The theme in force when setup opened.
pub fn opened_with(&self) -> &str {
&self.opened_with
}
/// What has been chosen so far.
pub fn choices(&self) -> SetupChoices {
SetupChoices {
theme: self.themes.get(self.theme).cloned().flatten(),
disabled_tools: self
.tools
.iter()
.filter(|(_, enabled)| !enabled)
.map(|(tool, _)| tool.name.to_string())
.collect(),
start: StartScreen::ALL[self.start],
}
}
/// Handle a keypress. `configured` is whether a provider can answer a turn right now.
pub fn on_key(&mut self, key: &KeyEvent, configured: bool) -> ConfigOutcome {
let plain = key.modifiers.is_empty();
match key.code {
KeyCode::Char('s') if plain => ConfigOutcome::SkipSetup,
KeyCode::Esc | KeyCode::Left => {
match Step::ALL.get(self.step.index().wrapping_sub(1)) {
Some(previous) => {
self.step = *previous;
ConfigOutcome::Consumed
}
// Back from the first step is out
None if key.code == KeyCode::Esc => ConfigOutcome::SkipSetup,
None => ConfigOutcome::Consumed,
}
}
KeyCode::Up | KeyCode::Char('k') if plain => self.step_cursor(-1),
KeyCode::Down | KeyCode::Char('j') if plain => self.step_cursor(1),
KeyCode::Char(' ') if self.step == Step::Tools => {
if let Some((_, enabled)) = self.tools.get_mut(self.tool) {
*enabled = !*enabled;
}
ConfigOutcome::Consumed
}
KeyCode::Enter | KeyCode::Right => self.advance(configured),
_ => ConfigOutcome::Consumed,
}
}
/// Put the cursor on row `index` of the step showing (a click, or the pointer over it).
pub fn select(&mut self, index: usize) -> ConfigOutcome {
match self.step {
Step::Theme if index < self.themes.len() => {
self.theme = index;
return ConfigOutcome::PreviewTheme(self.previewed_theme());
}
Step::Provider if index <= SIGN_IN.len() => self.provider = index,
Step::Tools if index < self.tools.len() => self.tool = index,
Step::Start if index < StartScreen::ALL.len() => self.start = index,
_ => {}
}
ConfigOutcome::Consumed
}
/// The row under the cursor, as Enter does it (a click lands here too).
pub fn activate(&mut self, configured: bool) -> ConfigOutcome {
if self.step == Step::Tools {
if let Some((_, enabled)) = self.tools.get_mut(self.tool) {
*enabled = !*enabled;
}
return ConfigOutcome::Consumed;
}
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));
match self.step {
Step::Theme => ConfigOutcome::PreviewTheme(self.previewed_theme()),
_ => ConfigOutcome::Consumed,
}
}
/// 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 {
if self.step == Step::Provider {
if let Some(choice) = SIGN_IN.get(self.provider) {
return choice.scope().map_or(ConfigOutcome::Consumed, ConfigOutcome::SignIn);
}
}
match Step::ALL.get(self.step.index() + 1) {
Some(next) => {
self.step = *next;
// With a provider already answering, the step's likeliest answer is to move on
if self.step == Step::Provider && configured {
self.provider = SIGN_IN.len();
}
ConfigOutcome::Consumed
}
None => ConfigOutcome::FinishSetup(self.choices()),
}
}
}
/// The scope a provider row signs in to, for the renderer and the tests.
pub(super) fn sign_in_rows() -> &'static [ConfigChoice] {
&SIGN_IN
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
use crossterm::event::KeyModifiers;
use luxe_core::auth::LoginScope;
fn key(code: KeyCode) -> KeyEvent {
KeyEvent::new(code, KeyModifiers::NONE)
}
fn themes() -> Vec<String> {
vec!["luxe".into(), "nord".into(), "gruvbox".into()]
}
fn fresh(desktop: Option<&str>) -> SetupState {
SetupState::open(
SetupMode::FirstRun,
&Config::default(),
themes(),
desktop.map(str::to_string),
"luxe".into(),
)
}
/// Moving through the themes repaints the screen in each, and the one chosen is what is
/// written; following the desktop is a choice to write nothing.
#[test]
fn the_theme_step_previews_as_it_moves_and_records_the_choice() {
let mut setup = fresh(Some("tokyo-night"));
assert_eq!(setup.choices().theme, None, "the desktop leads when there is one");
assert_eq!(setup.previewed_theme(), "tokyo-night");
assert_eq!(
setup.on_key(&key(KeyCode::Down), false),
ConfigOutcome::PreviewTheme("luxe".into())
);
setup.on_key(&key(KeyCode::Down), false);
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");
}
#[test]
fn enter_walks_the_steps_and_the_last_one_finishes() {
let mut setup = fresh(None);
setup.on_key(&key(KeyCode::Enter), true);
assert_eq!(setup.step(), Step::Provider);
// Past the sign-in rows to "continue"
for _ in 0..3 {
setup.on_key(&key(KeyCode::Down), true);
}
setup.on_key(&key(KeyCode::Enter), true);
assert_eq!(setup.step(), Step::Tools);
setup.on_key(&key(KeyCode::Enter), true);
assert_eq!(setup.step(), Step::Start);
match setup.on_key(&key(KeyCode::Enter), true) {
ConfigOutcome::FinishSetup(choices) => {
assert_eq!(choices.start, StartScreen::Launcher);
assert!(choices.disabled_tools.is_empty(), "every tool stays on by default");
}
other => panic!("expected the end of setup, got {other:?}"),
}
}
/// The sign-in rows are the Configuration surface's own, so each opens the wizard on the list
/// it names.
#[test]
fn the_provider_step_signs_in_through_the_surfaces_own_wizard() {
let mut setup = fresh(None);
setup.on_key(&key(KeyCode::Enter), false);
assert_eq!(
setup.on_key(&key(KeyCode::Enter), false),
ConfigOutcome::SignIn(LoginScope::Subscription)
);
setup.on_key(&key(KeyCode::Down), false);
assert_eq!(
setup.on_key(&key(KeyCode::Enter), false),
ConfigOutcome::SignIn(LoginScope::ApiKey)
);
}
/// A credential found in the environment means the provider step can be passed with Enter.
#[test]
fn with_a_provider_already_answering_enter_moves_past_the_provider_step() {
let mut setup = fresh(None);
setup.on_key(&key(KeyCode::Enter), true);
assert_eq!(setup.step(), Step::Provider);
setup.on_key(&key(KeyCode::Enter), true);
assert_eq!(setup.step(), Step::Tools);
}
#[test]
fn space_turns_a_tool_off_and_the_choice_names_it() {
let mut setup = fresh(None);
setup.on_key(&key(KeyCode::Enter), true);
for _ in 0..3 {
setup.on_key(&key(KeyCode::Down), true);
}
setup.on_key(&key(KeyCode::Enter), true);
assert_eq!(setup.step(), Step::Tools);
setup.on_key(&key(KeyCode::Char(' ')), true);
let first = luxe_core::tool_catalog::toggleable()[0].name;
assert_eq!(setup.choices().disabled_tools, vec![first.to_string()]);
}
/// Re-running `luxe init` opens on what the file already says, so finishing without touching
/// anything changes nothing.
#[test]
fn every_answer_starts_from_the_config_in_force() {
let config: Config = serde_json::from_str(
r#"{"theme":"gruvbox","tools":{"disabled":["debug"]},"dashboard":{"style":"minimal"}}"#,
)
.unwrap();
let setup = SetupState::open(SetupMode::Init, &config, themes(), None, "gruvbox".into());
let choices = setup.choices();
assert_eq!(choices.theme.as_deref(), Some("gruvbox"));
assert_eq!(choices.disabled_tools, vec!["debug".to_string()]);
assert_eq!(choices.start, StartScreen::Minimal);
}
#[test]
fn s_skips_from_anywhere_and_esc_steps_back_until_it_leaves() {
let mut setup = fresh(None);
assert_eq!(setup.on_key(&key(KeyCode::Char('s')), false), ConfigOutcome::SkipSetup);
setup.on_key(&key(KeyCode::Enter), false);
assert_eq!(setup.on_key(&key(KeyCode::Esc), false), ConfigOutcome::Consumed);
assert_eq!(setup.step(), Step::Theme);
assert_eq!(setup.on_key(&key(KeyCode::Esc), false), ConfigOutcome::SkipSetup);
}
}

View File

@@ -0,0 +1,450 @@
//! Setup rendering — where the steps stand, then the one showing.
use ratatui::{
layout::Rect,
style::{Modifier, Style},
text::{Line, Span},
widgets::{Padding, Paragraph, Wrap},
Frame,
};
use unicode_width::UnicodeWidthStr;
use super::{sign_in_rows, SetupMode, SetupState, StartScreen, Step};
use crate::glyphs::{Icon, Mark};
use crate::mouse::{HitRegions, MouseTarget};
use crate::theme::styles::{Depth, ThemeStyles};
use crate::widgets::{badge, selection_block, selection_row, slab, truncate_end, SELECTION_FRAME};
/// Widest the panel grows.
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;
impl SetupState {
/// Rows the panel would like, which leaves the wordmark what is left.
pub fn panel_height(area: Rect) -> u16 {
area.height.saturating_sub(9).clamp(18, 32).min(area.height)
}
/// Draw the panel into exactly `panel`. `configured` names what can answer a turn now.
pub fn view(
&self,
f: &mut Frame,
panel: Rect,
theme: &ThemeStyles,
hit: &std::cell::RefCell<HitRegions>,
configured: &[String],
) {
let title = match self.mode {
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));
let note = luxe_core::paths::home_relative(&luxe_core::config::Config::global_path());
let inner = crate::widgets::render_footed(f, block, panel, self.hint(), Some(&note), theme);
if inner.height < 6 {
return;
}
f.render_widget(Paragraph::new(self.stepper(theme)), Rect { height: 1, ..inner });
let body = Rect { y: inner.y + 2, height: inner.height - 2, ..inner };
match self.step {
Step::Theme => self.render_themes(f, body, theme, hit),
Step::Provider => self.render_provider(f, body, theme, hit, configured),
Step::Tools => self.render_tools(f, body, theme, hit),
Step::Start => self.render_start(f, body, theme, hit),
}
}
/// `✓ Theme ── 2 Provider ── 3 Tools ── 4 Start`, each step cut into a slab: the ones behind
/// on the raised step, the one here on the accent, the rest on the idle surface.
fn stepper(&self, theme: &ThemeStyles) -> Line<'static> {
let canvas = theme.background.bg.unwrap_or(theme.slab.canvas);
let mut spans = Vec::new();
for (index, step) in Step::ALL.iter().enumerate() {
if index > 0 {
spans.push(Span::styled(" ── ", theme.border_muted));
}
let here = self.step.index();
let (surface, style, mark) = match index.cmp(&here) {
std::cmp::Ordering::Less => {
(theme.slab.at(Depth::Raised), theme.text, Mark::Yes.glyph().to_string())
}
std::cmp::Ordering::Equal => (
theme.slab.at(Depth::Hero),
Style::new().fg(theme.slab.ink).add_modifier(Modifier::BOLD),
(index + 1).to_string(),
),
std::cmp::Ordering::Greater => {
(theme.slab.idle[0], theme.muted, (index + 1).to_string())
}
};
spans.extend(slab(
[Span::styled(format!("{mark} {}", step.label()), style)],
surface,
canvas,
Style::new(),
));
}
Line::from(spans)
}
fn hint(&self) -> &'static str {
match self.step {
Step::Theme => "↑/↓ preview · enter use this one · s skip setup",
Step::Provider => "enter open · ↑/↓ choose · ← back · s skip setup",
Step::Tools => "space turn on or off · enter continue · ← back · s skip setup",
Step::Start => "enter finish · ↑/↓ choose · ← back · s skip setup",
}
}
fn render_themes(
&self,
f: &mut Frame,
body: Rect,
theme: &ThemeStyles,
hit: &std::cell::RefCell<HitRegions>,
) {
let list = Rect { width: LIST_WIDTH.min(body.width), ..body };
let height = usize::from(list.height);
let start =
(self.theme + 1).saturating_sub(height).min(self.themes.len().saturating_sub(height));
let mut regions = hit.borrow_mut();
let lines: Vec<Line<'static>> = self
.themes
.iter()
.enumerate()
.skip(start)
.take(height)
.map(|(index, offer)| {
regions.push(
Rect::new(list.x, list.y + (index - start) as u16, list.width, 1),
MouseTarget::ConfigRow(index),
);
let chosen = index == self.theme;
let label = match offer {
None => {
format!("Follow the desktop ({})", self.desktop.clone().unwrap_or_default())
}
Some(name) if name == "luxe" => "luxe (Luxe's own)".to_string(),
Some(name) => name.clone(),
};
let spans = vec![
Span::styled(
Mark::Cursor.gutter(chosen),
theme.accent.add_modifier(Modifier::BOLD),
),
Span::styled(label, theme.label_on(chosen)),
];
selection_row(spans, usize::from(list.width), chosen, theme)
})
.collect();
drop(regions);
f.render_widget(Paragraph::new(lines), list);
let sample = Rect {
x: list.right() + 3,
width: body.right().saturating_sub(list.right() + 3),
..body
};
if sample.width > 20 {
render_sample(f, sample, theme);
}
}
fn render_provider(
&self,
f: &mut Frame,
body: Rect,
theme: &ThemeStyles,
hit: &std::cell::RefCell<HitRegions>,
configured: &[String],
) {
let summary = match configured.is_empty() {
true => Line::from(Span::styled(
"Nothing can answer a turn yet. Choose how you reach a model, or skip and set one \
up later in /config.",
theme.warning,
)),
false => Line::from(vec![
Span::styled("Ready: ", theme.success),
Span::styled(configured.join(" · "), theme.text),
Span::styled(" Add another, or continue.", theme.muted),
]),
};
f.render_widget(
Paragraph::new(summary).wrap(Wrap { trim: true }),
Rect { height: 2, ..body },
);
let list = Rect { y: body.y + 3, height: body.height.saturating_sub(3), ..body };
let width = usize::from(list.width);
let mut lines: Vec<Line<'static>> = Vec::new();
let mut regions = hit.borrow_mut();
let rows: Vec<(String, String)> = sign_in_rows()
.iter()
.map(|choice| (choice.label().to_string(), choice.detail().to_string()))
.chain(std::iter::once(match configured.is_empty() {
true => (
"Skip for now".to_string(),
"Set a provider up any time in /config".to_string(),
),
false => ("Continue".to_string(), "On to the tools the agent can use".to_string()),
}))
.collect();
for (index, (label, detail)) in rows.into_iter().enumerate() {
let chosen = index == self.provider;
let y = list.y + lines.len() as u16;
if y < list.bottom() {
regions.push(
Rect::new(list.x, y, list.width, 2.min(list.bottom() - y)),
MouseTarget::ConfigRow(index),
);
}
lines.extend(selection_block(
vec![
vec![
Span::styled(
Mark::Cursor.gutter(chosen),
theme.accent.add_modifier(Modifier::BOLD),
),
Span::styled(label, theme.label_on(chosen)),
],
vec![
Span::raw(" "),
Span::styled(
truncate_end(&detail, width.saturating_sub(SELECTION_FRAME + 2)),
theme.muted,
),
],
],
width,
chosen,
theme,
));
}
drop(regions);
f.render_widget(Paragraph::new(lines), list);
}
fn render_tools(
&self,
f: &mut Frame,
body: Rect,
theme: &ThemeStyles,
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 lines: Vec<Line<'static>> = self
.tools
.iter()
.enumerate()
.skip(start)
.take(height)
.map(|(index, (tool, enabled))| {
regions.push(
Rect::new(list.x, list.y + (index - start) as u16, list.width, 1),
MouseTarget::ConfigRow(index),
);
let chosen = index == self.tool;
let mut spans = vec![
Span::styled(
Mark::Cursor.gutter(chosen),
theme.accent.add_modifier(Modifier::BOLD),
),
Span::styled(format!("{:<17}", tool.name), theme.label_on(chosen)),
];
let toggle = match enabled {
true => Span::styled("● on", theme.success),
false => Span::styled("○ off", theme.muted),
};
let used: usize = spans.iter().map(|span| span.content.width()).sum();
let pad = width.saturating_sub(SELECTION_FRAME + used + toggle.content.width());
spans.push(Span::raw(" ".repeat(pad)));
spans.push(toggle);
selection_row(spans, width, chosen, theme)
})
.collect();
drop(regions);
f.render_widget(Paragraph::new(lines), list);
let side = Rect {
x: list.right() + 3,
width: body.right().saturating_sub(list.right() + 3),
..body
};
let Some((tool, _)) = self.tools.get(self.tool) else { return };
if side.width < 16 {
return;
}
let mut words = vec![
Line::from(vec![
Span::styled(tool.name, theme.text.add_modifier(Modifier::BOLD)),
Span::styled(format!(" {}", tool.summary), theme.muted),
]),
Line::default(),
Line::from(Span::styled(tool.detail, theme.text)),
];
if let Some(needs) = tool.needs {
words.push(Line::default());
words.push(Line::from(Span::styled(
format!("Registers only where there is {needs}."),
theme.muted,
)));
}
words.push(Line::default());
words.push(Line::from(vec![
Span::styled("read, write, edit and bash", theme.text),
Span::styled(" are always on: the agent cannot work without them.", theme.muted),
]));
words.push(Line::default());
words.push(Line::from(vec![
Span::styled("Change these later in ", theme.muted),
Span::styled("/settings", theme.accent),
Span::styled(", on the Tools page.", theme.muted),
]));
f.render_widget(Paragraph::new(words).wrap(Wrap { trim: true }), side);
}
fn render_start(
&self,
f: &mut Frame,
body: Rect,
theme: &ThemeStyles,
hit: &std::cell::RefCell<HitRegions>,
) {
f.render_widget(
Paragraph::new(Line::from(Span::styled(
"What Luxe opens on when you run it in a project.",
theme.muted,
))),
Rect { height: 1, ..body },
);
let list = Rect { y: body.y + 2, height: body.height.saturating_sub(2), ..body };
let width = usize::from(list.width);
let mut lines: Vec<Line<'static>> = Vec::new();
let mut regions = hit.borrow_mut();
for (index, screen) in StartScreen::ALL.iter().enumerate() {
let chosen = index == self.start;
let y = list.y + lines.len() as u16;
if y < list.bottom() {
regions.push(
Rect::new(list.x, y, list.width, 2.min(list.bottom() - y)),
MouseTarget::ConfigRow(index),
);
}
let radio = match chosen {
true => Span::styled("● ", theme.accent),
false => Span::styled("○ ", theme.muted),
};
lines.extend(selection_block(
vec![
vec![
Span::styled(
Mark::Cursor.gutter(chosen),
theme.accent.add_modifier(Modifier::BOLD),
),
radio,
Span::styled(screen.label(), theme.label_on(chosen)),
],
vec![Span::raw(" "), Span::styled(screen.detail(), theme.muted)],
],
width,
chosen,
theme,
));
lines.push(Line::default());
}
drop(regions);
f.render_widget(Paragraph::new(lines), list);
}
}
/// A sample of the product in whatever theme is showing: a message, a reply, an edit with its diff,
/// and the slabs the dock is built from — the things a palette has to get right.
fn render_sample(f: &mut Frame, area: Rect, theme: &ThemeStyles) {
let width = usize::from(area.width);
let canvas = theme.background.bg.unwrap_or(theme.slab.canvas);
let filled = |spans: Vec<Span<'static>>, bg: ratatui::style::Color| {
let mut spans: Vec<Span<'static>> = spans
.into_iter()
.map(|span| {
let style = if span.style.bg.is_some() { span.style } else { span.style.bg(bg) };
Span::styled(span.content, style)
})
.collect();
let used: usize = spans.iter().map(|span| span.content.width()).sum();
spans.push(Span::styled(" ".repeat(width.saturating_sub(used)), Style::new().bg(bg)));
Line::from(spans)
};
let user = theme.user_msg_bg.bg.unwrap_or_else(|| theme.slab.at(Depth::Recessed));
let card = theme.tool_call_success_bg.bg.unwrap_or_else(|| theme.slab.at(Depth::Recessed));
let add = theme.diff_add_bg.bg.unwrap_or(card);
let del = theme.diff_del_bg.bg.unwrap_or(card);
let mut heads = badge("PLAN", Depth::Hero, canvas, theme);
heads.push(Span::raw(" "));
heads.extend(badge("CHANGES", Depth::Raised, canvas, theme));
heads.push(Span::raw(" "));
heads.extend(badge("MODEL", Depth::Recessed, canvas, theme));
let lines = vec![
filled(
vec![
Span::styled("▌ ", theme.accent),
Span::styled("Rename the dock's headings to match the rail", theme.text),
],
user,
),
Line::default(),
Line::from(Span::styled(
"Two headings drift from the rail's names; renaming both.",
theme.text,
)),
Line::default(),
filled(
vec![
Span::styled(" ± edit", theme.success.add_modifier(Modifier::BOLD)),
Span::styled(" src/view/dock.rs", theme.text),
Span::styled(" 6ms", theme.muted),
],
card,
),
filled(
vec![
Span::styled(" 734 ", theme.muted),
Span::styled("fn ", theme.accent),
Span::styled("heading(section: Section) {", theme.text),
],
card,
),
filled(
vec![
Span::styled(" -735 ", theme.error),
Span::styled(" let label = \"FILES\";", theme.text),
],
del,
),
filled(
vec![
Span::styled(" +735 ", theme.success),
Span::styled(" let label = \"CHANGES\";", theme.text),
],
add,
),
filled(vec![Span::styled(" 736 ", theme.muted), Span::styled("}", theme.text)], card),
Line::default(),
Line::from(heads),
Line::default(),
Line::from(vec![
Span::styled("info ", theme.info),
Span::styled("warning ", theme.warning),
Span::styled("error ", theme.error),
Span::styled("success", theme.success),
]),
];
f.render_widget(Paragraph::new(lines), area);
}

View File

@@ -0,0 +1,213 @@
#![allow(clippy::unwrap_used)]
use super::*;
use crossterm::event::KeyModifiers;
use luxe_core::auth::{AuthMethod, CredentialKind, StoredCredentialInfo};
pub(super) fn key(code: KeyCode) -> KeyEvent {
KeyEvent::new(code, KeyModifiers::NONE)
}
pub(super) fn files() -> Vec<ConfigFile> {
vec![
ConfigFile {
name: "config.json",
detail: "Theme, dock, statusline",
path: PathBuf::from("/home/dev/.config/luxe/config.json"),
},
ConfigFile {
name: "models.json",
detail: "Providers and models",
path: PathBuf::from("/home/dev/.config/luxe/models.json"),
},
ConfigFile {
name: "auth.json",
detail: "Credentials",
path: PathBuf::from("/home/dev/.config/luxe/auth.json"),
},
]
}
pub(super) fn provider(id: &str, status: CredentialStatus) -> ProviderOption {
ProviderOption {
id: id.to_string(),
name: id.to_uppercase(),
methods: vec![AuthMethod::api_key(None)],
status,
note: None,
console_url: None,
keyless: false,
needs_endpoint: false,
}
}
pub(super) fn state() -> ConfigurationState {
ConfigurationState::open(&[], files())
}
#[test]
fn each_row_opens_the_list_of_providers_it_names() {
let mut config = state();
assert_eq!(
config.on_key(&key(KeyCode::Enter)),
ConfigOutcome::SignIn(LoginScope::Subscription)
);
config.on_key(&key(KeyCode::Down));
assert_eq!(config.on_key(&key(KeyCode::Enter)), ConfigOutcome::SignIn(LoginScope::ApiKey));
config.on_key(&key(KeyCode::Down));
assert_eq!(
config.on_key(&key(KeyCode::Enter)),
ConfigOutcome::SignIn(LoginScope::LocalOrCustom)
);
}
/// The numbers are drawn beside the rows, so pressing one has to run that row.
#[test]
fn a_numbered_row_runs_without_arrowing_to_it() {
let mut config = state();
assert_eq!(config.on_key(&key(KeyCode::Char('2'))), ConfigOutcome::SignIn(LoginScope::ApiKey));
assert_eq!(config.selected_row(), 1, "the cursor follows the number that was pressed");
// A number past the end of the list does nothing rather than wrapping to something.
assert_eq!(config.on_key(&key(KeyCode::Char('9'))), ConfigOutcome::Consumed);
}
#[test]
fn the_last_row_opens_the_file_list_and_then_one_file() {
let mut config = state();
assert_eq!(config.on_key(&key(KeyCode::Char('5'))), ConfigOutcome::Consumed);
assert!(config.showing_files());
config.on_key(&key(KeyCode::Down));
assert_eq!(
config.on_key(&key(KeyCode::Enter)),
ConfigOutcome::EditFile(PathBuf::from("/home/dev/.config/luxe/models.json"))
);
}
/// One step back at a time: out of the file list to the menu, out of the menu to the caller.
#[test]
fn escape_steps_back_rather_than_out() {
let mut config = state();
config.on_key(&key(KeyCode::Char('5')));
assert_eq!(config.on_key(&key(KeyCode::Esc)), ConfigOutcome::Consumed);
assert!(!config.showing_files());
assert_eq!(config.on_key(&key(KeyCode::Esc)), ConfigOutcome::Close);
}
#[test]
fn the_cursor_stops_at_both_ends_of_each_list() {
let mut config = state();
for _ in 0..6 {
config.on_key(&key(KeyCode::Down));
}
assert_eq!(config.selected_row(), ConfigChoice::ROWS.len() - 1);
for _ in 0..6 {
config.on_key(&key(KeyCode::Up));
}
assert_eq!(config.selected_row(), 0);
// The file list keeps its own cursor, and coming back lands on the row that opened it.
config.on_key(&key(KeyCode::Char('5')));
config.on_key(&key(KeyCode::Down));
assert_eq!(config.selected_row(), 1);
config.on_key(&key(KeyCode::Esc));
assert_eq!(config.selected_row(), ConfigChoice::ROWS.len() - 1);
}
/// "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.
#[test]
fn the_summary_names_every_credential_and_where_it_came_from() {
let providers = vec![
provider(
"openai",
CredentialStatus::Stored(StoredCredentialInfo {
kind: CredentialKind::ApiKey,
expires_at_ms: None,
account: None,
}),
),
provider("anthropic", CredentialStatus::Env("ANTHROPIC_API_KEY".into())),
provider("groq", CredentialStatus::Missing),
];
let config = ConfigurationState::open(&providers, files());
assert!(config.is_configured());
let summary = config.summary();
assert!(summary.contains("OPENAI (API key)"), "{summary}");
assert!(summary.contains("ANTHROPIC (ANTHROPIC_API_KEY)"), "{summary}");
assert!(!summary.contains("GROQ"), "a provider with no credential is not signed in");
let empty = ConfigurationState::open(&[provider("groq", CredentialStatus::Missing)], files());
assert!(!empty.is_configured());
assert_eq!(empty.summary(), "No provider is configured yet.");
}
/// Below its minimum the surface draws only "Resize to continue", so the menu and the setup flow
/// hold their keys there the way the settings pages do; Esc still leaves.
///
/// The break this catches: only the settings pages knew they were undrawn, so a key on the menu
/// or in setup opened a sign-in or answered a question nobody could see.
#[test]
fn an_undrawn_surface_holds_its_keys_on_every_stage() {
use ratatui::{backend::TestBackend, Terminal};
let styles = crate::theme::styles::ThemeStyles::from_resolved(
&luxe_core::theme::ThemeRegistry::new().resolve("nord").unwrap(),
"nord",
);
let hit = std::cell::RefCell::new(crate::mouse::HitRegions::default());
let draw = |config: &ConfigurationState, (width, height): (u16, u16)| {
let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
let clock = crate::widgets::BannerClock::default();
terminal.draw(|f| config.view(f, f.area(), &styles, &hit, clock)).unwrap();
};
let mut config = state();
draw(&config, (30, 8));
assert_eq!(config.on_key(&key(KeyCode::Down)), ConfigOutcome::Consumed);
assert_eq!(config.selected_row(), 0, "the cursor did not move under the notice");
assert_eq!(config.on_key(&key(KeyCode::Enter)), ConfigOutcome::Consumed, "nothing opened");
assert_eq!(config.on_key(&key(KeyCode::Esc)), ConfigOutcome::Close, "esc still leaves");
let mut config = state();
draw(&config, (80, 24));
config.on_key(&key(KeyCode::Down));
assert_eq!(config.selected_row(), 1, "drawn, the menu moves");
let mut config = state();
let setup = crate::configuration::SetupState::open(
crate::configuration::SetupMode::FirstRun,
&luxe_core::config::Config::default(),
vec!["nord".into(), "gruvbox".into()],
None,
"nord".into(),
);
config.show_setup(setup);
let before = format!("{:?}", config.setup());
draw(&config, (30, 8));
assert_eq!(config.on_key(&key(KeyCode::Down)), ConfigOutcome::Consumed);
assert_eq!(config.on_key(&key(KeyCode::Enter)), ConfigOutcome::Consumed);
assert_eq!(format!("{:?}", config.setup()), before, "setup took nothing undrawn");
}
/// The app draws the resize notice itself, without the surface's own view, so the hold has to
/// come from that path too: through the real render and the real key route, nothing moves or
/// opens on the menu or in setup.
#[test]
fn the_app_holds_the_surfaces_keys_under_its_resize_notice() {
use crate::fixture::{seeded_app, FixtureScenario};
use ratatui::{backend::TestBackend, Terminal};
for scenario in [FixtureScenario::Configuration, FixtureScenario::Setup] {
let mut app = seeded_app("luxe", scenario).expect("the fixture");
app.update(crate::app::Msg::TerminalResized { width: 30, height: 8 });
let mut terminal = Terminal::new(TestBackend::new(30, 8)).unwrap();
terminal.draw(|frame| crate::view::render(frame, &mut app)).unwrap();
assert!(app.overlays.configuration.is_some(), "{scenario:?} opens the surface");
let before = format!("{:?}", app.overlays.configuration);
for code in [KeyCode::Down, KeyCode::Enter] {
app.update(crate::app::Msg::Key(key(code)));
}
assert_eq!(format!("{:?}", app.overlays.configuration), before, "{scenario:?}");
assert!(app.overlays.auth_wizard.is_none(), "{scenario:?} opened nothing");
}
}