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,420 @@
//! 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.
///
/// 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
/// (submit, newline, paste, select all), and anything that acts on "the selected" thing a palette
/// opened from anywhere cannot point at.
pub(super) fn built_in() -> Vec<Command> {
use Need::{
ChangesPane, Chat, Diff, Image, PullRequestReview, Repository, Review, Turn, Waiting,
};
vec![
// === Anywhere ===
Command::action(UiAction::Quit)
.with_slash("/quit")
.summary("Leaves Luxe; the session is saved as it goes, so nothing is lost.")
.keywords(&["exit", "close"]),
Command::action(UiAction::Reload)
.with_slash("/reload")
.summary("Re-reads your config and keybindings without restarting.")
.keywords(&["refresh", "settings", "keybindings"]),
Command::slash(id::HELP, "Help", "/help")
.keys(UiAction::ToggleHelp)
.summary("Every key for this screen, as your keymap binds them, and where the guide is.")
.detail("Commands are in this list. In a review, the review's keys.")
.keywords(&["help", "keys", "shortcuts", "keybindings"]),
// === The conversation ===
//
// A review draws nothing over itself but the palette, so a command that opens a picker or
// answers in the transcript lists here, where what it does can be seen
Command::slash(id::MODEL, "Change model", "/model")
.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 \
window, output cap, reasoning levels and pricing move with it.",
)
.keywords(&["switch", "provider", "llm"]),
Command::slash(id::THINKING, "Set thinking level", "/thinking")
.needs(&[Chat])
.summary("How hard the model reasons before it answers, from Off to Ultra.")
.detail(
"A level the active model cannot honor is shown and cannot be picked. The level is \
remembered per model.",
)
.keywords(&["reasoning", "effort"]),
Command::slash(id::THEME, "Change theme", "/theme")
.needs(&[Chat])
.summary("Previews every theme as you move, and keeps the one you choose.")
.detail("`enter` writes it to your config. `esc` puts back the one you started with.")
.keywords(&["colors", "appearance"]),
Command::slash(id::MOUSE, "Mouse support", "/mouse")
.needs(&[Chat])
.keys(UiAction::ToggleMouse)
.summary("Turns mouse capture on or off.")
.detail(
"On, the wheel scrolls, a drag selects and copies, and a click opens a card. Off \
gives every gesture back to the terminal. Hold Shift to hand one drag back without \
turning it off.",
)
.usage(&[("/mouse", "toggle"), ("/mouse on", ""), ("/mouse off", "")])
.keywords(&["click", "scroll", "select"]),
Command::slash(id::PERMISSIONS, "Auto-approve tool asks", "/permissions")
.needs(&[Chat])
.summary("Approves every tool call that would have asked you first.")
.detail(
"Deny rules still apply, and the statusline says it is on for as long as it is.",
)
.usage(&[("/permissions", "toggle"), ("/permissions on", ""), ("/permissions off", "")])
.keywords(&["permission", "approve", "walk away"]),
Command::slash(id::NEW, "New session", "/new")
.needs(&[Chat])
.summary("Starts a fresh session; the one you leave is kept, and can be resumed.")
.detail("Resume it with `/sessions`, from the start screen, or with `luxe -c`.")
.keywords(&["clear", "reset", "start"]),
Command::slash(id::SESSIONS, "Sessions", "/sessions")
.needs(&[Chat])
.summary("Every session in this project, searchable, to pick up where it left off.")
.detail(
"Searches titles and what was said, with a preview of the one under the cursor; \
`#146` finds the sessions that worked on that pull request. The session you leave \
is kept, and one with a worktree of its own opens there.",
)
.keywords(&["resume", "switch", "history", "open", "find"]),
Command::slash(id::MODE, "Switch mode", "/mode")
.needs(&[Chat])
.keys(UiAction::CycleMode)
.summary("Moves between build, which changes things, and plan, which writes only the plan.")
.detail(
"Plan mode reads, asks and writes only `PLAN.md` (`plan.files`), and is held to it: \
an edit anywhere else does not run. Bare, `/mode` moves to the next mode. The \
composer's title shows the mode, and clicking it switches.",
)
.usage(&[("/mode", "the next mode"), ("/mode plan", ""), ("/mode build", "")])
.keywords(&["plan", "build", "read-only", "planning", "agent"]),
Command::slash(id::CONTEXT, "Context window", "/context")
.needs(&[Chat])
.summary("What is occupying the context window, ranked, with what to do about each.")
.keywords(&["tokens", "occupancy"]),
Command::slash(id::COMPACT, "Compact the conversation", "/compact")
.needs(&[Chat])
.summary("Summarizes the conversation now, whatever the occupancy.")
.usage(&[("/compact", ""), ("/compact <focus>", "what the summary should keep")])
.keywords(&["summarize", "summary", "shrink"]),
Command::slash(id::COST, "Session cost", "/cost")
.needs(&[Chat])
.summary("What this session has cost, by model and by kind of token.")
.detail("On a subscription it shows the allowance left rather than dollars.")
.keywords(&["tokens", "price", "billing"]),
Command::action(UiAction::SearchConvo)
.with_slash("/search")
.needs(&[Chat])
.summary("Finds text in the transcript.")
.keywords(&["find"]),
Command::action(UiAction::CopyMessage)
.needs(&[Chat, Turn])
.summary("Copies the selected message, or the last one, to the clipboard.")
.detail("With text selected, it copies the selection instead.")
.keywords(&["clipboard", "yank"]),
Command::action(UiAction::Retry)
.needs(&[Chat, Turn])
.summary("Sends your last message again, after the reply it got.")
.detail(
"The model sees that reply. To ask again as if it never happened, use Replace the \
last answer.",
)
.keywords(&["retry", "resend"]),
Command::action(UiAction::Regenerate)
.needs(&[Chat, Turn])
.summary("Asks your last message again in its place, without the reply it replaces.")
.keywords(&["regenerate", "redo"]),
Command::action(UiAction::EditResend)
.needs(&[Chat, Turn])
.summary("Puts your last message back in the composer to change and send again.")
.keywords(&["edit", "resend"]),
Command::action(UiAction::DequeueMessages)
.needs(&[Chat, Waiting])
.summary("Brings every message still waiting for a turn back into the composer.")
.keywords(&["queue", "recall"]),
Command::action(UiAction::ToggleToolOutput)
.needs(&[Chat, Turn])
.summary("Expands every tool card to its whole output, or folds them back.")
.keywords(&["expand", "collapse", "tools"]),
Command::action(UiAction::OpenImage)
.needs(&[Chat, Image])
.summary("Opens the newest image in the conversation full-window.")
.keywords(&["picture", "screenshot"]),
// === The workspace ===
Command::slash(id::DOCK, "Context Dock", "/dock")
.needs(&[Chat])
.keys(UiAction::ToggleDock)
.summary("Shows or hides the sidebar.")
.detail(
"`auto` hands it back to the layout, which shows it when there is room. With the \
statusline on `auto`, hiding the sidebar brings the statusline back, so this \
swaps one for the other.",
)
.usage(&[
("/dock", "toggle"),
("/dock show", ""),
("/dock hide", ""),
("/dock auto", ""),
("/dock left", ""),
("/dock right", ""),
])
.keywords(&["sidebar", "panel", "rail"]),
Command::action(UiAction::ToggleDockPosition)
.needs(&[Chat])
.summary("Moves the Context Dock to the other side of the conversation.")
.keywords(&["dock", "left", "right"]),
Command::slash(id::STATUSLINE, "Statusline", "/statusline")
.needs(&[Chat])
.keys(UiAction::ToggleStatusline)
.summary("Shows or hides the bar under the composer.")
.detail(
"`auto` shows it only when the sidebar is not beside the conversation, so the \
telemetry is on screen once.",
)
.usage(&[
("/statusline", "toggle"),
("/statusline show", ""),
("/statusline hide", ""),
("/statusline auto", ""),
])
.keywords(&["bar", "footer", "status"]),
Command::slash(id::CHANGES, "Preview", "/preview")
.needs(&[Chat])
.keys(UiAction::ToggleChanges)
.summary("Shows one file where the transcript is, whole or as its diff.")
.detail(
"Read-only: nothing is written, no model is asked, and looking does not mark a \
file reviewed.",
)
.usage(&[
("/preview", "the file the sidebar leads with"),
("/preview <path>", "that file"),
])
.keywords(&["peek", "files", "changes", "what changed", "git diff", "view"]),
Command::slash(id::EDITOR, "Open in editor", "/editor")
.needs(&[Chat])
.summary("Opens the project, or one file or folder, in your editor.")
.detail(
"The editor is `$LUXE_EDITOR`, `$VISUAL` or `$EDITOR`. A terminal editor takes the \
screen until it exits; the agent keeps working underneath. In the preview and in a \
review, the file on screen opens at the line you are on.",
)
.usage(&[
("/editor", "the project"),
("/editor <path>", "a file or folder, relative to the project"),
("/editor <path>:<line>", "a file, at that line"),
])
.keywords(&["open", "edit", "vim", "code", "file"]),
Command::action(UiAction::ChangesOpenInEditor)
.needs(&[ChangesPane])
.summary("Opens the previewed file in your editor, at the line you are on.")
.keywords(&["edit", "open"]),
Command::action(UiAction::ChangesToggleView)
.needs(&[ChangesPane])
.summary("Shows a changed file whole, or what changed in it.")
.keywords(&["diff", "file", "view"]),
Command::action(UiAction::AskAboutSelection)
.needs(&[ChangesPane])
.summary("Puts the lines you picked in the File view into the composer, to ask about.")
.detail(
"Drag across line numbers or code to pick lines, or right-click them. The agent \
gets the path and the lines, and reads them itself.",
)
.keywords(&["ask", "lines", "selection", "mention"]),
Command::action(UiAction::FocusFiles)
.needs(&[Chat])
.summary("Moves the keyboard into the dock's file tree.")
.detail(
"`j`/`k` move, `l` opens, `h` closes, `enter` shows a file, `/` filters, `o` opens \
it in your editor, `@` mentions it, `y` copies its path, `a` shows only what \
changed, `esc` goes back to the composer.",
)
.keywords(&["files", "tree", "explorer", "browse"]),
Command::action(UiAction::ReviewOpenInEditor)
.needs(&[Review])
.summary("Opens the file under the cursor in your editor, at its line.")
.detail("It opens the working tree's copy, which is the one an editor can change.")
.keywords(&["edit", "open"]),
Command::action(UiAction::ChangesToggleWordWrap)
.needs(&[ChangesPane])
.summary("Wraps long lines in the diff, or lets them run off the edge.")
.keywords(&["wrap"]),
Command::action(UiAction::ReviewToggleSplit)
.needs(&[Diff])
.summary("Draws the diff in two columns, or in one.")
.detail("It starts from `diff.layout`, and this overrides that for the session.")
.keywords(&["split", "unified", "layout"]),
Command::slash(id::WORKTREE, "Worktree", "/worktree")
.needs(&[Chat])
.summary("Where this session works, and whether it is a checkout of its own.")
.detail("`luxe --worktree` starts a session in a worktree of its own. The branch stays.")
.usage(&[
("/worktree", ""),
("/worktree remove", "end the session and remove its worktree"),
])
.keywords(&["checkout", "branch", "git"]),
// === Reviewing ===
Command::slash(id::DIFF, "Review changes", "/diff")
.needs(&[Chat])
.keys(UiAction::ReviewOpen)
.summary("Opens a Guided Review: a walkthrough of the current revision, read one chapter at a time.")
.detail(
"Used alone, `/diff` creates a review for the working tree, or opens it if one is \
already pinned. You can optionally name a target to create a fresh review for it.",
)
.usage(&[
("/diff", "the review open, or the working tree"),
("/diff turn", "the last turn"),
("/diff base <ref>", ""),
("/diff commit <oid>", ""),
("/diff pr <number or URL>", ""),
("/diff refresh", "rebuild the open review"),
])
.keywords(&["review", "guided"]),
Command::slash(id::REVIEW, "Second opinion", "/review")
.needs(&[Chat])
.summary("A reviewer in a fresh context reads the uncommitted changes and tells the agent.")
.detail(
"The reviewer changes nothing and never sees this conversation, which is what makes \
it a second opinion. It runs on `reviewer.model`, or this session's model. Findings \
come back as the agent's next turn, and the agent may push back on one it thinks \
is wrong.",
)
.usage(&[("/review", ""), ("/review <focus>", "what to look at hardest")])
.keywords(&["reviewer", "second opinion", "check", "critique"]),
Command::slash(id::PR, "Pull request", "/pr")
.needs(&[Chat, Repository])
.summary("This branch's pull request: status, reviewers and conversation.")
.detail(
"Each Status row carries its key; Enter on Ready opens the merge. In the \
Conversation, `r` replies and `d` drafts a reply with the agent.",
)
.keywords(&["checks", "threads", "github"]),
Command::slash(id::GITHUB, "GitHub", "/github")
.needs(&[Chat])
.summary("Pull requests and issues on GitHub, with each one's status and conversation.")
.detail(
"Sections come from `github.sections`. Enter reviews or takes up the row, `→` \
moves to its Overview and Conversation, `c` refers to it, `o` opens it, and `/` \
filters.",
)
.keywords(&["pull requests", "issues", "gh"]),
Command::slash(id::STACK, "Restack the stack", "/stack")
.needs(&[Chat, Repository])
.summary("Moves every branch in the stack back onto the one below it.")
.detail(
"Planned with `git replay` before anything moves, shown to you, then pushed \
atomically with leases.",
)
.keywords(&["rebase", "stacked", "branches"]),
Command::action(UiAction::ReviewReturnChat)
.needs(&[Review])
.summary("Back to the conversation, with the review kept pinned for when you return.")
.keywords(&["exit", "close", "chat"]),
Command::action(UiAction::ReviewFinish)
.needs(&[Review])
.summary("Decides what happens to your comments: send them, commit, or open a pull request.")
.detail("For a pull request, it posts the review to GitHub.")
.keywords(&["done", "accept"]),
Command::action(UiAction::ReviewRefresh)
.needs(&[Review])
.summary("Rebuilds the review from its source, so it shows the latest changes.")
.keywords(&["reload"]),
Command::action(UiAction::ReviewSource)
.needs(&[Review])
.summary("Reviews something else: the working tree, the last turn, a base, a commit.")
.keywords(&["target", "base", "commit"]),
Command::action(UiAction::ReviewAddFinding)
.needs(&[Review])
.summary("Writes a comment on the line under the cursor, for the agent to act on.")
.detail("In a pull request's review, it is posted with the review instead.")
.keywords(&["finding", "note"]),
Command::action(UiAction::ReviewAskQuestion)
.needs(&[Review])
.summary("Asks the agent about the line under the cursor; it answers and never edits.")
.keywords(&["question"]),
Command::action(UiAction::ReviewFindings)
.needs(&[Review])
.summary("Every comment on this review, to send, reply to or verify.")
.keywords(&["findings", "feedback"]),
Command::action(UiAction::ReviewSend)
.needs(&[Review])
.summary("Sends every unsent comment to the agent to act on.")
.keywords(&["submit", "agent"]),
Command::action(UiAction::ReviewOpenInBrowser)
.needs(&[PullRequestReview])
.summary("Opens this pull request in the browser.")
.keywords(&["browser", "web"]),
Command::action(UiAction::ReviewToggleGuide)
.needs(&[Review])
.summary("Shows or hides the guide beside the diff.")
.keywords(&["prose", "chapters"]),
Command::action(UiAction::ReviewToggleNoise)
.needs(&[Review])
.summary("Opens or folds the churn the review collapsed, like lockfiles and moves.")
.keywords(&["noise", "generated"]),
Command::action(UiAction::ReviewToggleWordWrap)
.needs(&[Review])
.summary("Wraps long lines in the diff, or lets them run off the edge.")
.keywords(&["wrap"]),
// === Status, setup and signing in ===
Command::slash(id::LSP, "Language servers", "/lsp")
.needs(&[Chat])
.summary("Every configured language server, whether it started, and what it is doing.")
.keywords(&["diagnostics"]),
Command::slash(id::DEBUG, "Debug adapters", "/debug")
.needs(&[Chat])
.summary("Every configured debug adapter, and whether it can be reached.")
.keywords(&["dap", "debugger"]),
Command::slash(id::MCP, "MCP servers", "/mcp")
.needs(&[Chat])
.summary("Every configured MCP server, its transport, and the tools it exposes.")
.keywords(&["servers"]),
Command::slash(id::TOOLS, "Tools", "/tools")
.needs(&[Chat])
.summary("Every tool the agent can reach this run, and the ones it cannot.")
.keywords(&["capabilities"]),
Command::slash(id::IMAGES, "Inline images", "/images")
.needs(&[Chat])
.summary("What this terminal can draw, and why.")
.keywords(&["graphics", "pictures", "kitty"]),
Command::slash(id::LOGIN, "Sign in", "/login")
.needs(&[Chat])
.summary("Adds a credential for a provider.")
.detail("Bare, it lists the providers. With a name, it goes straight to that one.")
.usage(&[("/login", ""), ("/login <provider>", "")])
.keywords(&["api key", "credentials"]),
Command::slash(id::LOGOUT, "Sign out", "/logout")
.needs(&[Chat])
.summary("Removes the credential Luxe stored for a provider.")
.detail("Bare, it lists what is signed in.")
.usage(&[("/logout <provider>", "")])
.keywords(&["credentials"]),
Command::slash(id::AUTH, "Credentials", "/auth")
.needs(&[Chat])
.summary("Which providers you are signed in to, and how.")
.keywords(&["login", "api key"]),
Command::slash(id::CONFIG, "Configuration", "/config")
.needs(&[Chat])
.summary("Providers, keys, settings and the config files, in one surface.")
.keywords(&["setup", "providers", "login"]),
Command::slash(id::SETTINGS, "Settings", "/settings")
.needs(&[Chat])
.summary("Appearance, the conversation, the dock, tools and the agent, as controls.")
.detail(
"Changes are written to your `config.json`, keeping everything else in it. `e` \
opens the file, and a value this project's `.luxe/config.json` sets is shown but \
changed there.",
)
.keywords(&["preferences", "options", "tools", "config"]),
]
}

