Add slash command argument completion to the TUI composer (#62343)

## Why

The slash command menu helps users find commands, but leaves them to
recall fixed arguments such as `on` and `off` for `/raw`.

## What changed

Show prefix-filtered suggestions for the first argument of supported
slash commands. For example, type `/mcp lo` and press `Tab` to complete
`/mcp login`. `Enter` and configured submit shortcuts still submit the
draft as typed.

Give mention completion priority and limit argument suggestions to
commands available in the current thread and connection state.

## Testing

Add tests for popup rendering, argument replacement, submit shortcuts,
and changes in thread availability and connection state.

GitOrigin-RevId: 8682c323064457dd9307b0a1520469011a8df9f3
This commit is contained in:
Benjamin Carlsson
2026-11-18 19:11:14 +00:00
committed by copyberry
parent 71527c18c7
commit 42cf4edfcd
15 changed files with 708 additions and 57 deletions
+13
View File
@@ -28,6 +28,7 @@ use ratatui::text::Line;
use super::App;
use super::InitialHistoryReplayBuffer;
use crate::bottom_pane::RestrictedInputMode;
use crate::history_cell;
use crate::history_cell::HistoryCell;
use crate::insert_history::HistoryLineWrapPolicy;
@@ -430,6 +431,18 @@ impl App {
tui: &mut tui::Tui,
size: ratatui::layout::Size,
) -> Result<()> {
let input_mode = if self.reconnect.offline {
Some(RestrictedInputMode::Disconnected)
} else if self
.current_displayed_thread_id()
.is_some_and(|id| self.thread_unavailable(id))
{
Some(RestrictedInputMode::UnavailableThread)
} else {
None
};
self.chat_widget
.set_composer_restricted_input_mode(input_mode);
self.flush_native_history(tui);
if tui.is_owned_screen() {
self.transcript_reflow.note_width(size.width);
+18
View File
@@ -302,6 +302,24 @@ async fn completed_global_chords_toggle_output_and_request_external_editor() ->
Ok(())
}
#[tokio::test]
async fn composer_submit_chord_works_with_slash_argument_popup() -> Result<()> {
let (mut app, mut tui, mut app_server) = chord_app().await?;
let config = toml::from_str("[composer]\nsubmit = 'ctrl-x enter'")?;
app.keymap = RuntimeKeymap::from_config(&config).expect("valid composer submit chord");
app.chat_widget.apply_keymap_update(config, &app.keymap);
app.chat_widget.set_raw_output_mode(/*enabled*/ true);
app.chat_widget.apply_external_edit("/raw off".to_owned());
assert!(!app.chat_widget.no_modal_or_popup_active());
press(&mut app, &mut tui, &mut app_server, ctrl('x')).await?;
assert!(app.key_chord_matcher.is_pending());
assert!(app.chat_widget.raw_output_mode());
press(&mut app, &mut tui, &mut app_server, KeyCode::Enter.into()).await?;
assert!(!app.chat_widget.raw_output_mode());
Ok(())
}
#[tokio::test]
async fn wrong_second_stroke_passes_through_but_escape_is_consumed() -> Result<()> {
let (mut app, mut tui, mut app_server) = chord_app().await?;
@@ -254,3 +254,43 @@ async fn unavailable_thread_new_and_clear_start_a_writable_session() -> Result<(
}
Ok(())
}
#[tokio::test]
async fn argument_popup_tracks_thread_availability_before_the_next_key() -> Result<()> {
let (mut app, _events, _ops) = make_test_app_with_channels().await;
let id = ThreadId::new();
app.active_thread_id = Some(id);
app.primary_thread_id = Some(id);
app.app_server_target = AppServerTarget::Remote {
endpoint: crate::resolve_remote_addr("ws://127.0.0.1:1")?,
};
app.chat_widget
.handle_thread_session(test_thread_session(id, app.config.cwd.to_path_buf()));
app.ensure_thread_channel(id).mark_live();
app.chat_widget
.restore_user_message_to_composer("/mcp ".into());
assert!(!app.chat_widget.no_modal_or_popup_active());
let mut tui = crate::tui::test_support::make_test_tui()?;
let size = tui.terminal.last_known_screen_size;
app.ensure_thread_channel(id).mark_replay_only();
app.handle_draw_pre_render(&mut tui, size)?;
app.chat_widget.pre_draw_tick();
assert!(app.chat_widget.no_modal_or_popup_active());
app.ensure_thread_channel(id).mark_live();
app.handle_draw_pre_render(&mut tui, size)?;
app.chat_widget.pre_draw_tick();
assert!(!app.chat_widget.no_modal_or_popup_active());
app.reconnect.offline = true;
app.handle_draw_pre_render(&mut tui, size)?;
app.chat_widget.pre_draw_tick();
assert!(app.chat_widget.no_modal_or_popup_active());
app.reconnect.offline = false;
app.handle_draw_pre_render(&mut tui, size)?;
app.chat_widget.pre_draw_tick();
assert!(!app.chat_widget.no_modal_or_popup_active());
Ok(())
}
+30 -34
View File
@@ -57,6 +57,7 @@
//! popup-specific handler if a popup is visible and otherwise to
//! [`ChatComposer::handle_key_event_without_popup`]. After every handled key, we call
//! [`ChatComposer::sync_popups`] so UI state follows the latest buffer/cursor.
//! The composer submit shortcut remains active while slash-argument suggestions are open.
//! A pending backend handoff uses the basic editor and paste detection while holding submission.
//! Redraws preserve the paste detector's window so trailing keys stay with the outgoing composer.
//! Fresh Vim drafts start in Insert; Normal `/` and `?` search the composer.
@@ -94,6 +95,8 @@
//! Slash-command dismissal is tracked separately. Pressing `Esc` while the command popup is active
//! records the first-line `/name` token and keeps the popup closed while that token is unchanged.
//! Editing the command token clears the dismissal and allows the popup to reopen.
//! Slash argument completion revalidates the live token before Tab replaces it; restricted
//! command dispatch dismisses completion immediately when it clears the draft.
//!
//! # History Navigation (↑/↓)
//!
@@ -119,8 +122,13 @@
//! keeps prompt-history search; explicitly configured keybindings retain precedence.
//! Vim queries stay draft-local.
//!
//! Slash commands are staged for local history instead of being recorded immediately. Command
//! recall is a two-phase handoff: stage the submitted slash text here, then record it after
//! Slash commands are staged for local history instead of being recorded immediately.
//! Finite first arguments have a separate completion menu: Tab inserts the selected argument,
//! while Enter submits the literal draft. Mentions retain priority over argument suggestions.
//! Argument suggestions retain the latest restricted routing mode across redraws and evaluate
//! completed arguments against parent-owned policy during ordinary input. Unavailable-thread
//! recovery keeps its existing exemption from that policy.
//! Command recall is a two-phase handoff: stage the submitted slash text here, then record it after
//! `ChatWidget` dispatches the command.
//!
//! # Question Draft Recovery
@@ -196,6 +204,7 @@
//! including `stop`), `/quit`, and `/exit`.
//! When connected but the thread is unavailable, configured
//! submit keys may dispatch explicitly allowed recovery and local commands; other drafts stay put.
//! Escape dismisses command and argument popups while preserving the Vim Insert-to-Normal transition.
//! Empty-prompt agents navigation remains available with its usual editor and draft guards.
//! Collapsed pastes expand into editable text so the full draft can be copied before quitting.
//!
@@ -428,6 +437,7 @@ mod popup_state;
mod reconnect;
pub(crate) use reconnect::RestrictedInputMode;
mod edit_history;
mod slash_argument;
mod slash_input;
mod sparkle;
mod status_surface;
@@ -1170,11 +1180,16 @@ impl ChatComposer {
}
let undo_enabled = self.config.undo_enabled && !self.draft.textarea.is_vim_enabled();
if self.popups.active() {
return if undo_enabled {
let contexts = if undo_enabled {
KeymapContextSet::composer_edit_only()
} else {
KeymapContextSet::default()
};
return if matches!(self.popups.active, ActivePopup::Argument(_)) {
contexts.with_composer_submit()
} else {
contexts
};
}
let contexts = self.draft.textarea.keymap_contexts();
let contexts = contexts.with(KeymapContext::Composer);
@@ -1809,6 +1824,7 @@ impl ChatComposer {
pub(crate) fn set_parent_owned_thread(&mut self) {
self.blocks_direct_input = true;
self.sync_slash_argument_popup(/*allow*/ true);
self.placeholder_text = "Viewing sub-agent — direct input is disabled".to_string();
}
@@ -2079,6 +2095,7 @@ impl ChatComposer {
/// Handle a key event coming from the main UI.
pub fn handle_key_event(&mut self, key_event: KeyEvent) -> (InputResult, bool) {
self.set_restricted_input_mode(/*mode*/ None);
if !self.draft.input_enabled {
return (InputResult::None, false);
}
@@ -2153,6 +2170,7 @@ impl ChatComposer {
key_event,
slash_input::SlashPopupInputMode::Normal,
),
ActivePopup::Argument(_) => self.handle_slash_argument_key(key_event),
ActivePopup::File(_) => self.handle_key_event_with_file_popup(key_event),
ActivePopup::Skill(_) => self.handle_key_event_with_skill_popup(key_event),
ActivePopup::MentionV2(_) => self.handle_key_event_with_mentions_v2_popup(key_event),
@@ -4154,9 +4172,14 @@ impl ChatComposer {
&& file_token.is_none()
&& mentions_v2_token.is_none()
&& mention_target.is_none();
self.sync_command_popup(allow_command_popup);
if !self.sync_slash_argument_popup(allow_command_popup) {
self.sync_command_popup(allow_command_popup);
}
if matches!(self.popups.active, ActivePopup::Command(_)) {
if matches!(
self.popups.active,
ActivePopup::Command(_) | ActivePopup::Argument(_)
) {
if self.popups.current_file_query.is_some() {
self.app_event_tx
.send(AppEvent::StartFileSearch(String::new()));
@@ -4766,7 +4789,7 @@ impl ChatComposer {
// Command and unified mention menus can render in a single row.
let height = if matches!(
self.popups.active,
ActivePopup::Command(_) | ActivePopup::MentionV2(_)
ActivePopup::Command(_) | ActivePopup::Argument(_) | ActivePopup::MentionV2(_)
) || height > 2
{
height
@@ -4786,6 +4809,7 @@ impl ChatComposer {
ratatui::widgets::Clear.render(popup_rect, buf);
match &self.popups.active {
ActivePopup::Command(popup) => popup.render_ref(popup_rect, buf),
ActivePopup::Argument(popup) => popup.render_ref(popup_rect, buf),
ActivePopup::MentionV2(popup) => popup.render_ref(popup_rect, buf),
ActivePopup::File(popup) => popup.render_ref(popup_rect, buf),
ActivePopup::Skill(popup) => popup.render_ref(popup_rect, buf),
@@ -10116,34 +10140,6 @@ mod tests {
assert_queued_bang_input(" !echo hi", "!echo hi", QueuedInputAction::Literal);
}
#[test]
fn slash_tab_completion_moves_cursor_to_end() {
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyModifiers;
let (tx, _rx) = unbounded_channel::<AppEvent>();
let sender = AppEventSender::new(tx);
let mut composer = ChatComposer::new(
/*has_input_focus*/ true,
sender,
/*enhanced_keys_supported*/ false,
"Ask Codex to do anything".to_string(),
/*disable_paste_burst*/ false,
);
type_chars_humanlike(&mut composer, &['/', 'c']);
let (_result, _needs_redraw) =
composer.handle_key_event(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE));
assert_eq!(composer.draft.textarea.text(), "/compact ");
assert_eq!(
composer.draft.textarea.cursor(),
composer.draft.textarea.text().len()
);
}
#[test]
fn slash_tab_completion_wins_over_queueing_while_task_running() {
use crossterm::event::KeyCode;
@@ -251,6 +251,7 @@ impl super::ChatComposer {
match &self.popups.active {
ActivePopup::None => composer,
ActivePopup::Command(_)
| ActivePopup::Argument(_)
| ActivePopup::File(_)
| ActivePopup::Skill(_)
| ActivePopup::MentionV2(_) => None,
@@ -1,6 +1,7 @@
//! Popup lifecycle state for the chat composer.
//! Tracks the single active popup plus dismissal/query state used to synchronize it.
use super::slash_argument::ArgumentPopup;
use crate::bottom_pane::command_popup::CommandPopup;
use crate::bottom_pane::file_search_popup::FileSearchPopup;
use crate::bottom_pane::mentions_v2::MentionV2Popup;
@@ -91,6 +92,8 @@ pub(super) struct PopupState {
pub(super) active: ActivePopup,
pub(super) daybreak_command_description: Option<&'static str>,
pub(super) dismissed_command_token: Option<String>,
pub(super) dismissed_argument_token: Option<String>,
pub(super) restricted_input_mode: Option<super::RestrictedInputMode>,
pub(super) dismissed_file_token: Option<DismissedToken>,
pub(super) current_file_query: Option<String>,
pub(super) dismissed_mention_token: Option<DismissedToken>,
@@ -108,6 +111,7 @@ pub(super) enum ActivePopup {
#[default]
None,
Command(CommandPopup),
Argument(ArgumentPopup),
File(FileSearchPopup),
Skill(SkillPopup),
MentionV2(MentionV2Popup),
@@ -123,6 +127,7 @@ impl ActivePopup {
match self {
Self::None => footer_total_height,
Self::Command(popup) => popup.calculate_required_height(width) + footer_total_height,
Self::Argument(popup) => popup.calculate_required_height(width) + footer_total_height,
Self::File(popup) => popup.calculate_required_height() + footer_total_height,
Self::Skill(popup) => popup.calculate_required_height(width) + footer_total_height,
Self::MentionV2(popup) => popup.calculate_required_height(width) + footer_total_height,
@@ -17,6 +17,14 @@ pub(crate) enum RestrictedInputMode {
}
impl ChatComposer {
pub(crate) fn set_restricted_input_mode(&mut self, mode: Option<RestrictedInputMode>) {
self.popups.restricted_input_mode = mode;
// Reconcile a popup opened before the routing mode changed, before Tab can accept it.
if matches!(self.popups.active, ActivePopup::Argument(_)) {
self.sync_slash_argument_popup(/*allow*/ true);
}
}
/// Preserve Enter inside a paste burst without attempting submission.
pub(crate) fn handle_paste_enter(&mut self, now: Instant) -> bool {
let in_slash_context = self.slash_commands_enabled()
@@ -64,6 +72,7 @@ impl ChatComposer {
key: KeyEvent,
mode: RestrictedInputMode,
) -> InputResult {
self.set_restricted_input_mode(Some(mode));
if mode == RestrictedInputMode::DraftHandoff {
if matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat) {
let now = tokio::time::Instant::now().into_std();
@@ -101,7 +110,10 @@ impl ChatComposer {
self.cancel_history_search();
self.attachments.clear_remote_image_selection();
if mode != RestrictedInputMode::UnavailableThread
|| !matches!(self.popups.active, ActivePopup::Command(_))
|| !matches!(
self.popups.active,
ActivePopup::Command(_) | ActivePopup::Argument(_)
)
{
self.popups.active = ActivePopup::None;
}
@@ -135,6 +147,28 @@ impl ChatComposer {
self.edit_restricted_draft(key);
return InputResult::None;
}
if mode == RestrictedInputMode::UnavailableThread
&& pending_pastes.is_empty()
&& matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat)
&& matches!(self.popups.active, ActivePopup::Argument(_))
&& !self.submit_keys.is_pressed(key)
&& (matches!(
key.code,
KeyCode::Tab | KeyCode::Up | KeyCode::Down | KeyCode::Esc
) || key.modifiers == KeyModifiers::CONTROL
&& matches!(key.code, KeyCode::Char('p' | 'n')))
{
let vim_escape = self.should_handle_vim_insert_escape(key);
let result = self.handle_slash_argument_key(key).0;
if vim_escape {
let first_line = self.draft.textarea.text().lines().next().unwrap_or("");
self.popups.dismissed_command_token =
slash_input::command_popup_filter_text(first_line, /*cursor*/ 0);
self.edit_restricted_draft(key);
}
self.sync_unavailable_slash_popup();
return result;
}
if mode == RestrictedInputMode::UnavailableThread
&& pending_pastes.is_empty()
&& matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat)
@@ -161,7 +195,7 @@ impl ChatComposer {
)
.0;
self.reset_vim_mode_after_successful_dispatch(&result);
self.sync_command_popup(/*allow*/ true);
self.sync_unavailable_slash_popup();
return result;
}
if !submit
@@ -201,12 +235,12 @@ impl ChatComposer {
if matches!(command, Some(SlashCommandItem::Builtin(command))
if matches!(command, SlashCommand::Warnings | SlashCommand::Config | SlashCommand::Rc | SlashCommand::Quit | SlashCommand::Exit)
|| mode == RestrictedInputMode::UnavailableThread && command.available_when_thread_unavailable())
{
let result = self
&& let Some(result) = self
.try_dispatch_bare_slash_command()
.or_else(|| self.try_dispatch_slash_command_with_args())
.unwrap_or(InputResult::None);
{
self.reset_vim_mode_after_successful_dispatch(&result);
self.popups.active = ActivePopup::None;
return result;
}
}
@@ -218,16 +252,21 @@ impl ChatComposer {
{
self.edit_restricted_draft(key);
if mode == RestrictedInputMode::UnavailableThread {
self.sync_command_popup(
self.slash_commands_enabled()
&& !self.draft.is_bash_mode
&& self.draft.textarea.vim_query().is_none(),
);
self.sync_unavailable_slash_popup();
}
}
InputResult::None
}
fn sync_unavailable_slash_popup(&mut self) {
let allow = self.slash_commands_enabled()
&& !self.draft.is_bash_mode
&& self.draft.textarea.vim_query().is_none();
if !self.sync_slash_argument_popup(allow) {
self.sync_command_popup(allow);
}
}
fn edit_restricted_draft(&mut self, key: KeyEvent) {
// Null is sent internally to clean up on disconnect or expand a paste.
let before = if key.code == KeyCode::Null {
@@ -293,22 +293,31 @@ fn unavailable_thread_accepts_highlighted_recovery_completion() {
#[test]
fn unavailable_thread_vim_escape_and_search_keep_popup_closed() {
let (mut composer, _) = new_test_composer();
composer.enable_vim_in_insert_mode();
for ch in "/sub".chars() {
for text in ["/sub", "/raw "] {
let (mut composer, _) = new_test_composer();
composer.enable_vim_in_insert_mode();
for ch in text.chars() {
composer.handle_restricted_key(
KeyCode::Char(ch).into(),
RestrictedInputMode::UnavailableThread,
);
}
assert!(matches!(
composer.popups.active,
ActivePopup::Command(_) | ActivePopup::Argument(_)
));
composer.handle_restricted_key(KeyCode::Esc.into(), RestrictedInputMode::UnavailableThread);
assert!(composer.draft.textarea.is_vim_normal_mode());
composer.sync_popups();
assert!(matches!(composer.popups.active, ActivePopup::None));
assert_eq!(composer.current_text(), text);
composer.handle_restricted_key(
KeyCode::Char(ch).into(),
KeyCode::Char('/').into(),
RestrictedInputMode::UnavailableThread,
);
assert!(composer.draft.textarea.vim_query().is_some());
assert!(matches!(composer.popups.active, ActivePopup::None));
}
composer.handle_restricted_key(KeyCode::Esc.into(), RestrictedInputMode::UnavailableThread);
assert!(composer.draft.textarea.is_vim_normal_mode());
composer.handle_restricted_key(
KeyCode::Char('/').into(),
RestrictedInputMode::UnavailableThread,
);
assert!(composer.draft.textarea.vim_query().is_some());
assert!(matches!(composer.popups.active, ActivePopup::None));
}
#[test]
@@ -0,0 +1,278 @@
//! Completion of finite first arguments for enabled slash commands.
//! Tab revalidates the live token before completing it; the configured submit shortcut
//! follows ordinary submission routing.
use std::ops::Range;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyModifiers;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::widgets::WidgetRef;
use super::ActivePopup;
use super::ChatComposer;
use super::InputResult;
use super::RestrictedInputMode;
use super::parent_owned_command_is_allowed;
use super::parse_slash_name;
use crate::bottom_pane::picker_style::selection_style;
use crate::bottom_pane::popup_consts::MAX_POPUP_ROWS;
use crate::bottom_pane::scroll_state::ScrollState;
use crate::bottom_pane::selection_popup_common::GenericDisplayRow;
use crate::bottom_pane::selection_popup_common::measure_rows_height;
use crate::bottom_pane::selection_popup_common::render_rows;
use crate::bottom_pane::slash_commands::SlashCommandItem;
use crate::bottom_pane::slash_commands::builtins_for_input;
use crate::key_hint::KeyBindingListExt;
use crate::slash_command::SlashCommand;
pub(super) fn choices(command: SlashCommand) -> &'static [&'static str] {
match command {
SlashCommand::Raw => &["on", "off"],
SlashCommand::Ide => &["on", "off", "status"],
SlashCommand::Usage => &["daily", "weekly", "cumulative"],
SlashCommand::Voice => &["settings", "mute", "stop"],
SlashCommand::Keymap => &["debug"],
SlashCommand::Goal => &["clear", "edit", "pause", "resume"],
SlashCommand::Mcp => &["verbose", "login"],
SlashCommand::Pets => &["off"],
_ => &[],
}
}
struct Target {
range: Range<usize>,
prefix: String,
identity: String,
choices: Vec<&'static str>,
}
pub(super) struct ArgumentPopup {
target: Target,
matches: Vec<&'static str>,
state: ScrollState,
}
impl ArgumentPopup {
fn new(target: Target) -> Option<Self> {
let prefix = target.prefix.to_ascii_lowercase();
let matches: Vec<_> = target
.choices
.iter()
.copied()
.filter(|value| value.starts_with(&prefix))
.collect();
if matches.is_empty() {
return None;
}
let mut state = ScrollState::new();
state.clamp_selection(matches.len());
Some(Self {
target,
matches,
state,
})
}
fn rows(&self) -> Vec<GenericDisplayRow> {
self.matches
.iter()
.enumerate()
.map(|(index, value)| GenericDisplayRow {
name: (*value).to_owned(),
name_prefix_spans: vec![if self.state.selected_idx == Some(index) {
"› ".into()
} else {
" ".into()
}],
selection_style: Some(selection_style()),
match_indices: Some((0..self.target.prefix.chars().count()).collect()),
..Default::default()
})
.collect()
}
pub(super) fn calculate_required_height(&self, width: u16) -> u16 {
measure_rows_height(&self.rows(), &self.state, MAX_POPUP_ROWS, width)
}
}
impl WidgetRef for ArgumentPopup {
fn render_ref(&self, area: Rect, buf: &mut Buffer) {
render_rows(
area,
buf,
&self.rows(),
&self.state,
MAX_POPUP_ROWS,
"no matches",
);
}
}
impl ChatComposer {
fn slash_argument_target(&self) -> Option<Target> {
let text = self.draft.textarea.text();
let line = text.split('\n').next()?;
let cursor = self.draft.textarea.cursor();
if cursor > line.len() || !line.is_char_boundary(cursor) {
return None;
}
let (name, _, start) = parse_slash_name(line)?;
if cursor <= 1 + name.len() || cursor < start {
return None;
}
let SlashCommandItem::Builtin(command) = self.slash_input().command(name)? else {
return None;
};
let choices = choices(command);
if choices.is_empty()
|| !builtins_for_input(self.builtin_command_flags())
.iter()
.any(|(_, visible)| *visible == command)
{
return None;
}
let end = start
+ line[start..]
.find(char::is_whitespace)
.unwrap_or(line.len() - start);
if cursor > end
|| self
.draft
.textarea
.text_element_ranges()
.any(|r| r.start < end && r.end > start)
{
return None;
}
match self.popups.restricted_input_mode {
Some(RestrictedInputMode::Disconnected | RestrictedInputMode::DraftHandoff) => {
return None;
}
Some(RestrictedInputMode::UnavailableThread)
if !command.available_when_thread_unavailable()
|| text.trim().lines().count() != 1 =>
{
return None;
}
Some(RestrictedInputMode::UnavailableThread) | None => {}
}
let choices: Vec<_> = choices
.iter()
.copied()
.filter(|value| {
// Restricted recovery dispatch intentionally bypasses parent-owned input policy.
if !self.blocks_direct_input
|| self.popups.restricted_input_mode
== Some(RestrictedInputMode::UnavailableThread)
{
return true;
}
let mut completed = text.to_owned();
completed.replace_range(start..end, value);
parse_slash_name(&completed)
.is_some_and(|(_, args, _)| parent_owned_command_is_allowed(command, args))
})
.collect();
if choices.is_empty() {
return None;
}
Some(Target {
range: start..end,
prefix: line[start..cursor].to_owned(),
identity: line[..end].to_owned(),
choices,
})
}
pub(super) fn sync_slash_argument_popup(&mut self, allow: bool) -> bool {
let target = allow.then(|| self.slash_argument_target()).flatten();
if self
.popups
.dismissed_argument_token
.as_ref()
.is_some_and(|identity| target.as_ref().is_some_and(|t| &t.identity == identity))
{
return false;
}
self.popups.dismissed_argument_token = None;
if let Some(target) = target {
if let ActivePopup::Argument(popup) = &self.popups.active
&& popup.target.identity == target.identity
&& popup.target.prefix == target.prefix
&& popup.target.range == target.range
&& popup.target.choices == target.choices
{
return true;
}
if let Some(popup) = ArgumentPopup::new(target) {
self.popups.active = ActivePopup::Argument(popup);
return true;
}
}
if matches!(self.popups.active, ActivePopup::Argument(_)) {
self.popups.active = ActivePopup::None;
}
false
}
pub(super) fn handle_slash_argument_key(&mut self, key: KeyEvent) -> (InputResult, bool) {
if self.submit_keys.is_pressed(key) {
return self.handle_key_event_without_popup(key);
}
let ActivePopup::Argument(popup) = &mut self.popups.active else {
unreachable!()
};
match (key.code, key.modifiers) {
(KeyCode::Up, _) | (KeyCode::Char('p'), KeyModifiers::CONTROL) => {
popup.state.move_up_wrap(popup.matches.len());
popup
.state
.ensure_visible(popup.matches.len(), MAX_POPUP_ROWS.min(popup.matches.len()));
}
(KeyCode::Down, _) | (KeyCode::Char('n'), KeyModifiers::CONTROL) => {
popup.state.move_down_wrap(popup.matches.len());
popup
.state
.ensure_visible(popup.matches.len(), MAX_POPUP_ROWS.min(popup.matches.len()));
}
(KeyCode::Tab, _) => {
if let Some(value) = popup
.state
.selected_idx
.and_then(|i| popup.matches.get(i))
.copied()
{
let range = popup.target.range.clone();
let identity = popup.target.identity.clone();
let prefix = popup.target.prefix.clone();
if self.slash_argument_target().is_some_and(|target| {
target.range == range
&& target.identity == identity
&& target.prefix == prefix
&& target.choices.contains(&value)
}) {
self.draft.textarea.replace_range(range.clone(), value);
self.draft.textarea.set_cursor(range.start + value.len());
self.popups.dismissed_argument_token =
self.slash_argument_target().map(|t| t.identity);
}
}
self.popups.active = ActivePopup::None;
}
(KeyCode::Esc, _) => {
self.popups.dismissed_argument_token = Some(popup.target.identity.clone());
self.popups.active = ActivePopup::None;
}
_ => return self.handle_key_event_without_popup(key),
}
(InputResult::None, true)
}
}
#[cfg(test)]
#[path = "slash_argument_tests.rs"]
mod tests;
@@ -0,0 +1,224 @@
#![cfg(test)]
use super::*;
use pretty_assertions::assert_eq;
use ratatui::Terminal;
use ratatui::backend::TestBackend;
#[test]
fn slash_argument_completion_and_dismissal() {
let (mut composer, _rx) = super::super::tests::new_test_composer();
composer.set_disable_paste_burst(/*disabled*/ true);
composer.draft.textarea.set_text_clearing_elements("/raw");
composer.draft.textarea.set_cursor(/*pos*/ 4);
composer.sync_popups();
composer.handle_key_event(KeyCode::Tab.into());
assert_eq!(composer.draft.textarea.text(), "/raw ");
assert!(matches!(composer.popups.active, ActivePopup::Argument(_)));
let mut terminal = Terminal::new(TestBackend::new(/*width*/ 8, /*height*/ 2)).unwrap();
terminal
.draw(|frame| {
let ActivePopup::Argument(popup) = &composer.popups.active else {
unreachable!()
};
popup.render_ref(frame.area(), frame.buffer_mut());
})
.unwrap();
insta::assert_snapshot!("slash_argument_popup", terminal.backend());
composer.handle_key_event(KeyCode::Down.into());
composer.handle_key_event(KeyCode::Tab.into());
assert_eq!(composer.draft.textarea.text(), "/raw off");
assert!(!composer.popup_active());
composer.draft.textarea.set_text_clearing_elements("/raw o");
composer.draft.textarea.set_cursor(/*pos*/ 6);
composer.sync_popups();
composer.handle_key_event(KeyCode::Esc.into());
composer.sync_popups();
assert!(!composer.popup_active());
composer.handle_key_event(KeyCode::Char('n').into());
assert!(matches!(composer.popups.active, ActivePopup::Argument(_)));
}
#[test]
fn slash_argument_completion_preserves_tail_and_enter_submits_literal() {
let (mut composer, _rx) = super::super::tests::new_test_composer();
composer
.draft
.textarea
.set_text_clearing_elements("/mcp loX server\nmore");
composer.draft.textarea.set_cursor(/*pos*/ 7);
composer.sync_popups();
composer.handle_key_event(KeyCode::Tab.into());
assert_eq!(composer.draft.textarea.text(), "/mcp login server\nmore");
composer.draft.textarea.set_text_clearing_elements("/raw o");
composer.draft.textarea.set_cursor(/*pos*/ 6);
composer.sync_popups();
assert_eq!(
composer.handle_key_event(KeyCode::Enter.into()).0,
InputResult::CommandWithArgs(SlashCommand::Raw, "o".to_owned(), Vec::new())
);
}
#[test]
fn slash_argument_popup_gives_modified_down_to_submit_binding() {
let (mut composer, _rx) = super::super::tests::new_test_composer();
let submit = KeyEvent::new(KeyCode::Down, KeyModifiers::CONTROL | KeyModifiers::ALT);
composer.submit_keys = vec![crate::key_hint::KeyBinding::from_event(submit)];
composer
.draft
.textarea
.set_text_clearing_elements("/raw off");
composer.draft.textarea.set_cursor(/*pos*/ 8);
composer.sync_popups();
assert!(matches!(composer.popups.active, ActivePopup::Argument(_)));
assert_eq!(
composer.handle_key_event(submit).0,
InputResult::CommandWithArgs(SlashCommand::Raw, "off".to_owned(), Vec::new())
);
}
#[test]
fn slash_argument_respects_catalog_and_unavailable_thread() {
let (mut composer, _rx) = super::super::tests::new_test_composer();
composer
.draft
.textarea
.set_text_clearing_elements("/usage ");
composer.draft.textarea.set_cursor(/*pos*/ 7);
composer.sync_popups();
assert!(!composer.popup_active());
composer.set_side_conversation_active(/*active*/ true);
composer.draft.textarea.set_text_clearing_elements("/mcp ");
composer.draft.textarea.set_cursor(/*pos*/ 5);
composer.sync_popups();
assert!(!composer.popup_active());
composer.set_side_conversation_active(/*active*/ false);
composer.draft.textarea.set_text_clearing_elements("/raw");
composer.draft.textarea.set_cursor(/*pos*/ 4);
composer.sync_popups();
let mode = super::super::reconnect::RestrictedInputMode::UnavailableThread;
composer.handle_restricted_key(KeyCode::Tab.into(), mode);
assert!(matches!(composer.popups.active, ActivePopup::Argument(_)));
composer.sync_popups();
composer.handle_restricted_key(KeyCode::Tab.into(), mode);
assert_eq!(composer.draft.textarea.text(), "/raw on");
}
#[test]
fn slash_argument_acceptance_revalidates_the_draft() {
let (mut composer, _rx) = super::super::tests::new_test_composer();
composer.set_disable_paste_burst(/*disabled*/ true);
composer.draft.textarea.set_text_clearing_elements("/raw ");
composer.draft.textarea.set_cursor(/*pos*/ 5);
composer.sync_popups();
// A different command can have the same still-valid replacement range.
composer.draft.textarea.set_text_clearing_elements("/ide ");
composer.draft.textarea.set_cursor(/*pos*/ 5);
composer.handle_slash_argument_key(KeyCode::Tab.into());
assert_eq!(composer.draft.textarea.text(), "/ide ");
composer.draft.textarea.set_text_clearing_elements("/raw ");
composer.draft.textarea.set_cursor(/*pos*/ 5);
composer.sync_popups();
let mode = super::super::reconnect::RestrictedInputMode::UnavailableThread;
assert_eq!(
composer.handle_restricted_key(KeyCode::Enter.into(), mode),
InputResult::Command(SlashCommand::Raw)
);
composer.handle_restricted_key(KeyCode::Tab.into(), mode);
assert_eq!(composer.draft.textarea.text(), "");
assert!(!composer.popup_active());
}
#[test]
fn slash_argument_revalidates_restricted_mode_before_acceptance_and_redraw() {
let (mut composer, _rx) = super::super::tests::new_test_composer();
composer.draft.textarea.set_text_clearing_elements("/mcp ");
composer.draft.textarea.set_cursor(/*pos*/ 5);
composer.sync_popups();
assert!(matches!(composer.popups.active, ActivePopup::Argument(_)));
let mode = RestrictedInputMode::UnavailableThread;
composer.handle_restricted_key(KeyCode::Tab.into(), mode);
assert_eq!(composer.draft.textarea.text(), "/mcp ");
composer.sync_popups();
assert!(!composer.popup_active());
composer.handle_restricted_key(KeyCode::Tab.into(), mode);
assert_eq!(composer.draft.textarea.text(), "/mcp ");
}
#[test]
fn slash_argument_respects_parent_owned_policy_before_acceptance() {
let (mut composer, _rx) = super::super::tests::new_test_composer();
composer.draft.textarea.set_text_clearing_elements("/raw ");
composer.draft.textarea.set_cursor(/*pos*/ 5);
composer.sync_popups();
assert!(matches!(composer.popups.active, ActivePopup::Argument(_)));
composer.set_parent_owned_thread();
composer.sync_popups();
assert!(!composer.popup_active());
// With no suggestion to accept, Tab retains ordinary bare-command submission.
assert_eq!(
composer.handle_key_event(KeyCode::Tab.into()).0,
InputResult::Command(SlashCommand::Raw)
);
assert_eq!(composer.draft.textarea.text(), "");
}
#[test]
fn slash_argument_restricted_completion_retains_single_line_recovery_semantics() {
let (mut composer, _rx) = super::super::tests::new_test_composer();
composer
.draft
.textarea
.set_text_clearing_elements("/raw o\nmore");
composer.draft.textarea.set_cursor(/*pos*/ 6);
composer.sync_popups();
composer.handle_restricted_key(KeyCode::Tab.into(), RestrictedInputMode::UnavailableThread);
composer.sync_popups();
assert!(!composer.popup_active());
assert_eq!(composer.draft.textarea.text(), "/raw o\nmore");
}
#[test]
fn parent_owned_unavailable_thread_retains_argument_recovery() {
let (mut composer, _rx) = super::super::tests::new_test_composer();
composer.set_parent_owned_thread();
composer.draft.textarea.set_text_clearing_elements("/raw ");
composer.draft.textarea.set_cursor(/*pos*/ 5);
composer.sync_popups();
assert!(!composer.popup_active());
let mode = RestrictedInputMode::UnavailableThread;
composer.handle_restricted_key(KeyCode::Null.into(), mode);
composer.sync_popups();
assert!(matches!(composer.popups.active, ActivePopup::Argument(_)));
composer.handle_restricted_key(KeyCode::Tab.into(), mode);
assert_eq!(composer.draft.textarea.text(), "/raw on");
assert_eq!(
composer.handle_restricted_key(KeyCode::Enter.into(), mode),
InputResult::CommandWithArgs(SlashCommand::Raw, "on".to_owned(), Vec::new())
);
}
#[test]
fn slash_tab_completion_moves_cursor_to_end() {
let (mut composer, _rx) = super::super::tests::new_test_composer();
super::super::tests::type_chars_humanlike(&mut composer, &['/', 'c']);
composer.handle_key_event(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE));
assert_eq!(composer.draft.textarea.text(), "/compact ");
assert_eq!(
composer.draft.textarea.cursor(),
composer.draft.textarea.text().len()
);
}
@@ -545,7 +545,9 @@ pub(super) fn selected_command_completion(
command: &CommandItem,
) -> Option<String> {
let selected_command_text = format!("/{}", command.command());
(!first_line.trim_start().starts_with(&selected_command_text))
let exact_with_arguments = first_line == selected_command_text
&& matches!(command, CommandItem::Builtin(cmd) if !super::slash_argument::choices(*cmd).is_empty());
(exact_with_arguments || !first_line.trim_start().starts_with(&selected_command_text))
.then(|| format!("{selected_command_text} "))
}
@@ -0,0 +1,6 @@
---
source: tui/src/bottom_pane/chat_composer/slash_argument_tests.rs
expression: terminal.backend()
---
"› on "
" off "
+4
View File
@@ -1139,6 +1139,10 @@ impl BottomPane {
self.request_redraw();
}
pub(crate) fn set_composer_restricted_input_mode(&mut self, mode: Option<RestrictedInputMode>) {
self.composer.set_restricted_input_mode(mode);
}
pub(crate) fn pre_draw_tick(&mut self) {
self.pre_draw_tick_at(Instant::now());
}
+4
View File
@@ -210,6 +210,10 @@ impl ChatWidget {
cancellation
}
pub(crate) fn set_composer_restricted_input_mode(&mut self, mode: Option<RestrictedInputMode>) {
self.bottom_pane.set_composer_restricted_input_mode(mode);
}
pub(crate) fn handle_restricted_key(
&mut self,
key: KeyEvent,
+12
View File
@@ -66,10 +66,16 @@ const FOCUSED_SIDEBAR: u64 = 1 << 29;
const TRANSCRIPT_SELECT: u64 = 1 << 30;
const COMPOSER_EDIT_ONLY: u64 = 1 << 31;
const CLOUD_ENVIRONMENT_SELECTION: u64 = 1 << 32;
const COMPOSER_SUBMIT: u64 = 1 << 33;
const TRANSCRIPT_BROWSING: u64 = 1 << 14;
impl KeymapContextSet {
/// Retain submission while an argument suggestion is open.
pub(crate) const fn with_composer_submit(self) -> Self {
Self(self.0 | COMPOSER_SUBMIT)
}
pub(crate) const fn composer_edit_only() -> Self {
Self(COMPOSER_EDIT_ONLY)
}
@@ -225,6 +231,12 @@ impl KeymapContextSet {
/// Whether this input path can dispatch the action, including focus-specific exclusions.
pub(crate) fn contains_action(self, action: KeymapActionId) -> bool {
if self.0 & COMPOSER_SUBMIT != 0
&& action.context == KeymapContext::Composer
&& action.action == "submit"
{
return true;
}
if self.0 & COMPOSER_EDIT_ONLY != 0 && action.context == KeymapContext::Composer {
let edit = matches!(action.action, "undo" | "redo");
return edit != self.contains(KeymapContext::Composer);