Disambiguate skill mentions from shell parameters (#33232)

## Why

Skill mentions and shell parameters both use a `$` prefix. Numeric and special
shell parameters should not open or displace completion popups, while loaded
skills can legitimately have digit- or hyphen-leading names.

## What changed

- Classify `$` queries as skill candidates, shell variables, definite shell
  parameters, or ambiguous shell-like names.
- Offer completion for an ambiguous name only when it fuzzy-matches a bindable
  loaded mention, reusing the filtered catalog when the popup opens.
- Keep definite shell forms such as `$1`, `$12`, `$-`, and `$_` out of mention
  completion and preserve completion targets elsewhere in the composer.

## Testing

Added unit and snapshot coverage for positional and special parameters,
digit- and hyphen-leading skills, uppercase shell variables, unbindable
qualified skills, and competing completion targets.

GitOrigin-RevId: 8bb64cb5ca0fa8233c7fadb11a53678d57eb814c
This commit is contained in:
Charlie Marsh
2026-07-15 04:04:17 +00:00
committed by copyberry
parent 35b33e4304
commit b6f1cfa3f3
10 changed files with 460 additions and 35 deletions
+279 -17
View File
@@ -273,6 +273,7 @@ use codex_file_search::FileMatch;
#[cfg(test)]
use codex_plugin::AppConnectorId;
use codex_plugin::PluginCapabilitySummary;
use std::cell::OnceCell;
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::VecDeque;
@@ -415,6 +416,13 @@ pub(crate) struct ChatComposer {
vim_normal_keymap: VimNormalKeymap,
}
/// A resolved legacy `$` target plus any catalog built while disambiguating shell syntax.
struct MentionCompletionTarget {
range: Range<usize>,
query: String,
prebuilt_mentions: Option<Vec<MentionItem>>,
}
#[derive(Clone, Debug)]
struct ComposerDraft {
text: String,
@@ -1909,9 +1917,12 @@ impl ChatComposer {
KeyEvent {
code: KeyCode::Esc, ..
} => {
if let Some((range, query)) = self.current_mention_token_range() {
self.popups.dismissed_mention_token =
Some(DismissedToken::new(&self.draft.textarea, range, query));
if let Some(target) = self.current_mention_target() {
self.popups.dismissed_mention_token = Some(DismissedToken::new(
&self.draft.textarea,
target.range,
target.query,
));
}
self.popups.active = ActivePopup::None;
(InputResult::None, true)
@@ -1935,9 +1946,9 @@ impl ChatComposer {
if close_popup {
if let Some((insert_text, path)) = selected_mention
&& let Some((token_range, _)) = self.current_mention_token_range()
&& let Some(target) = self.current_mention_target()
{
self.insert_selected_mention(token_range, &insert_text, path.as_deref());
self.insert_selected_mention(target.range, &insert_text, path.as_deref());
}
self.popups.active = ActivePopup::None;
}
@@ -2376,14 +2387,71 @@ impl ChatComposer {
.map(|(_, token)| token)
}
fn current_mention_token_range(&self) -> Option<(Range<usize>, String)> {
/// Resolves the active legacy `$` target without eagerly cloning the mention catalog.
///
/// Definite shell syntax is rejected. Ambiguous shell-like queries are accepted only when a
/// bindable mention matches. The query-independent catalog built during that check is carried
/// forward only when the selected target is also ambiguous.
fn current_mention_target(&self) -> Option<MentionCompletionTarget> {
if !self.mentions_enabled() {
return None;
}
let (range, token) =
self.current_editable_prefixed_token_range('$', /*allow_empty*/ true)?;
let mentions: OnceCell<Vec<MentionItem>> = OnceCell::new();
let (range, query) = {
let dollar_query_is_completable =
|query: &str| match completion_target::dollar_query_kind(query) {
completion_target::DollarQueryKind::Completable => true,
completion_target::DollarQueryKind::AmbiguousShellParameter => mentions
.get_or_init(|| {
self.mention_items()
.into_iter()
.filter(|mention| {
mention.path.is_some()
&& Self::mention_token_from_insert_text(
&mention.insert_text,
)
.is_some()
})
.collect()
})
.iter()
.any(|mention| mention.fuzzy_match_query(query).is_some()),
completion_target::DollarQueryKind::ShellVariable
| completion_target::DollarQueryKind::DefiniteShellParameter
| completion_target::DollarQueryKind::Invalid => false,
};
let (range, query) =
completion_target::current_prefixed_token_range_with_dollar_predicate(
&self.draft.textarea,
'$',
/*allow_empty*/ true,
dollar_query_is_completable,
)?;
if !completion_target::prefixed_token_range_is_editable(
&self.draft.textarea,
'$',
&range,
&query,
) || !dollar_query_is_completable(&query)
{
return None;
}
(range, query)
};
let prebuilt_mentions = if matches!(
completion_target::dollar_query_kind(&query),
completion_target::DollarQueryKind::AmbiguousShellParameter
) {
mentions.into_inner()
} else {
None
};
completion_target::dollar_query_is_completable(&token).then_some((range, token))
Some(MentionCompletionTarget {
range,
query,
prebuilt_mentions,
})
}
/// Replace the active `@token` (the one under the cursor) with `path`.
@@ -3482,17 +3550,17 @@ impl ChatComposer {
self.popups.active = ActivePopup::None;
return;
}
let mut mention_token = self.current_mention_token_range();
let mut mention_target = self.current_mention_target();
let at_token_start = mentions_v2_token
.as_ref()
.or(file_token.as_ref())
.map(|(range, _)| range.start);
let mention_token_start = mention_token.as_ref().map(|(range, _)| range.start);
let mention_token_start = mention_target.as_ref().map(|target| target.range.start);
if let (Some(at_token_start), Some(mention_token_start)) =
(at_token_start, mention_token_start)
{
if at_token_start > mention_token_start {
mention_token = None;
mention_target = None;
} else if mention_token_start > at_token_start {
mentions_v2_token = None;
file_token = None;
@@ -3503,7 +3571,7 @@ impl ChatComposer {
&& !self.draft.is_bash_mode
&& file_token.is_none()
&& mentions_v2_token.is_none()
&& mention_token.is_none();
&& mention_target.is_none();
self.sync_command_popup(allow_command_popup);
if matches!(self.popups.active, ActivePopup::Command(_)) {
@@ -3522,13 +3590,13 @@ impl ChatComposer {
return;
}
if let Some((range, token)) = mention_token {
if let Some(target) = mention_target {
if self.popups.current_file_query.is_some() {
self.app_event_tx
.send(AppEvent::StartFileSearch(String::new()));
self.popups.current_file_query = None;
}
self.sync_mention_popup(range, token);
self.sync_mention_popup(target);
return;
}
self.popups.dismissed_mention_token = None;
@@ -3662,7 +3730,12 @@ impl ChatComposer {
self.popups.dismissed_file_token = None;
}
fn sync_mention_popup(&mut self, range: Range<usize>, query: String) {
fn sync_mention_popup(&mut self, target: MentionCompletionTarget) {
let MentionCompletionTarget {
range,
query,
prebuilt_mentions,
} = target;
if self
.popups
.dismissed_mention_token
@@ -3672,7 +3745,7 @@ impl ChatComposer {
return;
}
let mentions = self.mention_items();
let mentions = prebuilt_mentions.unwrap_or_else(|| self.mention_items());
if mentions.is_empty() {
self.popups.active = ActivePopup::None;
return;
@@ -6518,6 +6591,195 @@ mod tests {
);
}
#[test]
fn file_popup_ignores_shell_positional_parameter_snapshot() {
snapshot_composer_state(
"file_popup_ignores_shell_positional_parameter",
/*enhanced_keys_supported*/ false,
|composer| {
composer.set_skill_mentions(Some(vec![test_skill_metadata("available")]));
composer.set_text_content("@src $1_suffix".to_string(), Vec::new(), Vec::new());
composer.draft.textarea.set_cursor("@src ".len());
composer.sync_popups();
assert!(matches!(composer.popups.active, ActivePopup::File(_)));
},
);
}
#[test]
fn file_popup_ignores_bare_shell_parameter_with_matching_skill_snapshot() {
snapshot_composer_state(
"file_popup_ignores_bare_shell_parameter_with_matching_skill",
/*enhanced_keys_supported*/ false,
|composer| {
composer.set_skill_mentions(Some(vec![test_skill_metadata("_tool")]));
composer.set_text_content("@src $_".to_string(), Vec::new(), Vec::new());
composer.draft.textarea.set_cursor("@src ".len());
composer.sync_popups();
assert!(matches!(composer.popups.active, ActivePopup::File(_)));
},
);
}
#[test]
fn file_popup_ignores_definite_shell_parameters_with_matching_skills() {
for (query, skill_name) in [("12", "12factor"), ("-", "-tool")] {
let (mut composer, _rx) = new_test_composer();
composer.set_skill_mentions(Some(vec![test_skill_metadata(skill_name)]));
composer.set_text_content(format!("@src ${query}"), Vec::new(), Vec::new());
composer.draft.textarea.set_cursor("@src ".len());
composer.sync_popups();
assert!(matches!(composer.popups.active, ActivePopup::File(_)));
}
}
#[test]
fn skill_popup_accepts_loaded_hyphen_leading_skill_name() {
let (mut composer, _rx) = new_test_composer();
composer.set_skill_mentions(Some(vec![test_skill_metadata("-tool")]));
composer.set_text_content("$-t".to_string(), Vec::new(), Vec::new());
composer.draft.textarea.set_cursor("$-t".len());
composer.sync_popups();
let ActivePopup::Skill(popup) = &composer.popups.active else {
panic!("expected skill popup for -tool");
};
assert_eq!(
popup
.selected_mention()
.expect("expected -tool selection")
.insert_text,
"$-tool"
);
}
#[test]
fn file_popup_ignores_unbindable_qualified_skill_snapshot() {
snapshot_composer_state(
"file_popup_ignores_unbindable_qualified_skill",
/*enhanced_keys_supported*/ false,
|composer| {
composer.set_skill_mentions(Some(vec![test_skill_metadata("1plugin:deploy")]));
composer.set_text_content("@src $1plugin:d".to_string(), Vec::new(), Vec::new());
composer.draft.textarea.set_cursor("@src ".len());
composer.sync_popups();
assert!(matches!(composer.popups.active, ActivePopup::File(_)));
},
);
}
#[test]
fn skill_popup_preserves_normal_target_after_ambiguous_probe_snapshot() {
snapshot_composer_state(
"skill_popup_preserves_normal_target_after_ambiguous_probe",
/*enhanced_keys_supported*/ false,
|composer| {
composer.set_skill_mentions(Some(vec![test_skill_metadata("plugin:deploy")]));
composer.set_text_content("$1x $plugin:d".to_string(), Vec::new(), Vec::new());
composer.draft.textarea.set_cursor("$1x ".len());
composer.sync_popups();
let ActivePopup::Skill(popup) = &composer.popups.active else {
panic!("expected the right qualified skill popup");
};
assert_eq!(
popup
.selected_mention()
.expect("expected qualified skill selection")
.insert_text,
"$plugin:deploy"
);
},
);
}
#[test]
fn mention_target_prebuilds_catalog_only_for_ambiguous_query() {
let (mut composer, _rx) = new_test_composer();
composer.set_skill_mentions(Some(vec![test_skill_metadata("1password")]));
composer.set_text_content("$normal".to_string(), Vec::new(), Vec::new());
composer.draft.textarea.set_cursor("$normal".len());
let normal_target = composer
.current_mention_target()
.expect("expected normal mention target");
assert!(normal_target.prebuilt_mentions.is_none());
composer.set_text_content("$1p".to_string(), Vec::new(), Vec::new());
composer.draft.textarea.set_cursor("$1p".len());
let ambiguous_target = composer
.current_mention_target()
.expect("expected ambiguous mention target");
assert_eq!(
ambiguous_target.prebuilt_mentions.map(|mentions| {
mentions
.into_iter()
.map(|mention| mention.display_name)
.collect::<Vec<_>>()
}),
Some(vec!["1password".to_string()])
);
}
#[test]
fn skill_popup_accepts_digit_leading_skill_snapshot() {
snapshot_composer_state(
"skill_popup_accepts_digit_leading_skill",
/*enhanced_keys_supported*/ false,
|composer| {
composer.set_skill_mentions(Some(vec![test_skill_metadata("1password")]));
composer.set_text_content("$1p".to_string(), Vec::new(), Vec::new());
composer.draft.textarea.set_cursor("$1p".len());
composer.sync_popups();
assert!(matches!(composer.popups.active, ActivePopup::Skill(_)));
},
);
}
#[test]
fn skill_popup_does_not_fuzzy_match_shell_variable_snapshot() {
snapshot_composer_state(
"skill_popup_does_not_fuzzy_match_shell_variable",
/*enhanced_keys_supported*/ false,
|composer| {
composer.set_skill_mentions(Some(vec![test_skill_metadata("home")]));
composer.set_text_content("$HOME".to_string(), Vec::new(), Vec::new());
composer.draft.textarea.set_cursor("$HOME".len());
composer.sync_popups();
assert!(matches!(composer.popups.active, ActivePopup::None));
},
);
}
#[test]
fn skill_popup_preserves_loaded_shell_like_skill_at_separator() {
let (mut composer, _rx) = new_test_composer();
composer.set_skill_mentions(Some(vec![
test_skill_metadata("1password"),
test_skill_metadata("rustdoc"),
]));
composer.set_text_content("$1p $rustdoc".to_string(), Vec::new(), Vec::new());
composer.draft.textarea.set_cursor("$1p ".len());
composer.sync_popups();
let ActivePopup::Skill(popup) = &composer.popups.active else {
panic!("expected the left shell-like skill popup");
};
assert_eq!(
popup
.selected_mention()
.expect("expected 1password selection")
.insert_text,
"$1password"
);
}
#[test]
fn skill_popup_accepts_lowercase_skill_named_like_env_var() {
let (mut composer, _rx) = new_test_composer();
@@ -72,6 +72,22 @@ pub(super) fn current_prefixed_token_range(
textarea: &TextArea,
prefix: char,
allow_empty: bool,
) -> Option<(Range<usize>, String)> {
current_prefixed_token_range_with_dollar_predicate(
textarea,
prefix,
allow_empty,
dollar_query_is_completable,
)
}
/// Extracts a prefixed token while using the provided dollar-query predicate for separator
/// arbitration.
pub(super) fn current_prefixed_token_range_with_dollar_predicate(
textarea: &TextArea,
prefix: char,
allow_empty: bool,
dollar_query_is_completable: impl Fn(&str) -> bool,
) -> Option<(Range<usize>, String)> {
let cursor_offset = textarea.cursor();
let text = textarea.text();
@@ -279,9 +295,30 @@ pub(super) fn prefixed_token_range_is_editable(
/// Rejects shell-like dollar syntax while preserving lowercase and plugin-qualified skill queries.
///
/// Only uppercase common environment-variable spellings are excluded. The check uses the complete
/// colon-qualified name so a skill such as `home` or `home:search` is not mistaken for `$HOME`.
/// Uppercase common environment-variable spellings and tokens beginning with a positional or
/// special shell parameter are excluded. The check uses the complete colon-qualified name so a
/// skill such as `home` or `home:search` is not mistaken for `$HOME`.
pub(super) fn dollar_query_is_completable(query: &str) -> bool {
matches!(dollar_query_kind(query), DollarQueryKind::Completable)
}
/// Classifies text after `$` for arbitration between shell syntax and mention completion.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum DollarQueryKind {
Completable,
ShellVariable,
DefiniteShellParameter,
/// A digit-leading query containing a non-digit, or a `-` query with a suffix.
AmbiguousShellParameter,
Invalid,
}
/// Conservatively classifies a dollar query before the mention catalog is consulted.
///
/// Numeric-only and exact special-parameter forms remain definite shell syntax. A digit-leading
/// query containing a non-digit, or a `-` query with a suffix, is ambiguous because loaded
/// mentions may legally use those spellings.
pub(super) fn dollar_query_kind(query: &str) -> DollarQueryKind {
let name_end = query
.as_bytes()
.iter()
@@ -290,7 +327,24 @@ pub(super) fn dollar_query_is_completable(query: &str) -> bool {
let name = &query[..name_end];
let is_shell_var =
name.bytes().all(|byte| !byte.is_ascii_lowercase()) && is_common_env_var(name);
query.is_empty() || name_end > 0 && !is_shell_var
let is_shell_parameter = name
.as_bytes()
.first()
.is_some_and(|byte| *byte == b'-' || byte.is_ascii_digit());
let is_numeric_parameter = !name.is_empty() && name.bytes().all(|byte| byte.is_ascii_digit());
if query.is_empty() {
DollarQueryKind::Completable
} else if name_end == 0 {
DollarQueryKind::Invalid
} else if is_shell_var {
DollarQueryKind::ShellVariable
} else if is_numeric_parameter || matches!(name, "-" | "_") {
DollarQueryKind::DefiniteShellParameter
} else if is_shell_parameter {
DollarQueryKind::AmbiguousShellParameter
} else {
DollarQueryKind::Completable
}
}
#[cfg(test)]
@@ -184,4 +184,18 @@ fn dollar_query_classifies_shell_and_skill_syntax() {
assert!(dollar_query_is_completable("home:search"));
assert!(dollar_query_is_completable("home"));
assert!(!dollar_query_is_completable("HOME"));
for query in ["0", "1", "12", "-", "_"] {
assert!(!dollar_query_is_completable(query));
assert_eq!(
dollar_query_kind(query),
DollarQueryKind::DefiniteShellParameter
);
}
for query in ["1_suffix", "1foo", "-x"] {
assert!(!dollar_query_is_completable(query));
assert_eq!(
dollar_query_kind(query),
DollarQueryKind::AmbiguousShellParameter
);
}
}
+32 -15
View File
@@ -28,6 +28,36 @@ pub(crate) struct MentionItem {
pub(crate) sort_rank: u8,
}
/// The best fuzzy match for a mention and the display-name positions that can be highlighted.
///
/// `display_name_indices` is absent when only an alternate search term matched.
pub(crate) struct MentionMatch {
display_name_indices: Option<Vec<usize>>,
score: i32,
}
impl MentionItem {
/// Matches the display name first, then falls back to the best distinct search term.
pub(crate) fn fuzzy_match_query(&self, query: &str) -> Option<MentionMatch> {
if let Some((indices, score)) = fuzzy_match(&self.display_name, query) {
Some(MentionMatch {
display_name_indices: Some(indices),
score,
})
} else {
self.search_terms
.iter()
.filter(|term| *term != &self.display_name)
.filter_map(|term| fuzzy_match(term, query).map(|(_indices, score)| score))
.min()
.map(|score| MentionMatch {
display_name_indices: None,
score,
})
}
}
}
const MENTION_NAME_TRUNCATE_LEN: usize = 28;
pub(crate) struct SkillPopup {
@@ -137,21 +167,8 @@ impl SkillPopup {
continue;
}
let best_match =
if let Some((indices, score)) = fuzzy_match(&mention.display_name, filter) {
Some((Some(indices), score))
} else {
mention
.search_terms
.iter()
.filter(|term| *term != &mention.display_name)
.filter_map(|term| fuzzy_match(term, filter).map(|(_indices, score)| score))
.min()
.map(|score| (None, score))
};
if let Some((indices, score)) = best_match {
out.push((idx, indices, score));
if let Some(mention_match) = mention.fuzzy_match_query(filter) {
out.push((idx, mention_match.display_name_indices, mention_match.score));
}
}
@@ -0,0 +1,13 @@
---
source: tui/src/bottom_pane/chat_composer.rs
expression: terminal.backend()
---
" "
"› @src $_ "
" "
" "
" "
" "
" "
" "
" loading... "
@@ -0,0 +1,13 @@
---
source: tui/src/bottom_pane/chat_composer.rs
expression: terminal.backend()
---
" "
"› @src $1_suffix "
" "
" "
" "
" "
" "
" "
" loading... "
@@ -0,0 +1,13 @@
---
source: tui/src/bottom_pane/chat_composer.rs
expression: terminal.backend()
---
" "
"› @src $1plugin:d "
" "
" "
" "
" "
" "
" "
" loading... "
@@ -0,0 +1,13 @@
---
source: tui/src/bottom_pane/chat_composer.rs
expression: terminal.backend()
---
" "
"› $1p "
" "
" "
" "
" "
" 1password [Skill] Example skill used in tests. "
" "
" Press enter to insert or esc to close "
@@ -0,0 +1,13 @@
---
source: tui/src/bottom_pane/chat_composer.rs
expression: terminal.backend()
---
" "
"› $HOME "
" "
" "
" "
" "
" "
" "
" 100% context left "
@@ -0,0 +1,13 @@
---
source: tui/src/bottom_pane/chat_composer.rs
expression: terminal.backend()
---
" "
"› $1x $plugin:d "
" "
" "
" "
" "
" deploy (plugin) [Skill] Example skill used in tests. "
" "
" Press enter to insert or esc to close "