View File

@@ -0,0 +1,37 @@
//! Ids of the commands run by id rather than by a key action.
//!
//! The built-in table and every match that runs one name these, so a renamed or a
//! new command cannot be matched by a string nothing defines.
pub(crate) const AUTH: &str = "cmd.auth";
pub(crate) const CHANGES: &str = "cmd.changes";
pub(crate) const COMPACT: &str = "cmd.compact";
pub(crate) const CONFIG: &str = "cmd.config";
pub(crate) const CONTEXT: &str = "cmd.context";
pub(crate) const COST: &str = "cmd.cost";
pub(crate) const DEBUG: &str = "cmd.debug";
pub(crate) const DIFF: &str = "cmd.diff";
pub(crate) const DOCK: &str = "cmd.dock";
pub(crate) const EDITOR: &str = "cmd.editor";
pub(crate) const GITHUB: &str = "cmd.github";
pub(crate) const HELP: &str = "cmd.help";
pub(crate) const IMAGES: &str = "cmd.images";
pub(crate) const LOGIN: &str = "cmd.login";
pub(crate) const LOGOUT: &str = "cmd.logout";
pub(crate) const LSP: &str = "cmd.lsp";
pub(crate) const MCP: &str = "cmd.mcp";
pub(crate) const MODE: &str = "cmd.mode";
pub(crate) const MODEL: &str = "cmd.model";
pub(crate) const MOUSE: &str = "cmd.mouse";
pub(crate) const NEW: &str = "cmd.new";
pub(crate) const PERMISSIONS: &str = "cmd.permissions";
pub(crate) const PR: &str = "cmd.pr";
pub(crate) const REVIEW: &str = "cmd.review";
pub(crate) const SESSIONS: &str = "cmd.sessions";
pub(crate) const SETTINGS: &str = "cmd.settings";
pub(crate) const STACK: &str = "cmd.stack";
pub(crate) const STATUSLINE: &str = "cmd.statusline";
pub(crate) const THEME: &str = "cmd.theme";
pub(crate) const THINKING: &str = "cmd.thinking";
pub(crate) const TOOLS: &str = "cmd.tools";
pub(crate) const WORKTREE: &str = "cmd.worktree";

