use std::sync::Arc;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use super::{
daemon_gate::{command_route, CommandRoute},
palette::{ActivePalette, DiscoveryCache, PALETTE_CACHE_TTL},
App, CommandChoice, CommandChoiceKind,
};
use crate::commands;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum CommandPaletteKeyOutcome {
Ignored,
Handled,
Submit,
}
impl App {
pub(super) fn command_context(&self) -> commands::CommandContext {
commands::CommandContext {
fast_mode_supported: self
.daemon_options
.as_ref()
.is_some_and(|options| options.fast_mode.is_some()),
}
}
pub(super) fn visible_command_matches(&mut self) -> Option<Vec<CommandChoice>> {
if self.input_ui.command_palette_dismissed() {
return None;
}
let matches = self.command_matches();
(!matches.is_empty()
&& (self.cursor_in_command_token()
|| !commands::argument_choices(
self.input_ui.text(),
self.input_ui.cursor(),
&self.command_context(),
)
.is_empty()
|| !self.mcp_argument_choices().is_empty()
|| self.skill_mention_cursor().is_some()))
.then_some(matches)
}
pub(super) fn command_matches(&mut self) -> Vec<CommandChoice> {
if let Some(cursor) = self.skill_mention_cursor() {
return self.skill_mention_choices(&cursor);
}
let context = self.command_context();
let arguments =
commands::argument_choices(self.input_ui.text(), self.input_ui.cursor(), &context);
if !arguments.is_empty() {
return arguments.iter().map(argument_command_choice).collect();
}
let mcp_arguments = self.mcp_argument_choices();
if !mcp_arguments.is_empty() {
return mcp_arguments;
}
let Some(prefix) = commands::command_prefix(self.input_ui.text()) else {
return Vec::new();
};
let prefix = prefix.trim_start_matches('/').to_ascii_lowercase();
let offered: Vec<_> = self
.daemon_options
.iter()
.flat_map(|options| &options.commands)
.filter(|command| command.kind == rho_protocol::CommandKind::Slash)
.collect();
let session_choice = |command: &rho_protocol::SessionCommand| CommandChoice {
name: command.name.clone(),
usage: match &command.input_hint {
Some(hint) => format!("/{} {hint}", command.name),
None => format!("/{}", command.name),
},
description: command.description.clone(),
kind: CommandChoiceKind::SessionCommand,
};
let mut builtins = commands::matching_commands(&prefix);
builtins.retain(|command| context.is_discoverable(command.id));
let exact = builtins
.iter()
.find(|command| command.name.eq_ignore_ascii_case(&prefix))
.copied();
let mut choices: Vec<_> = builtins
.into_iter()
.filter_map(|command| match command_route(command.id) {
CommandRoute::Prompt => offered
.iter()
.find(|offered| offered.name == command.name)
.map(|offered| session_choice(offered)),
CommandRoute::Ui | CommandRoute::Options => Some(CommandChoice {
name: command.name.into(),
usage: command.usage.into(),
description: command.description.into(),
kind: CommandChoiceKind::Builtin(command),
}),
})
.collect();
if let Some(command) = exact {
choices.extend(command.argument_choices.iter().map(argument_command_choice));
}
choices.extend(
offered
.iter()
.filter(|command| command.name.to_ascii_lowercase().starts_with(&prefix))
.filter(|command| {
!commands::COMMANDS
.iter()
.any(|builtin| builtin.name == command.name)
})
.map(|command| session_choice(command)),
);
choices
}
pub(super) fn discovered_skills(&mut self) -> Arc<Vec<crate::skills::Skill>> {
DiscoveryCache::get_or_refresh(&mut self.palette_caches.skills, PALETTE_CACHE_TTL, || {
crate::skills::discover(
&self.info.runtime.cwd,
crate::workspace::ProjectTrusts::of_this_process(),
)
})
}
pub(super) fn resolve_prompt_template(&self, name: &str, trailing: &str) -> Option<String> {
let template_name = crate::prompt_templates::command_template_name(name)?;
let templates = crate::prompt_templates::load(
&self.info.runtime.cwd,
self.info.runtime.prompt_template_home.as_deref(),
self.info.runtime.config_prompt_templates.clone(),
);
crate::prompt_templates::find(&templates, template_name)
.map(|template| crate::prompt_templates::expand(template, trailing))
}
#[cfg(test)]
pub(super) fn selected_command(&mut self) -> Option<CommandChoice> {
let matches = self.command_matches();
selected_command(&matches, self.input_ui.command_selection())
}
pub(super) fn dismiss_command_palette_on_esc(&mut self) {
if self.input_ui.text() == "/" {
self.input_ui.clear_text();
self.input_ui.set_cursor(0);
}
self.input_ui.set_command_palette_dismissed(true);
self.input_ui.reset_command_selection();
}
pub(super) fn handle_command_palette_key(&mut self, key: KeyEvent) -> CommandPaletteKeyOutcome {
let Some(ActivePalette::Command(matches)) = self.active_palette() else {
return CommandPaletteKeyOutcome::Ignored;
};
match (key.modifiers, key.code) {
(KeyModifiers::NONE, KeyCode::Up) => {
if !matches.is_empty() {
let next = if self.input_ui.command_selection() == 0 {
matches.len() - 1
} else {
self.input_ui.command_selection() - 1
};
self.input_ui.move_command_selection(next);
}
CommandPaletteKeyOutcome::Handled
}
(KeyModifiers::NONE, KeyCode::Down) => {
if !matches.is_empty() {
let next = (self.input_ui.command_selection() + 1) % matches.len();
self.input_ui.move_command_selection(next);
}
CommandPaletteKeyOutcome::Handled
}
(KeyModifiers::NONE, KeyCode::Tab) => {
if let Some(choice) = selected_command(&matches, self.input_ui.command_selection())
{
self.complete_command_choice(&choice);
self.input_ui.set_command_palette_dismissed(false);
self.clamp_command_selection();
}
CommandPaletteKeyOutcome::Handled
}
(KeyModifiers::NONE, KeyCode::Enter) => {
if let Some(choice) = selected_command(&matches, self.input_ui.command_selection())
.filter(|choice| self.enter_completes_choice(choice))
{
self.complete_command_choice(&choice);
self.clamp_command_selection();
}
CommandPaletteKeyOutcome::Submit
}
(KeyModifiers::NONE, KeyCode::Esc) => {
self.dismiss_command_palette_on_esc();
CommandPaletteKeyOutcome::Handled
}
_ => CommandPaletteKeyOutcome::Ignored,
}
}
pub(super) fn enter_completes_choice(&self, choice: &CommandChoice) -> bool {
match choice.kind {
CommandChoiceKind::Builtin(_) | CommandChoiceKind::SessionCommand => true,
CommandChoiceKind::BuiltinArgument(_) => self.input_ui.command_selection_explicit(),
CommandChoiceKind::McpPromptArgument { .. } => {
self.input_ui.command_selection_explicit()
|| self
.mcp_argument_cursor()
.is_some_and(|cursor| !cursor.key.typed.trim().is_empty())
}
CommandChoiceKind::SkillMention { .. } => {
self.input_ui.command_selection_explicit()
|| self
.skill_mention_cursor()
.is_some_and(|cursor| crate::skills::mention::mentionable(&cursor.typed))
}
}
}
pub(super) fn complete_command_choice(&mut self, choice: &CommandChoice) {
let (input, cursor) = match &choice.kind {
CommandChoiceKind::Builtin(spec) => {
self.input_ui
.set_submission_mode(super::InputSubmissionMode::ParseCommands);
commands::complete_command(self.input_ui.text(), self.input_ui.cursor(), spec)
}
CommandChoiceKind::BuiltinArgument(choice) => {
self.input_ui
.set_submission_mode(super::InputSubmissionMode::ParseCommands);
commands::complete_argument_choice(choice)
}
CommandChoiceKind::SessionCommand => {
self.input_ui
.set_submission_mode(super::InputSubmissionMode::ParseCommands);
complete_slash_command(self.input_ui.text(), self.input_ui.cursor(), &choice.name)
}
CommandChoiceKind::McpPromptArgument { value } => {
self.input_ui
.set_submission_mode(super::InputSubmissionMode::ParseCommands);
super::mcp_argument_completion::replace_value(
self.input_ui.text(),
value,
&choice.name,
)
}
CommandChoiceKind::SkillMention { token } => {
self.complete_skill_mention(token, &choice.name);
self.input_ui.set_shell_mode(None);
return;
}
};
self.input_ui.set_text_and_cursor(input, cursor);
self.input_ui.set_shell_mode(None);
}
}
pub(super) fn selected_command(
matches: &[CommandChoice],
selection: usize,
) -> Option<CommandChoice> {
matches
.get(selection.min(matches.len().saturating_sub(1)))
.cloned()
}
fn argument_command_choice(choice: &'static commands::CommandArgumentChoice) -> CommandChoice {
CommandChoice {
name: choice.completion.to_string(),
usage: choice.usage.to_string(),
description: choice.description.to_string(),
kind: CommandChoiceKind::BuiltinArgument(choice),
}
}
pub(super) fn slash_command_args(input: &str) -> &str {
let token_end = input
.char_indices()
.find_map(|(index, ch)| ch.is_whitespace().then_some(index))
.unwrap_or(input.len());
input[token_end..].trim_start()
}
pub(super) fn complete_slash_command(input: &str, cursor: usize, name: &str) -> (String, usize) {
let token_end = input
.char_indices()
.find_map(|(index, ch)| ch.is_whitespace().then_some(index))
.unwrap_or(input.len());
let token_len = input[..token_end].chars().count();
let args = slash_command_args(input);
let completed = if args.is_empty() {
format!("/{name}")
} else {
format!("/{name} {args}")
};
let completed_token_len = name.chars().count() + 1;
let new_cursor = if cursor <= token_len {
completed_token_len
} else {
completed
.chars()
.count()
.min(completed_token_len.saturating_add(cursor.saturating_sub(token_len)))
};
(completed, new_cursor)
}
#[cfg(test)]
#[path = "command_palette_tests.rs"]
mod tests;