Fix Unicode fuzzy matching and slash popup activation (#64058)

## Why

Fuzzy matching lowercased candidates and queries differently, so Greek
sigma variants could fail to match. The slash-command popup could also
open for fuzzy matches that its exact and prefix filters never displayed,
taking over the arrow keys while the user was editing a draft.

## What changed

- Apply the same Unicode case folding to both sides of a fuzzy match and
  use it to rank exact and prefix matches in the skill popup.
- Use the same command list and case-insensitive exact and prefix
  matching rules to open and filter the slash-command popup.

## Testing

Cover Greek sigma and long s in the fuzzy matcher, snapshot skill
results with a folded exact match above a prefix match, and check that
the arrow keys move the cursor through a draft starting with `/ſtatus`.

GitOrigin-RevId: 04cf3a65b02204221569c4f7b2d4397f48554e2d
This commit is contained in:
Eric Traut
2026-11-26 02:42:20 +00:00
committed by copyberry
parent 06023b038f
commit f79875c21b
8 changed files with 135 additions and 102 deletions
+3
View File
@@ -5653,6 +5653,9 @@ version = "0.0.0"
[[package]]
name = "codex-utils-fuzzy-match"
version = "0.0.0"
dependencies = [
"nucleo",
]
[[package]]
name = "codex-utils-git-discovery"
@@ -12291,16 +12291,15 @@ mod tests {
"'/re' should activate slash popup via prefix match"
);
// Case 3: fuzzy match "/ac" (subsequence of /compact and /feedback)
composer.set_text_content("/ac".to_string(), Vec::new(), Vec::new());
assert!(
matches!(composer.popups.active, ActivePopup::Command(_)),
"'/ac' should activate slash popup via fuzzy match"
);
// A fuzzy-only match must leave the arrow keys available for editing.
let draft = "/ſtatus\nexample";
composer.set_text_content(String::new(), Vec::new(), Vec::new());
composer.handle_paste(draft.to_string());
composer.handle_key_event(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE));
assert_eq!(composer.draft.textarea.cursor(), "/ſtatus".len());
composer.handle_key_event(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
assert_eq!(composer.draft.textarea.cursor(), draft.len());
// Case 4: invalid prefix "/zzz" – still allowed to open popup if it
// matches no built-in command; our current logic will not open popup.
// Verify that explicitly.
composer.set_text_content("/zzz".to_string(), Vec::new(), Vec::new());
assert!(
matches!(composer.popups.active, ActivePopup::None),
+17 -44
View File
@@ -11,9 +11,11 @@ use super::selection_popup_common::GenericDisplayRow;
use super::selection_popup_common::measure_rows_height_with_col_width_mode;
use super::selection_popup_common::render_rows_with_col_width_mode;
use super::slash_commands::BuiltinCommandFlags;
use super::slash_commands::CommandMatch;
use super::slash_commands::ServiceTierCommand;
use super::slash_commands::SlashCommandItem;
use super::slash_commands::commands_for_input;
use super::slash_commands::commands_for_popup;
use super::slash_commands::match_command_name;
use crate::slash_command::SlashCommand;
// Hide alias commands in the default popup list so each unique action appears once.
@@ -81,21 +83,13 @@ impl CommandPopup {
service_tier_commands: Vec<ServiceTierCommand>,
) -> Self {
// Keep built-in availability in sync with the composer.
let commands = commands_for_input(
BuiltinCommandFlags {
side_conversation_active: false,
..flags.into()
},
&service_tier_commands,
)
.into_iter()
.filter_map(|command| match command {
SlashCommandItem::Builtin(cmd) => (!cmd.command().starts_with("debug")
&& cmd != SlashCommand::Apps)
.then_some(CommandItem::Builtin(cmd)),
SlashCommandItem::ServiceTier(command) => Some(CommandItem::ServiceTier(command)),
})
.collect();
let commands = commands_for_popup(flags.into(), &service_tier_commands)
.into_iter()
.map(|command| match command {
SlashCommandItem::Builtin(cmd) => CommandItem::Builtin(cmd),
SlashCommandItem::ServiceTier(command) => CommandItem::ServiceTier(command),
})
.collect();
Self {
disconnected: flags.disconnected,
command_filter: None,
@@ -174,37 +168,16 @@ impl CommandPopup {
let filter_lower = filter.to_lowercase();
let filter_chars = filter.chars().count();
let mut exact: Vec<(CommandItem, Option<Vec<usize>>)> = Vec::new();
let mut prefix: Vec<(CommandItem, Option<Vec<usize>>)> = Vec::new();
let indices_for = |offset| Some((offset..offset + filter_chars).collect());
let mut push_match =
|item: CommandItem, display: &str, name: Option<&str>, name_offset: usize| {
let display_lower = display.to_lowercase();
let name_lower = name.map(str::to_lowercase);
let display_exact = display_lower == filter_lower;
let name_exact = name_lower.as_deref() == Some(filter_lower.as_str());
if display_exact || name_exact {
let offset = if display_exact { 0 } else { name_offset };
exact.push((item, indices_for(offset)));
return;
}
let display_prefix = display_lower.starts_with(&filter_lower);
let name_prefix = name_lower
.as_ref()
.is_some_and(|name| name.starts_with(&filter_lower));
if display_prefix || name_prefix {
let offset = if display_prefix { 0 } else { name_offset };
prefix.push((item, indices_for(offset)));
}
let mut prefix = Vec::new();
for command in &self.commands {
let matches = match match_command_name(command.command(), &filter_lower) {
Some(CommandMatch::Exact) => &mut out,
Some(CommandMatch::Prefix) => &mut prefix,
None => continue,
};
for command in self.commands.iter() {
let display = command.command();
push_match(command.clone(), display, None, 0);
matches.push((command.clone(), Some((0..filter_chars).collect())));
}
out.extend(exact);
out.extend(prefix);
if self.side_conversation_active || self.disconnected {
out.sort_by_key(|(item, _)| self.unavailable_reason(item).is_some());
+20 -13
View File
@@ -22,6 +22,7 @@ use super::scroll_state::ScrollState;
use super::selection_popup_common::GenericDisplayRow;
use crate::key_hint;
use crate::text_formatting::truncate_text;
use codex_utils_fuzzy_match::fold_for_match;
use codex_utils_fuzzy_match::fuzzy_match;
#[derive(Clone, Debug)]
@@ -71,18 +72,16 @@ impl MentionItem {
}
}
fn match_tier(&self, lowercase_query: &str) -> MatchTier {
let display_name = self.display_name.to_lowercase();
let insert_name = self
.insert_text
.strip_prefix('$')
.unwrap_or(&self.insert_text)
.to_lowercase();
if display_name == lowercase_query || insert_name == lowercase_query {
fn match_tier(&self, folded_query: &str) -> MatchTier {
let display_name = fold_for_match(&self.display_name);
let insert_name = fold_for_match(
self.insert_text
.strip_prefix('$')
.unwrap_or(&self.insert_text),
);
if display_name == folded_query || insert_name == folded_query {
MatchTier::Exact
} else if display_name.starts_with(lowercase_query)
|| insert_name.starts_with(lowercase_query)
{
} else if display_name.starts_with(folded_query) || insert_name.starts_with(folded_query) {
MatchTier::Prefix
} else {
MatchTier::Fuzzy
@@ -235,7 +234,7 @@ impl SkillPopup {
fn filtered(&self) -> Vec<(usize, Option<Vec<usize>>, i32)> {
let filter = self.query.trim();
let lowercase_filter = filter.to_lowercase();
let folded_filter = fold_for_match(filter);
let mut out: Vec<(usize, Option<Vec<usize>>, i32)> = Vec::new();
for (idx, mention) in self.mentions.iter().enumerate() {
@@ -254,7 +253,7 @@ impl SkillPopup {
let tier = if filter.is_empty() {
MatchTier::Fuzzy
} else {
mention.match_tier(&lowercase_filter)
mention.match_tier(&folded_filter)
};
let frequency = mention
.path
@@ -510,6 +509,8 @@ mod tests {
&["logging-best-practices", "Logging Best Practices"],
),
named_mention_item("PR Babysitter", &["babysit-pr", "PR Babysitter"]),
named_mention_item("tool-οστ", &[]),
named_mention_item("tool-ος", &[]),
]);
popup.frequencies.insert("plugin://github".to_owned(), 50);
popup.set_query("pr");
@@ -540,5 +541,11 @@ mod tests {
),
]
);
popup.set_query("tool-οσ");
insta::assert_snapshot!(
"skill_popup_folded_name",
render_popup(&popup, /*width*/ 48)
);
}
}
+30 -26
View File
@@ -5,8 +5,6 @@
//! and ensures they stay in sync.
use std::str::FromStr;
use codex_utils_fuzzy_match::fuzzy_match;
use crate::slash_command::SlashCommand;
use crate::slash_command::built_in_slash_commands;
@@ -38,13 +36,6 @@ impl SlashCommandItem {
}
}
pub(crate) fn available_in_side_conversation(&self) -> bool {
match self {
Self::Builtin(cmd) => cmd.available_in_side_conversation(),
Self::ServiceTier(_) => false,
}
}
pub(crate) fn available_during_task(&self) -> bool {
match self {
Self::Builtin(cmd) => cmd.available_during_task(),
@@ -87,13 +78,20 @@ pub(crate) fn builtins_for_input(flags: BuiltinCommandFlags) -> Vec<(&'static st
.collect()
}
pub(crate) fn commands_for_input(
pub(crate) fn commands_for_popup(
flags: BuiltinCommandFlags,
service_tier_commands: &[ServiceTierCommand],
) -> Vec<SlashCommandItem> {
let mut commands = Vec::new();
let tiers_enabled = flags.service_tier_commands_enabled;
for (_, cmd) in builtins_for_input(flags) {
// Side conversations show unavailable commands without enabling dispatch.
for (_, cmd) in builtins_for_input(BuiltinCommandFlags {
side_conversation_active: false,
..flags
}) {
if cmd.command().starts_with("debug") || cmd == SlashCommand::Apps {
continue;
}
commands.push(SlashCommandItem::Builtin(cmd));
if cmd == SlashCommand::Model && tiers_enabled {
commands.extend(
@@ -105,9 +103,6 @@ pub(crate) fn commands_for_input(
}
}
commands
.into_iter()
.filter(|cmd| !flags.side_conversation_active || cmd.available_in_side_conversation())
.collect()
}
/// Find a single built-in command by a recognized name or alias, after applying feature gating.
@@ -158,17 +153,26 @@ pub(crate) fn has_slash_command_prefix(
flags: BuiltinCommandFlags,
service_tier_commands: &[ServiceTierCommand],
) -> bool {
// A side conversation can describe a known command as unavailable in the
// popup, even though dispatch must continue to reject it.
commands_for_input(
BuiltinCommandFlags {
side_conversation_active: false,
..flags
},
service_tier_commands,
)
.into_iter()
.any(|command| fuzzy_match(command.command(), name).is_some())
let filter = name.to_lowercase();
commands_for_popup(flags, service_tier_commands)
.iter()
.any(|command| match_command_name(command.command(), &filter).is_some())
}
pub(super) enum CommandMatch {
Exact,
Prefix,
}
pub(super) fn match_command_name(command: &str, lowercase_filter: &str) -> Option<CommandMatch> {
let name = command.to_lowercase();
if name == lowercase_filter {
Some(CommandMatch::Exact)
} else if name.starts_with(lowercase_filter) {
Some(CommandMatch::Prefix)
} else {
None
}
}
#[cfg(test)]
@@ -271,7 +275,7 @@ mod tests {
},
];
let items = commands_for_input(all_enabled_flags(), &commands);
let items = commands_for_popup(all_enabled_flags(), &commands);
let model_idx = items
.iter()
.position(|item| matches!(item, SlashCommandItem::Builtin(SlashCommand::Model)))
@@ -0,0 +1,30 @@
---
source: tui/src/bottom_pane/skill_popup.rs
expression: "render_popup(&popup, 48)"
---
Buffer {
area: Rect { x: 0, y: 0, width: 48, height: 5 },
content: [
" ",
"› tool-ος [Skill] ",
" tool-οστ [Skill] ",
" ",
" enter insert · esc close ",
],
styles: [
x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
x: 0, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD | REVERSED,
x: 12, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: REVERSED,
x: 19, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD | REVERSED,
x: 0, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
x: 2, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD,
x: 9, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
x: 12, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
x: 19, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
x: 2, y: 4, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD,
x: 7, y: 4, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
x: 17, y: 4, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD,
x: 20, y: 4, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
x: 26, y: 4, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
]
}
+3
View File
@@ -9,3 +9,6 @@ workspace = true
[lib]
doctest = false
[dependencies]
nucleo = { workspace = true }
+24 -10
View File
@@ -17,13 +17,13 @@ pub fn fuzzy_match(haystack: &str, needle: &str) -> Option<(Vec<usize>, i32)> {
let mut lowered_chars: Vec<char> = Vec::new();
let mut lowered_to_orig_char_idx: Vec<usize> = Vec::new();
for (orig_idx, ch) in haystack.chars().enumerate() {
for lc in ch.to_lowercase() {
for lc in fold_char(ch) {
lowered_chars.push(lc);
lowered_to_orig_char_idx.push(orig_idx);
}
}
let lowered_needle: Vec<char> = needle.to_lowercase().chars().collect();
let lowered_needle: Vec<char> = needle.chars().flat_map(fold_char).collect();
let mut result_orig_indices: Vec<usize> = Vec::with_capacity(lowered_needle.len());
let mut first_lower_pos: Option<usize> = None;
@@ -63,6 +63,22 @@ pub fn fuzzy_match(haystack: &str, needle: &str) -> Option<(Vec<usize>, i32)> {
Some((result_orig_indices, score))
}
/// Normalize text for exact and prefix comparisons consistent with [`fuzzy_match`].
pub fn fold_for_match(text: &str) -> String {
text.chars().flat_map(fold_char).collect()
}
// Simple case folding equates variants without expanding ß to ss. Lowercasing
// afterwards preserves existing expansions such as İ → i̇.
fn fold_char(ch: char) -> std::char::ToLowercase {
let ch = if ch.is_ascii() {
ch
} else {
nucleo::chars::to_lower_case(ch)
};
ch.to_lowercase()
}
#[cfg(test)]
mod tests {
use super::*;
@@ -139,14 +155,12 @@ mod tests {
}
#[test]
fn case_insensitive_matching_basic() {
let (idx, score) = match fuzzy_match("FooBar", "foO") {
Some(v) => v,
None => panic!("expected a match"),
};
assert_eq!(idx, vec![0, 1, 2]);
// Contiguous prefix match (case-insensitive) -> window 0 with bonus
assert_eq!(score, -100);
fn case_insensitive_matching() {
assert_eq!(fuzzy_match("FooBar", "foO"), Some((vec![0, 1, 2], -100)));
assert_eq!(fuzzy_match("ΟΣ", "ΟΣ"), Some((vec![0, 1], -100)));
assert_eq!(fuzzy_match("ΟΣ", "ος"), Some((vec![0, 1], -100)));
assert_eq!(fuzzy_match("ος", "σ"), Some((vec![1], 0)));
assert_eq!(fuzzy_match("ſ", "s"), Some((vec![0], -100)));
}
#[test]