View File

@@ -0,0 +1,31 @@
//! Command ranking — the order the palette and the slash menu list matches in.
use super::Command;
/// Ranks `commands` against `query`: fuzzy on each [`Command::haystack`], by keyword prefix
/// otherwise, best first, ties in the order given.
///
/// Returns each match's index into `commands` with the haystack positions that matched, empty for
/// a keyword match since nothing it matched is on screen. A blank query keeps the order given.
pub fn rank(query: &str, commands: &[&Command]) -> Vec<(usize, Vec<usize>)> {
let query = query.trim();
if query.is_empty() {
return (0..commands.len()).map(|index| (index, Vec::new())).collect();
}
let haystacks: Vec<String> = commands.iter().map(|command| command.haystack()).collect();
let haystacks: Vec<&str> = haystacks.iter().map(String::as_str).collect();
let mut found: Vec<(usize, i64, Vec<usize>)> = crate::fuzzy::rank(query, &haystacks)
.into_iter()
.map(|matched| (matched.idx, matched.score, matched.positions))
.collect();
for (index, command) in commands.iter().enumerate() {
if found.iter().any(|(kept, ..)| *kept == index) {
continue;
}
if let Some(score) = command.keyword_score(query) {
found.push((index, score, Vec::new()));
}
}
found.sort_by(|left, right| right.1.cmp(&left.1).then(left.0.cmp(&right.0)));
found.into_iter().map(|(index, _, positions)| (index, positions)).collect()
}

View File

@@ -0,0 +1,394 @@
use super::*;
/// The places a palette can open, from a fresh session to a pull request's review, so a property
/// that must hold everywhere is checked everywhere.
fn contexts() -> Vec<(&'static str, CommandContext)> {
let idle = CommandContext::default();
let busy = CommandContext {
has_turn: true,
has_image: true,
messages_waiting: true,
in_repository: true,
..CommandContext::default()
};
let changes = CommandContext { changes_pane: true, ..busy.clone() };
let review = CommandContext { surface: Surface::Review, ..busy.clone() };
let pull_request = CommandContext { pull_request_review: true, ..review.clone() };
vec![
("a fresh session", idle),
("a conversation", busy),
("the Changes pane", changes),
("a review", review),
("a pull request's review", pull_request),
]
}
fn names(menu: &Menu) -> Vec<&str> {
menu.entries.iter().map(|entry| entry.command.name.as_ref()).collect()
}
fn menu(context: &CommandContext, recent: &[&str]) -> Menu {
let recent: Vec<String> = recent.iter().map(|id| id.to_string()).collect();
CommandRegistry::all().arrange(context, &KeyMap::defaults(), &recent)
}
#[test]
fn ids_and_slash_triggers_are_unique() {
let registry = CommandRegistry::all();
let mut ids: Vec<&str> = registry.iter().map(|command| command.id.as_ref()).collect();
ids.sort_unstable();
ids.dedup();
assert_eq!(ids.len(), registry.len(), "command ids must be unique");
let mut slashes: Vec<&str> = registry.iter().filter_map(Command::slash_name).collect();
let count = slashes.len();
slashes.sort_unstable();
slashes.dedup();
assert_eq!(slashes.len(), count, "slash triggers must be unique");
}
/// Every slash command that shipped before still answers to its name, collapsed or not.
#[test]
fn every_slash_trigger_still_parses() {
let registry = CommandRegistry::all();
for name in [
"/new",
"/sessions",
"/model",
"/thinking",
"/mode",
"/review",
"/theme",
"/help",
"/context",
"/compact",
"/cost",
"/worktree",
"/github",
"/stack",
"/pr",
"/preview",
"/diff",
"/dock",
"/statusline",
"/mouse",
"/permissions",
"/lsp",
"/debug",
"/mcp",
"/tools",
"/images",
"/login",
"/logout",
"/auth",
"/config",
"/quit",
"/reload",
"/search",
] {
assert!(registry.parse_slash(name).is_some(), "missing slash trigger {name}");
}
assert!(registry.parse_slash("/new").is_some_and(|c| c.kind == CommandKind::Slash));
assert_eq!(
registry.parse_slash("/quit").map(|c| c.kind),
Some(CommandKind::Action(UiAction::Quit)),
"an action with a slash trigger runs as the action"
);
}
/// `/peek` is what the preview was called, and it still opens it, arguments and all.
#[test]
fn a_renamed_trigger_still_works() {
let registry = CommandRegistry::all();
let old = registry.parse_slash("/peek src/app.rs").expect("the old trigger");
assert_eq!(old.slash_name(), Some("/preview"));
assert_eq!(old.args.as_deref(), Some("src/app.rs"));
}
#[test]
fn parse_slash_keeps_trimmed_arguments_and_only_at_the_start() {
let registry = CommandRegistry::all();
let diff = registry.parse_slash("/diff base main ").expect("known command");
assert_eq!(diff.id, "cmd.diff");
assert_eq!(diff.args.as_deref(), Some("base main"));
assert_eq!(registry.parse_slash("/statusline").and_then(|c| c.args), None);
assert!(registry.parse_slash("/unknown").is_none());
assert!(registry.parse_slash("say /help").is_none());
}
/// A name is something you would say out loud: short, no punctuation standing in for a
/// description, and a summary that is one sentence.
#[test]
fn names_are_names_and_summaries_are_sentences() {
for command in CommandRegistry::all().iter() {
let name = command.name.as_ref();
assert!(name.split_whitespace().count() <= 4, "{name:?} is more than four words");
assert!(!name.contains(['(', ')', ':', ',', '<']), "{name:?} carries punctuation");
let summary = command.summary.as_ref();
assert!(summary.ends_with('.'), "{name}: the summary is a sentence: {summary:?}");
assert!(summary.chars().count() <= 90, "{name}: the summary runs long: {summary:?}");
assert!(!summary.contains(". "), "{name}: one sentence: {summary:?}");
for (form, _) in &command.usage {
let slash = command.slash_name().expect("only slash commands take arguments");
assert!(form.starts_with(slash), "{name}: {form:?} is not a form of {slash}");
}
}
}
/// Two rows the reader has to choose between never share a name. The same words in contexts
/// that never list together are fine: that is the same act on two surfaces.
#[test]
fn names_are_unique_wherever_they_list() {
for (place, context) in contexts() {
let menu = menu(&context, &[]);
let mut seen = names(&menu);
let count = seen.len();
seen.sort_unstable();
seen.dedup();
assert_eq!(seen.len(), count, "a name repeats in {place}: {:?}", names(&menu));
}
}
/// Keys that move around, editor mechanics, and commands about "the selected" thing are keys,
/// not commands; none of them may creep back into a list you search.
#[test]
fn keys_and_mechanics_are_not_commands() {
let registry = CommandRegistry::all();
let has = |action: UiAction| registry.iter().any(|command| command.keys == Some(action));
for action in [
UiAction::Submit,
UiAction::NewLine,
UiAction::Cancel,
UiAction::OpenPalette,
UiAction::PasteClipboard,
UiAction::SelectAll,
UiAction::CopyCode,
UiAction::CopySelection,
UiAction::EditLastMessage,
UiAction::ScrollUp,
UiAction::PageDown,
UiAction::SelectBlockUp,
UiAction::ShowDock,
UiAction::HideDock,
UiAction::ResetDockAuto,
UiAction::ShowStatusline,
UiAction::HideStatusline,
UiAction::ResetStatuslineAuto,
UiAction::ChangesFileNext,
UiAction::ChangesFilePrev,
UiAction::ReviewExit,
UiAction::ReviewOpenSelection,
UiAction::ReviewChapterNext,
UiAction::ReviewFileNext,
UiAction::ReviewHunkNext,
UiAction::ReviewLineNext,
UiAction::ReviewPagePrev,
UiAction::ReviewScrollLeft,
UiAction::ReviewLineStart,
UiAction::ReviewEditFinding,
UiAction::ReviewDeleteFinding,
UiAction::ReviewResolveFinding,
UiAction::ReviewReanchorFinding,
UiAction::ReviewHelp,
UiAction::DashboardQuit,
] {
assert!(!has(action), "{} should not be a command", action.id());
}
}
/// The complaint this list exists to answer: a fresh session lists nothing about a review, and a
/// review lists nothing that only means something in the conversation.
#[test]
fn a_menu_lists_only_what_can_run_there() {
let fresh = menu(&CommandContext::default(), &[]);
let listed = names(&fresh);
for absent in
["Leave review", "Finish review", "Comment on this line", "Ask again", "View image"]
{
assert!(!listed.contains(&absent), "a fresh session lists {absent:?}");
}
for present in ["New session", "Change model", "Review changes", "Help", "Quit"] {
assert!(listed.contains(&present), "a fresh session is missing {present:?}");
}
assert!(!listed.contains(&"Pull request"), "no checkout, no pull request");
let review = CommandContext { surface: Surface::Review, ..CommandContext::default() };
let review_menu = menu(&review, &[]);
let listed = names(&review_menu);
// A review draws no picker and no transcript over itself, so what opens one stays in the chat
for absent in
["New session", "Review changes", "Session cost", "Open on GitHub", "Change model"]
{
assert!(!listed.contains(&absent), "a review lists {absent:?}");
}
for present in ["Leave review", "Finish review", "Side by side", "Help", "Quit"] {
assert!(listed.contains(&present), "a review is missing {present:?}");
}
let every = CommandRegistry::all().len();
assert!(fresh.entries.len() < every, "a fresh session lists a subset");
}
/// Unfiltered, a menu is predictable: alphabetical by name, with nothing out of place.
#[test]
fn an_unfiltered_menu_is_alphabetical() {
for (place, context) in contexts() {
let menu = menu(&context, &[]);
assert_eq!(menu.recent, 0);
let listed: Vec<String> = names(&menu).iter().map(|name| name.to_lowercase()).collect();
let mut sorted = listed.clone();
sorted.sort();
assert_eq!(listed, sorted, "{place} is not alphabetical");
}
}
/// What you just used leads, most recent first and at most five, then the alphabet resumes
/// without them. One that cannot run here is skipped, and the next recent one takes its place.
#[test]
fn recently_used_commands_lead_the_menu() {
let recent = [
"cmd.pr",
"tui.review.finish",
"cmd.model",
"cmd.new",
"cmd.cost",
"tui.app.quit",
"cmd.theme",
"cmd.diff",
];
let menu = menu(&CommandContext::default(), &recent);
let listed = names(&menu);
assert_eq!(menu.recent, RECENT_SHOWN);
assert_eq!(
&listed[..RECENT_SHOWN],
["Change model", "New session", "Session cost", "Quit", "Change theme"],
"Pull request needs a checkout and Finish review a review, so both are skipped"
);
assert_eq!(listed.iter().filter(|name| **name == "Change model").count(), 1, "listed once");
let rest: Vec<String> = listed[RECENT_SHOWN..].iter().map(|name| name.to_lowercase()).collect();
let mut sorted = rest.clone();
sorted.sort();
assert_eq!(rest, sorted, "the rest stays alphabetical");
assert!(rest.contains(&"review changes".to_string()), "a sixth recent is not lost");
let none = self::menu(&CommandContext::default(), &["cmd.gone", "tui.review.finish"]);
assert_eq!(none.recent, 0, "an id nobody knows, and one that cannot run, lead nothing");
}
/// The key shown beside a command is the one bound now, not the one that shipped.
#[test]
fn a_menu_shows_the_key_bound_now() {
let chord_of = |menu: &Menu, name: &str| {
menu.entries.iter().find(|entry| entry.command.name == name).and_then(|e| e.chord.clone())
};
let context = CommandContext::default();
let shipped = CommandRegistry::all().arrange(&context, &KeyMap::defaults(), &[]);
assert_eq!(chord_of(&shipped, "Review changes").as_deref(), Some("ctrl+g"));
assert_eq!(chord_of(&shipped, "Context Dock").as_deref(), Some("alt+d"));
assert_eq!(chord_of(&shipped, "Help"), None, "help ships unbound");
let rebound = KeyMap::defaults().with_overrides(std::collections::HashMap::from([(
"tui.app.toggle_help".to_string(),
vec!["f1".to_string()],
)]));
let menu = CommandRegistry::all().arrange(&context, &rebound, &[]);
assert_eq!(chord_of(&menu, "Help").as_deref(), Some("f1"));
}
#[test]
fn filtering_a_menu_keeps_its_recent_lead_honest() {
let menu = menu(&CommandContext::default(), &["cmd.new", "tui.app.quit", "cmd.model"]);
assert_eq!(menu.recent, 3);
let slash_only = menu.filtered(|command| command.id != "tui.app.quit");
assert_eq!(slash_only.recent, 2);
assert_eq!(names(&slash_only)[..2], ["New session", "Change model"]);
}
/// 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.
#[test]
fn a_later_source_cannot_take_a_built_in_id_or_trigger() {
let impostor = |id: &'static str, slash: &'static str| {
Command::slash(id, "Impostor", slash).summary("Pretends.")
};
let registry = CommandRegistry::from_sources([
built_in(),
vec![impostor("cmd.new", "/fresh"), impostor("my.new", "/new"), impostor("my.x", "/x")],
]);
assert_eq!(registry.len(), built_in().len() + 1, "only the command with a free name joins");
assert_eq!(registry.parse_slash("/new").map(|c| c.name), Some("New session".into()));
assert!(registry.parse_slash("/x").is_some());
assert!(!registry.is_empty());
let none = CommandRegistry::from_sources(Vec::<Vec<Command>>::new());
assert!(none.is_empty() && none.iter().next().is_none(), "no sources, no commands");
}
#[test]
fn the_haystack_is_the_name_and_trigger_and_never_the_summary() {
let registry = CommandRegistry::all();
let credentials = registry.iter().find(|c| c.id == "cmd.auth").expect("present");
assert_eq!(credentials.haystack(), "Credentials auth");
let swap = registry.iter().find(|c| c.id == "tui.workspace.toggle_dock_position").unwrap();
assert_eq!(swap.haystack(), "Swap the sidebar's side", "no trigger, just the name");
}
fn ranked(query: &str) -> Vec<String> {
let menu = menu(&CommandContext::default(), &[]);
let commands: Vec<&Command> = menu.entries.iter().map(|entry| &entry.command).collect();
rank(query, &commands).into_iter().map(|(index, _)| commands[index].name.to_string()).collect()
}
/// A command found by what it is called outranks one found by what it is about: `/diff` is
/// Review changes, and Preview only knows the word.
#[test]
fn a_name_or_trigger_outranks_a_keyword() {
let found = ranked("diff");
assert_eq!(found[..2], ["Review changes", "Preview"], "{found:?}");
assert_eq!(ranked("exit").first().map(String::as_str), Some("Quit"));
assert_eq!(ranked("keys").first().map(String::as_str), Some("Help"), "the old name finds it");
assert_eq!(ranked("api").first().map(String::as_str), Some("Credentials"), "and API keys");
}
/// Keywords are vocabulary: they match from the start of one of their words, never scattered.
#[test]
fn a_keyword_matches_from_the_start_of_a_word() {
let registry = CommandRegistry::all();
let compact = registry.parse_slash("/compact").expect("present");
assert!(compact.keyword_score("shri").is_some(), "the start of a word");
assert!(compact.keyword_score("hunk").is_none(), "not the letters of \"shrink\"");
assert!(compact.keyword_score("rink").is_none(), "not the middle of a word");
let permissions = registry.parse_slash("/permissions").expect("present");
assert!(permissions.keyword_score("walk aw").is_some(), "a phrase from its start");
assert!(permissions.keyword_score("away").is_some(), "or any word in it");
assert!(ranked("hunk").is_empty(), "nothing in a conversation is about hunks");
assert!(ranked(" ").len() > 20, "a blank query keeps everything");
}
#[test]
fn needs_describe_what_is_missing() {
let fresh = CommandContext::default();
let pr = CommandRegistry::all().parse_slash("/pr").expect("present");
assert_eq!(pr.unmet(&fresh), Some(Need::Repository));
assert_eq!(Need::Repository.describe(), "a git checkout");
let in_checkout = CommandContext { in_repository: true, ..fresh.clone() };
assert!(pr.available(&in_checkout));
let review = CommandContext { surface: Surface::Review, in_repository: true, ..fresh };
assert_eq!(pr.unmet(&review), Some(Need::Chat), "the first unmet need is the one named");
}
/// What one launch ran leads the next one's menu; the default holder never writes anywhere, which
/// is what keeps a test's commands out of the reader's state file.
#[test]
fn recent_commands_survive_a_relaunch_and_the_default_stays_in_memory() {
let directory = tempfile::tempdir().expect("temp dir");
let path = directory.path().join("state.json");
let mut first = RecentCommands::persisted(path.clone());
assert!(first.ids().is_empty());
first.record("cmd.cost");
first.record("cmd.new");
first.record("cmd.cost");
assert_eq!(first.ids(), ["cmd.cost", "cmd.new"]);
assert_eq!(RecentCommands::persisted(path.clone()).ids(), ["cmd.cost", "cmd.new"]);
let mut transient = RecentCommands::default();
transient.record("cmd.model");
assert_eq!(transient.ids(), ["cmd.model"]);
assert_eq!(RecentCommands::persisted(path).ids(), ["cmd.cost", "cmd.new"], "untouched");
}