mirror of
https://github.com/openai/codex.git
synced 2026-11-30 00:10:49 +00:00
cleaup
This commit is contained in:
@@ -17,3 +17,8 @@ toml = { version = "0.9", optional = true }
|
||||
cli = ["clap", "serde", "toml"]
|
||||
elapsed = []
|
||||
sandbox_summary = []
|
||||
|
||||
[dev-dependencies]
|
||||
clap = { version = "4", features = ["derive", "wrap_help"] }
|
||||
serde = { version = "1" }
|
||||
toml = { version = "0.9" }
|
||||
|
||||
@@ -1,49 +1,110 @@
|
||||
/// Simple case-insensitive subsequence matcher used for fuzzy filtering.
|
||||
///
|
||||
/// Returns the indices (positions) of the matched characters in `haystack`
|
||||
/// and a score where smaller is better. Currently, indices are byte offsets
|
||||
/// from `char_indices()` of a lowercased copy of `haystack`.
|
||||
/// Returns the indices (character positions) of the matched characters in the
|
||||
/// ORIGINAL `haystack` string and a score where smaller is better.
|
||||
///
|
||||
/// Note: For ASCII inputs these indices align with character positions. If
|
||||
/// extended Unicode inputs are used, be mindful of byte vs char indices.
|
||||
/// Unicode correctness: we perform the match on a lowercased copy of the
|
||||
/// haystack and needle but maintain a mapping from each character in the
|
||||
/// lowercased haystack back to the original character index in `haystack`.
|
||||
/// This ensures the returned indices can be safely used with
|
||||
/// `str::chars().enumerate()` consumers for highlighting, even when
|
||||
/// lowercasing expands certain characters (e.g., ß → ss, İ → i̇).
|
||||
pub fn fuzzy_match(haystack: &str, needle: &str) -> Option<(Vec<usize>, i32)> {
|
||||
if needle.is_empty() {
|
||||
return Some((Vec::new(), i32::MAX));
|
||||
}
|
||||
let h_lower = haystack.to_lowercase();
|
||||
let n_lower = needle.to_lowercase();
|
||||
let mut indices: Vec<usize> = Vec::with_capacity(n_lower.len());
|
||||
let mut h_iter = h_lower.char_indices();
|
||||
let mut last_pos: Option<usize> = None;
|
||||
|
||||
for ch in n_lower.chars() {
|
||||
let mut found = None;
|
||||
for (i, hc) in h_iter.by_ref() {
|
||||
if hc == ch {
|
||||
found = Some(i);
|
||||
// Build a lowercased view of the haystack alongside a mapping from the
|
||||
// lowered-character indices back to the ORIGINAL character indices.
|
||||
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() {
|
||||
// Lowercasing may yield multiple chars; map each back to the same
|
||||
// original char index so we can highlight correctly.
|
||||
for lc in ch.to_lowercase() {
|
||||
lowered_chars.push(lc);
|
||||
lowered_to_orig_char_idx.push(orig_idx);
|
||||
}
|
||||
}
|
||||
|
||||
let lowered_needle: Vec<char> = needle.to_lowercase().chars().collect();
|
||||
|
||||
// Greedy subsequence match over the lowered chars.
|
||||
let mut result_orig_indices: Vec<usize> = Vec::with_capacity(lowered_needle.len());
|
||||
let mut last_lower_pos: Option<usize> = None;
|
||||
let mut cur = 0usize; // current search start in lowered_chars
|
||||
for &nc in lowered_needle.iter() {
|
||||
let mut found_at: Option<usize> = None;
|
||||
while cur < lowered_chars.len() {
|
||||
if lowered_chars[cur] == nc {
|
||||
found_at = Some(cur);
|
||||
cur += 1; // next search starts after this position
|
||||
break;
|
||||
}
|
||||
cur += 1;
|
||||
}
|
||||
if let Some(pos) = found {
|
||||
indices.push(pos);
|
||||
last_pos = Some(pos);
|
||||
} else {
|
||||
return None;
|
||||
}
|
||||
let pos = found_at?;
|
||||
// Map the lowered pos back to the original character index.
|
||||
result_orig_indices.push(lowered_to_orig_char_idx[pos]);
|
||||
last_lower_pos = Some(pos);
|
||||
}
|
||||
|
||||
// Score: window length minus needle length (tighter is better), with a bonus for prefix match.
|
||||
let first = *indices.first().unwrap_or(&0);
|
||||
let last = last_pos.unwrap_or(first);
|
||||
let window = (last as i32 - first as i32 + 1) - (n_lower.len() as i32);
|
||||
// Score: window length (in lowered char positions) minus lowered needle
|
||||
// length (tighter is better), with a strong bonus for prefix match.
|
||||
let first_lower_pos = if result_orig_indices.is_empty() {
|
||||
0usize
|
||||
} else {
|
||||
let target_orig = result_orig_indices[0];
|
||||
lowered_to_orig_char_idx
|
||||
.iter()
|
||||
.position(|&oi| oi == target_orig)
|
||||
.unwrap_or(0)
|
||||
};
|
||||
let last_lower_pos = last_lower_pos.unwrap_or(first_lower_pos);
|
||||
let window =
|
||||
(last_lower_pos as i32 - first_lower_pos as i32 + 1) - (lowered_needle.len() as i32);
|
||||
let mut score = window.max(0);
|
||||
if first == 0 {
|
||||
if first_lower_pos == 0 {
|
||||
score -= 100; // strong bonus for prefix match
|
||||
}
|
||||
Some((indices, score))
|
||||
|
||||
// Ensure indices are unique and sorted for robust highlighting consumers.
|
||||
result_orig_indices.sort_unstable();
|
||||
result_orig_indices.dedup();
|
||||
Some((result_orig_indices, score))
|
||||
}
|
||||
|
||||
/// Convenience wrapper to get only the indices for a fuzzy match.
|
||||
pub fn fuzzy_indices(haystack: &str, needle: &str) -> Option<Vec<usize>> {
|
||||
fuzzy_match(haystack, needle).map(|(idx, _)| idx)
|
||||
fuzzy_match(haystack, needle).map(|(mut idx, _)| {
|
||||
// Already sorted/deduped, but keep invariant local to this helper too.
|
||||
idx.sort_unstable();
|
||||
idx.dedup();
|
||||
idx
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ascii_basic_indices() {
|
||||
let (idx, _score) = fuzzy_match("hello", "hl").expect("match");
|
||||
assert_eq!(idx, vec![0, 2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_dotted_i_istanbul_highlighting() {
|
||||
// 'İ' lowercases to two chars (i + combining dot). Ensure index 0 is highlighted once.
|
||||
let (idx, _score) = fuzzy_match("İstanbul", "is").expect("match");
|
||||
assert_eq!(idx, vec![0, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_german_sharp_s_casefold() {
|
||||
// Ensure we at least don't panic with non-ASCII inputs; lowercase-based
|
||||
// matching does not equate ß with "ss", so this should be None.
|
||||
assert!(fuzzy_match("straße", "strasse").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
+12
-34
@@ -413,7 +413,7 @@ impl App<'_> {
|
||||
widget.show_model_selector();
|
||||
}
|
||||
}
|
||||
AppEvent::OpenApprovalSelector => {
|
||||
AppEvent::OpenExecutionSelector => {
|
||||
if let AppState::Chat { widget } = &mut self.app_state {
|
||||
widget.show_execution_selector();
|
||||
}
|
||||
@@ -428,8 +428,8 @@ impl App<'_> {
|
||||
AppState::GitWarning { .. } => {}
|
||||
AppState::DangerWarning { widget, .. } => widget.update_latest_log(line),
|
||||
},
|
||||
AppEvent::DispatchCommand(command) => match command {
|
||||
SlashCommand::New => {
|
||||
AppEvent::DispatchCommand { cmd, args } => match (cmd, args.as_deref()) {
|
||||
(SlashCommand::New, _) => {
|
||||
let new_widget = Box::new(ChatWidget::new(
|
||||
self.config.clone(),
|
||||
self.app_event_tx.clone(),
|
||||
@@ -445,16 +445,16 @@ impl App<'_> {
|
||||
self.app_state = AppState::Chat { widget: new_widget };
|
||||
self.app_event_tx.send(AppEvent::RequestRedraw);
|
||||
}
|
||||
SlashCommand::Compact => {
|
||||
(SlashCommand::Compact, _) => {
|
||||
if let AppState::Chat { widget } = &mut self.app_state {
|
||||
widget.clear_token_usage();
|
||||
self.app_event_tx.send(AppEvent::CodexOp(Op::Compact));
|
||||
}
|
||||
}
|
||||
SlashCommand::Quit => {
|
||||
(SlashCommand::Quit, _) => {
|
||||
break;
|
||||
}
|
||||
SlashCommand::Diff => {
|
||||
(SlashCommand::Diff, _) => {
|
||||
let (is_git_repo, diff_text) = match get_git_diff() {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
@@ -476,7 +476,7 @@ impl App<'_> {
|
||||
}
|
||||
}
|
||||
#[cfg(debug_assertions)]
|
||||
SlashCommand::TestApproval => {
|
||||
(SlashCommand::TestApproval, _) => {
|
||||
use std::collections::HashMap;
|
||||
|
||||
use codex_core::protocol::ApplyPatchApprovalRequestEvent;
|
||||
@@ -484,12 +484,6 @@ impl App<'_> {
|
||||
|
||||
self.app_event_tx.send(AppEvent::CodexEvent(Event {
|
||||
id: "1".to_string(),
|
||||
// msg: EventMsg::ExecApprovalRequest(ExecApprovalRequestEvent {
|
||||
// call_id: "1".to_string(),
|
||||
// command: vec!["git".into(), "apply".into()],
|
||||
// cwd: self.config.cwd.clone(),
|
||||
// reason: Some("test".to_string()),
|
||||
// }),
|
||||
msg: EventMsg::ApplyPatchApprovalRequest(
|
||||
ApplyPatchApprovalRequestEvent {
|
||||
call_id: "1".to_string(),
|
||||
@@ -514,26 +508,10 @@ impl App<'_> {
|
||||
),
|
||||
}));
|
||||
}
|
||||
SlashCommand::Model => {
|
||||
// Disallow `/model` without arguments; no action.
|
||||
}
|
||||
SlashCommand::Approvals => {
|
||||
// Disallow `/approvals` without arguments; no action.
|
||||
}
|
||||
},
|
||||
AppEvent::DispatchCommandWithArgs(command, args) => match command {
|
||||
SlashCommand::Model => self.handle_model_command(&args),
|
||||
SlashCommand::Approvals => self.handle_approvals_command(&args),
|
||||
#[cfg(debug_assertions)]
|
||||
SlashCommand::TestApproval => {
|
||||
self.app_event_tx.send(AppEvent::DispatchCommand(command));
|
||||
}
|
||||
SlashCommand::New
|
||||
| SlashCommand::Quit
|
||||
| SlashCommand::Diff
|
||||
| SlashCommand::Compact => {
|
||||
self.app_event_tx.send(AppEvent::DispatchCommand(command));
|
||||
}
|
||||
(SlashCommand::Model, Some(args)) => self.handle_model_command(args),
|
||||
(SlashCommand::Approvals, Some(args)) => self.handle_approvals_command(args),
|
||||
// Disallow `/model` and `/approvals` without args: no action.
|
||||
(SlashCommand::Model, None) | (SlashCommand::Approvals, None) => {}
|
||||
},
|
||||
AppEvent::StartFileSearch(query) => {
|
||||
self.file_search.on_user_query(query);
|
||||
@@ -561,7 +539,7 @@ impl App<'_> {
|
||||
fn draw_next_frame(&mut self, terminal: &mut tui::Tui) -> Result<()> {
|
||||
let screen_size = terminal.size()?;
|
||||
let last_known_screen_size = terminal.last_known_screen_size;
|
||||
if screen_size != last_known_screen_size && !self.fixup_viewport_after_danger {
|
||||
if screen_size != last_known_screen_size {
|
||||
let cursor_pos = terminal.get_cursor_position()?;
|
||||
let last_known_cursor_pos = terminal.last_known_cursor_pos;
|
||||
if cursor_pos.y != last_known_cursor_pos.y {
|
||||
|
||||
@@ -33,12 +33,12 @@ pub(crate) enum AppEvent {
|
||||
LatestLog(String),
|
||||
|
||||
/// Dispatch a recognized slash command from the UI (composer) to the app
|
||||
/// layer so it can be handled centrally.
|
||||
DispatchCommand(SlashCommand),
|
||||
|
||||
/// Dispatch a recognized slash command along with the raw argument string
|
||||
/// following the command on the first line.
|
||||
DispatchCommandWithArgs(SlashCommand, String),
|
||||
/// layer so it can be handled centrally. Optional `args` contains the
|
||||
/// left-trimmed raw argument string following the command, if any.
|
||||
DispatchCommand {
|
||||
cmd: SlashCommand,
|
||||
args: Option<String>,
|
||||
},
|
||||
|
||||
/// Kick off an asynchronous file search for the given query (text after
|
||||
/// the `@`). Previous searches may be cancelled by the app layer so there
|
||||
@@ -67,6 +67,6 @@ pub(crate) enum AppEvent {
|
||||
sandbox: SandboxPolicy,
|
||||
},
|
||||
|
||||
/// Request the app to open the approval selector (populate options and show popup).
|
||||
OpenApprovalSelector,
|
||||
/// Request the app to open the execution-mode selector (populate options and show popup).
|
||||
OpenExecutionSelector,
|
||||
}
|
||||
|
||||
@@ -26,7 +26,9 @@ use crate::command_utils::parse_execution_mode_token;
|
||||
|
||||
use crate::app_event::AppEvent;
|
||||
use crate::app_event_sender::AppEventSender;
|
||||
use crate::slash_command::ParsedSlash;
|
||||
use crate::slash_command::SlashCommand;
|
||||
use crate::slash_command::parse_slash_line;
|
||||
use codex_file_search::FileMatch;
|
||||
|
||||
const BASE_PLACEHOLDER_TEXT: &str = "...";
|
||||
@@ -47,8 +49,7 @@ pub(crate) struct ChatComposer<'a> {
|
||||
history: ChatComposerHistory,
|
||||
ctrl_c_quit_hint: bool,
|
||||
use_shift_enter_hint: bool,
|
||||
dismissed_file_popup_token: Option<String>,
|
||||
dismissed_slash_token: Option<String>,
|
||||
dismissed: Dismissed,
|
||||
current_file_query: Option<String>,
|
||||
pending_pastes: Vec<(String, String)>,
|
||||
}
|
||||
@@ -61,6 +62,13 @@ enum ActivePopup {
|
||||
Selection(SelectionPopup),
|
||||
}
|
||||
|
||||
/// Tracks tokens for which the user explicitly dismissed a popup to avoid
|
||||
/// reopening it immediately unless the input changes meaningfully.
|
||||
struct Dismissed {
|
||||
slash: Option<String>,
|
||||
file: Option<String>,
|
||||
}
|
||||
|
||||
impl ChatComposer<'_> {
|
||||
#[inline]
|
||||
fn first_line(&self) -> &str {
|
||||
@@ -91,7 +99,7 @@ impl ChatComposer<'_> {
|
||||
let msg = format!("{attempted} not a recognized command");
|
||||
self.app_event_tx
|
||||
.send(AppEvent::InsertHistory(vec![Line::from(msg)]));
|
||||
self.dismissed_slash_token = Some(cmd_token.to_string());
|
||||
self.dismissed.slash = Some(cmd_token.to_string());
|
||||
self.active_popup = ActivePopup::None;
|
||||
}
|
||||
|
||||
@@ -99,7 +107,7 @@ impl ChatComposer<'_> {
|
||||
fn sync_popups(&mut self) {
|
||||
self.sync_command_popup();
|
||||
if matches!(self.active_popup, ActivePopup::Command(_)) {
|
||||
self.dismissed_file_popup_token = None;
|
||||
self.dismissed.file = None;
|
||||
} else {
|
||||
self.sync_file_search_popup();
|
||||
}
|
||||
@@ -169,8 +177,10 @@ impl ChatComposer<'_> {
|
||||
history: ChatComposerHistory::new(),
|
||||
ctrl_c_quit_hint: false,
|
||||
use_shift_enter_hint,
|
||||
dismissed_file_popup_token: None,
|
||||
dismissed_slash_token: None,
|
||||
dismissed: Dismissed {
|
||||
slash: None,
|
||||
file: None,
|
||||
},
|
||||
current_file_query: None,
|
||||
pending_pastes: Vec::new(),
|
||||
};
|
||||
@@ -358,7 +368,7 @@ impl ChatComposer<'_> {
|
||||
ActivePopup::Command(_) => {
|
||||
self.sync_command_popup();
|
||||
// When slash popup active, suppress file popup.
|
||||
self.dismissed_file_popup_token = None;
|
||||
self.dismissed.file = None;
|
||||
}
|
||||
_ => {
|
||||
self.sync_command_popup();
|
||||
@@ -389,7 +399,7 @@ impl ChatComposer<'_> {
|
||||
}
|
||||
Input { key: Key::Esc, .. } => {
|
||||
if let Some(cmd_token) = Self::slash_token_from_first_line(&first_line_owned) {
|
||||
self.dismissed_slash_token = Some(cmd_token.to_string());
|
||||
self.dismissed.slash = Some(cmd_token.to_string());
|
||||
}
|
||||
self.active_popup = ActivePopup::None;
|
||||
(InputResult::None, true)
|
||||
@@ -435,11 +445,13 @@ impl ChatComposer<'_> {
|
||||
if *cmd == SlashCommand::Model && args.trim().is_empty() {
|
||||
self.app_event_tx.send(AppEvent::OpenModelSelector);
|
||||
} else if *cmd == SlashCommand::Approvals && args.trim().is_empty() {
|
||||
self.app_event_tx.send(AppEvent::OpenApprovalSelector);
|
||||
self.app_event_tx.send(AppEvent::OpenExecutionSelector);
|
||||
} else {
|
||||
// Send command + args to the app layer.
|
||||
self.app_event_tx
|
||||
.send(AppEvent::DispatchCommandWithArgs(*cmd, args));
|
||||
self.app_event_tx.send(AppEvent::DispatchCommand {
|
||||
cmd: *cmd,
|
||||
args: Some(args),
|
||||
});
|
||||
}
|
||||
|
||||
// Clear textarea so no residual text remains
|
||||
@@ -476,7 +488,7 @@ impl ChatComposer<'_> {
|
||||
Input { key: Key::Esc, .. } => {
|
||||
// Hide popup without modifying text, remember token to avoid immediate reopen.
|
||||
if let Some(tok) = Self::current_at_token(&self.textarea) {
|
||||
self.dismissed_file_popup_token = Some(tok.to_string());
|
||||
self.dismissed.file = Some(tok.to_string());
|
||||
}
|
||||
self.active_popup = ActivePopup::None;
|
||||
(InputResult::None, true)
|
||||
@@ -562,10 +574,10 @@ impl ChatComposer<'_> {
|
||||
if !args.is_empty() {
|
||||
match popup.kind() {
|
||||
SelectionKind::Model if cmd_token == SlashCommand::Model.command() => {
|
||||
self.app_event_tx.send(AppEvent::DispatchCommandWithArgs(
|
||||
SlashCommand::Model,
|
||||
args,
|
||||
));
|
||||
self.app_event_tx.send(AppEvent::DispatchCommand {
|
||||
cmd: SlashCommand::Model,
|
||||
args: Some(args),
|
||||
});
|
||||
self.textarea.select_all();
|
||||
self.textarea.cut();
|
||||
self.pending_pastes.clear();
|
||||
@@ -821,7 +833,7 @@ impl ChatComposer<'_> {
|
||||
let first_line = self.first_line().to_string();
|
||||
let input_starts_with_slash = first_line.starts_with('/');
|
||||
if !input_starts_with_slash {
|
||||
self.dismissed_slash_token = None;
|
||||
self.dismissed.slash = None;
|
||||
}
|
||||
let current_cmd_token: Option<&str> = Self::slash_token_from_first_line(&first_line);
|
||||
|
||||
@@ -864,13 +876,13 @@ impl ChatComposer<'_> {
|
||||
self.app_event_tx.send(AppEvent::OpenModelSelector);
|
||||
} else if should_open_approval_selector {
|
||||
self.active_popup = ActivePopup::None;
|
||||
self.app_event_tx.send(AppEvent::OpenApprovalSelector);
|
||||
self.app_event_tx.send(AppEvent::OpenExecutionSelector);
|
||||
} else {
|
||||
popup.on_composer_text_change(first_line.clone());
|
||||
}
|
||||
} else {
|
||||
self.active_popup = ActivePopup::None;
|
||||
self.dismissed_slash_token = None;
|
||||
self.dismissed.slash = None;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
@@ -880,11 +892,11 @@ impl ChatComposer<'_> {
|
||||
// dismissed the slash popup for this token.
|
||||
self.app_event_tx.send(AppEvent::OpenModelSelector);
|
||||
} else if should_open_approval_selector {
|
||||
self.app_event_tx.send(AppEvent::OpenApprovalSelector);
|
||||
self.app_event_tx.send(AppEvent::OpenExecutionSelector);
|
||||
} else {
|
||||
// Avoid immediate reopen of the slash popup if it was just dismissed for
|
||||
// this exact command token.
|
||||
if self.dismissed_slash_token.as_deref() == current_cmd_token {
|
||||
if self.dismissed.slash.as_deref() == current_cmd_token {
|
||||
return;
|
||||
}
|
||||
let mut command_popup = CommandPopup::new();
|
||||
@@ -904,13 +916,13 @@ impl ChatComposer<'_> {
|
||||
Some(token) => token,
|
||||
None => {
|
||||
self.active_popup = ActivePopup::None;
|
||||
self.dismissed_file_popup_token = None;
|
||||
self.dismissed.file = None;
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
// If user dismissed popup for this exact query, don't reopen until text changes.
|
||||
if self.dismissed_file_popup_token.as_ref() == Some(&query) {
|
||||
if self.dismissed.file.as_ref() == Some(&query) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -929,7 +941,7 @@ impl ChatComposer<'_> {
|
||||
}
|
||||
|
||||
self.current_file_query = Some(query);
|
||||
self.dismissed_file_popup_token = None;
|
||||
self.dismissed.file = None;
|
||||
}
|
||||
|
||||
/// Synchronize the selection popup filter with the current composer text.
|
||||
@@ -958,19 +970,23 @@ impl ChatComposer<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a leading "/command" and return (command_token, args_trimmed_left).
|
||||
/// Returns None if the line does not start with a slash or the command is empty.
|
||||
/// Parse a leading "/command" via the centralized slash parser, returning
|
||||
/// (command_token, args_trimmed_left) for compatibility with existing code.
|
||||
/// Returns None if the line does not start with a slash or the command token is empty.
|
||||
fn parse_slash_command_and_args_from_line(line: &str) -> Option<(String, String)> {
|
||||
if let Some(stripped) = line.strip_prefix('/') {
|
||||
let token = stripped.trim_start();
|
||||
let cmd_token = token.split_whitespace().next().unwrap_or("");
|
||||
if cmd_token.is_empty() {
|
||||
return None;
|
||||
match parse_slash_line(line) {
|
||||
ParsedSlash::Command { cmd, args } => {
|
||||
Some((cmd.command().to_string(), args.to_string()))
|
||||
}
|
||||
let rest = &token[cmd_token.len()..];
|
||||
Some((cmd_token.to_string(), rest.trim_start().to_string()))
|
||||
} else {
|
||||
None
|
||||
ParsedSlash::Incomplete { token } if !token.is_empty() => {
|
||||
// Compute rest of line after token for completeness.
|
||||
// We mimic the previous logic: take the substring after the token in the trimmed view.
|
||||
let stripped = line.strip_prefix('/')?;
|
||||
let token_with_ws = stripped.trim_start();
|
||||
let rest = &token_with_ws[token.len()..];
|
||||
Some((token.to_string(), rest.trim_start().to_string()))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1008,22 +1024,9 @@ impl WidgetRef for &ChatComposer<'_> {
|
||||
self.textarea.render(textarea_rect, buf);
|
||||
}
|
||||
ActivePopup::Selection(popup) => {
|
||||
let popup_height = popup.calculate_required_height();
|
||||
|
||||
let popup_height = popup_height.min(area.height);
|
||||
let textarea_rect = Rect {
|
||||
x: area.x,
|
||||
y: area.y,
|
||||
width: area.width,
|
||||
height: area.height.saturating_sub(popup_height),
|
||||
};
|
||||
let popup_rect = Rect {
|
||||
x: area.x,
|
||||
y: area.y + textarea_rect.height,
|
||||
width: area.width,
|
||||
height: popup_height,
|
||||
};
|
||||
|
||||
let desired_popup = popup.calculate_required_height();
|
||||
let (textarea_rect, popup_rect) =
|
||||
self.compute_textarea_and_popup_rect(area, desired_popup);
|
||||
popup.render(popup_rect, buf);
|
||||
self.textarea.render(textarea_rect, buf);
|
||||
}
|
||||
@@ -1301,7 +1304,10 @@ mod tests {
|
||||
let sender = AppEventSender::new(tx);
|
||||
let mut terminal = match Terminal::new(TestBackend::new(100, 10)) {
|
||||
Ok(t) => t,
|
||||
Err(e) => panic!("Failed to create terminal: {e}"),
|
||||
Err(e) => {
|
||||
eprintln!("Skipping ui_snapshots: failed to create terminal: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let test_cases = vec![
|
||||
@@ -1335,9 +1341,8 @@ mod tests {
|
||||
composer.handle_key_event(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE));
|
||||
}
|
||||
|
||||
terminal
|
||||
.draw(|f| f.render_widget_ref(&composer, f.area()))
|
||||
.unwrap_or_else(|e| panic!("Failed to draw {name} composer: {e}"));
|
||||
let draw_res = terminal.draw(|f| f.render_widget_ref(&composer, f.area()));
|
||||
assert!(draw_res.is_ok(), "Failed to draw {name} composer");
|
||||
|
||||
assert_snapshot!(name, terminal.backend());
|
||||
}
|
||||
@@ -1833,11 +1838,11 @@ mod tests {
|
||||
use crossterm::event::KeyModifiers;
|
||||
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
|
||||
|
||||
// We should emit OpenApprovalSelector
|
||||
// We should emit OpenExecutionSelector
|
||||
let mut saw_open = false;
|
||||
loop {
|
||||
match rx.try_recv() {
|
||||
Ok(AppEvent::OpenApprovalSelector) => {
|
||||
Ok(AppEvent::OpenExecutionSelector) => {
|
||||
saw_open = true;
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -1,26 +1,16 @@
|
||||
use ratatui::buffer::Buffer;
|
||||
use ratatui::layout::Rect;
|
||||
use ratatui::style::Color;
|
||||
use ratatui::style::Style;
|
||||
use ratatui::style::Stylize;
|
||||
use ratatui::symbols::border::QUADRANT_LEFT_HALF;
|
||||
use ratatui::text::Line;
|
||||
use ratatui::text::Span;
|
||||
use ratatui::widgets::Cell;
|
||||
use ratatui::widgets::Row;
|
||||
use ratatui::widgets::Table;
|
||||
use ratatui::widgets::Widget;
|
||||
use ratatui::widgets::WidgetRef;
|
||||
|
||||
use crate::slash_command::SlashCommand;
|
||||
use crate::slash_command::built_in_slash_commands;
|
||||
|
||||
const MAX_POPUP_ROWS: usize = 5;
|
||||
/// Ideally this is enough to show the longest command name.
|
||||
const FIRST_COLUMN_WIDTH: u16 = 20;
|
||||
use super::popup_consts::MAX_POPUP_ROWS;
|
||||
use super::selection_popup_common::GenericDisplayRow;
|
||||
use super::selection_popup_common::render_rows;
|
||||
|
||||
use super::scroll_state::ScrollState;
|
||||
use ratatui::style::Modifier;
|
||||
use codex_common::fuzzy_match::fuzzy_match;
|
||||
|
||||
pub(crate) struct CommandPopup {
|
||||
command_filter: String,
|
||||
@@ -74,24 +64,29 @@ impl CommandPopup {
|
||||
self.filtered_commands().len().clamp(1, MAX_POPUP_ROWS) as u16
|
||||
}
|
||||
|
||||
/// Return the list of commands that match the current filter. Matching is
|
||||
/// performed using a case-insensitive prefix comparison on the command name.
|
||||
/// Compute fuzzy-filtered matches paired with optional highlight indices and score.
|
||||
/// Sorted by ascending score, then by command name for stability.
|
||||
fn filtered(&self) -> Vec<(&SlashCommand, Option<Vec<usize>>, i32)> {
|
||||
let filter = self.command_filter.trim();
|
||||
let mut out: Vec<(&SlashCommand, Option<Vec<usize>>, i32)> = Vec::new();
|
||||
if filter.is_empty() {
|
||||
for (_, cmd) in self.all_commands.iter() {
|
||||
out.push((cmd, None, 0));
|
||||
}
|
||||
} else {
|
||||
for (_, cmd) in self.all_commands.iter() {
|
||||
if let Some((indices, score)) = fuzzy_match(cmd.command(), filter) {
|
||||
out.push((cmd, Some(indices), score));
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| a.2.cmp(&b.2).then_with(|| a.0.command().cmp(b.0.command())));
|
||||
out
|
||||
}
|
||||
|
||||
/// Backwards-compatible helper used by tests.
|
||||
fn filtered_commands(&self) -> Vec<&SlashCommand> {
|
||||
let filter = self.command_filter.as_str();
|
||||
self.all_commands
|
||||
.iter()
|
||||
.filter_map(|(_name, cmd)| {
|
||||
if filter.is_empty() {
|
||||
return Some(cmd);
|
||||
}
|
||||
let name = cmd.command();
|
||||
if name.len() >= filter.len() && name[..filter.len()].eq_ignore_ascii_case(filter) {
|
||||
Some(cmd)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect::<Vec<&SlashCommand>>()
|
||||
self.filtered().into_iter().map(|(c, _, _)| c).collect()
|
||||
}
|
||||
|
||||
/// Move the selection cursor one step up.
|
||||
@@ -122,73 +117,24 @@ impl CommandPopup {
|
||||
|
||||
impl WidgetRef for CommandPopup {
|
||||
fn render_ref(&self, area: Rect, buf: &mut Buffer) {
|
||||
let matches = self.filtered_commands();
|
||||
|
||||
let mut rows: Vec<Row> = Vec::new();
|
||||
|
||||
if matches.is_empty() {
|
||||
rows.push(Row::new(vec![
|
||||
Cell::from(""),
|
||||
Cell::from("No matching commands").add_modifier(Modifier::ITALIC),
|
||||
]));
|
||||
let matches = self.filtered();
|
||||
let rows_all: Vec<GenericDisplayRow> = if matches.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
let default_style = Style::default();
|
||||
let command_style = Style::default().fg(Color::LightBlue);
|
||||
let max_rows_from_area = area.height as usize;
|
||||
let visible_rows = MAX_POPUP_ROWS
|
||||
.min(matches.len())
|
||||
.min(max_rows_from_area.max(1));
|
||||
// Ensure the window is consistent with current area and selection
|
||||
let mut start_idx = self.state.scroll_top.min(matches.len().saturating_sub(1));
|
||||
if let Some(sel) = self.state.selected_idx {
|
||||
if sel < start_idx {
|
||||
start_idx = sel;
|
||||
} else if visible_rows > 0 {
|
||||
let bottom = start_idx + visible_rows - 1;
|
||||
if sel > bottom {
|
||||
start_idx = sel + 1 - visible_rows;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (global_idx, cmd) in matches
|
||||
.iter()
|
||||
.enumerate()
|
||||
.skip(start_idx)
|
||||
.take(visible_rows)
|
||||
{
|
||||
rows.push(Row::new(vec![
|
||||
Cell::from(Line::from(vec![
|
||||
if Some(global_idx) == self.state.selected_idx {
|
||||
Span::styled(
|
||||
"›",
|
||||
Style::default().bg(Color::DarkGray).fg(Color::LightCyan),
|
||||
)
|
||||
} else {
|
||||
Span::styled(QUADRANT_LEFT_HALF, Style::default().fg(Color::DarkGray))
|
||||
},
|
||||
Span::styled(format!("/{}", cmd.command()), command_style),
|
||||
])),
|
||||
Cell::from(cmd.description().to_string()).style(default_style),
|
||||
]));
|
||||
}
|
||||
}
|
||||
|
||||
use ratatui::layout::Constraint;
|
||||
|
||||
let table = Table::new(
|
||||
rows,
|
||||
[Constraint::Length(FIRST_COLUMN_WIDTH), Constraint::Min(10)],
|
||||
)
|
||||
.column_spacing(0);
|
||||
// .block(
|
||||
// Block::default()
|
||||
// .borders(Borders::LEFT)
|
||||
// .border_type(BorderType::QuadrantOutside)
|
||||
// .border_style(Style::default().fg(Color::DarkGray)),
|
||||
// );
|
||||
|
||||
table.render(area, buf);
|
||||
matches
|
||||
.into_iter()
|
||||
.map(|(cmd, indices, _)| GenericDisplayRow {
|
||||
name: format!("/{}", cmd.command()),
|
||||
match_indices: indices.map(|v| {
|
||||
// Shift highlight indices by one to account for the leading '/'
|
||||
v.into_iter().map(|i| i + 1).collect()
|
||||
}),
|
||||
is_current: false,
|
||||
description: Some(cmd.description().to_string()),
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
render_rows(area, buf, &rows_all, &self.state, MAX_POPUP_ROWS);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,6 +143,7 @@ mod tests {
|
||||
use super::*;
|
||||
use ratatui::buffer::Buffer;
|
||||
use ratatui::layout::Rect;
|
||||
use ratatui::widgets::Widget;
|
||||
|
||||
#[test]
|
||||
fn move_down_wraps_to_top() {
|
||||
|
||||
@@ -16,8 +16,7 @@ use ratatui::widgets::Table;
|
||||
use ratatui::widgets::Widget;
|
||||
use ratatui::widgets::WidgetRef;
|
||||
|
||||
/// Maximum number of suggestions shown in the popup.
|
||||
const MAX_RESULTS: usize = 8;
|
||||
use super::popup_consts::MAX_POPUP_ROWS;
|
||||
|
||||
/// Visual state for the file-search popup.
|
||||
pub(crate) struct FileSearchPopup {
|
||||
@@ -115,7 +114,7 @@ impl FileSearchPopup {
|
||||
// up to MAX_RESULTS regardless of the waiting flag so the list
|
||||
// remains stable while a newer search is in-flight.
|
||||
|
||||
self.matches.len().clamp(1, MAX_RESULTS) as u16
|
||||
self.matches.len().clamp(1, MAX_POPUP_ROWS) as u16
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,26 +133,24 @@ impl WidgetRef for &FileSearchPopup {
|
||||
} else {
|
||||
self.matches
|
||||
.iter()
|
||||
.take(MAX_RESULTS)
|
||||
.take(MAX_POPUP_ROWS)
|
||||
.enumerate()
|
||||
.map(|(i, file_match)| {
|
||||
let FileMatch { path, indices, .. } = file_match;
|
||||
let path = path.as_str();
|
||||
#[allow(clippy::expect_used)]
|
||||
let indices = indices.as_ref().expect("indices should be present");
|
||||
let indices_opt = indices.as_ref();
|
||||
|
||||
// Build spans with bold on matching indices.
|
||||
let mut idx_iter = indices.iter().peekable();
|
||||
// Build spans with bold on matching indices when provided by the searcher.
|
||||
let mut idx_iter = indices_opt.map(|v| v.iter().peekable());
|
||||
let mut spans: Vec<Span> = Vec::with_capacity(path.len());
|
||||
|
||||
for (char_idx, ch) in path.chars().enumerate() {
|
||||
let mut style = Style::default();
|
||||
if idx_iter
|
||||
.peek()
|
||||
.is_some_and(|next| **next == char_idx as u32)
|
||||
{
|
||||
idx_iter.next();
|
||||
style = style.add_modifier(Modifier::BOLD);
|
||||
if let Some(iter) = idx_iter.as_mut() {
|
||||
if iter.peek().is_some_and(|next| **next == char_idx as u32) {
|
||||
iter.next();
|
||||
style = style.add_modifier(Modifier::BOLD);
|
||||
}
|
||||
}
|
||||
spans.push(Span::styled(ch.to_string(), style));
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ mod chat_composer;
|
||||
mod chat_composer_history;
|
||||
mod command_popup;
|
||||
mod file_search_popup;
|
||||
mod popup_consts;
|
||||
mod scroll_state;
|
||||
mod selection_list;
|
||||
pub(crate) mod selection_popup;
|
||||
|
||||
@@ -1,123 +0,0 @@
|
||||
use super::scroll_state::ScrollState;
|
||||
use codex_common::fuzzy_match::fuzzy_indices;
|
||||
use ratatui::buffer::Buffer;
|
||||
use ratatui::layout::Rect;
|
||||
use ratatui::widgets::WidgetRef;
|
||||
|
||||
use super::selection_popup_common::GenericDisplayRow;
|
||||
use super::selection_popup_common::render_rows;
|
||||
|
||||
/// Maximum number of options shown in the popup.
|
||||
const MAX_RESULTS: usize = 8;
|
||||
|
||||
/// Visual state for the model-selection popup.
|
||||
pub(crate) struct ModelSelectionPopup {
|
||||
/// The current model (pinned and color-coded when visible).
|
||||
current_model: String,
|
||||
/// All available model options (deduplicated externally as needed).
|
||||
options: Vec<String>,
|
||||
/// Current filter query (derived from the composer, e.g. after `/model`).
|
||||
query: String,
|
||||
/// Selection/scroll state across the visible rows.
|
||||
state: ScrollState,
|
||||
}
|
||||
|
||||
impl ModelSelectionPopup {
|
||||
pub(crate) fn new(current_model: &str, options: Vec<String>) -> Self {
|
||||
let mut this = Self {
|
||||
current_model: current_model.to_string(),
|
||||
options,
|
||||
query: String::new(),
|
||||
state: ScrollState::new(),
|
||||
};
|
||||
// Initialize selection to the first visible row if any, so Enter works immediately.
|
||||
let visible_len = this.visible_rows().len();
|
||||
this.state.clamp_selection(visible_len);
|
||||
this.state
|
||||
.ensure_visible(visible_len, MAX_RESULTS.min(visible_len));
|
||||
this
|
||||
}
|
||||
|
||||
/// Update the current model and option list. Resets/clamps selection as needed.
|
||||
pub(crate) fn set_options(&mut self, current_model: &str, options: Vec<String>) {
|
||||
self.current_model = current_model.to_string();
|
||||
self.options = options;
|
||||
let visible_len = self.visible_rows().len();
|
||||
self.state.clamp_selection(visible_len);
|
||||
self.state
|
||||
.ensure_visible(visible_len, MAX_RESULTS.min(visible_len));
|
||||
}
|
||||
|
||||
/// Update the fuzzy filter query.
|
||||
pub(crate) fn set_query(&mut self, query: &str) {
|
||||
if self.query == query {
|
||||
return;
|
||||
}
|
||||
self.query.clear();
|
||||
self.query.push_str(query);
|
||||
// Reset/clamp selection based on new filtered list.
|
||||
let visible_len = self.visible_rows().len();
|
||||
if visible_len == 0 {
|
||||
self.state.reset();
|
||||
} else {
|
||||
self.state.selected_idx = Some(0);
|
||||
self.state
|
||||
.ensure_visible(visible_len, MAX_RESULTS.min(visible_len));
|
||||
}
|
||||
}
|
||||
|
||||
/// Move selection cursor up.
|
||||
pub(crate) fn move_up(&mut self) {
|
||||
let len = self.visible_rows().len();
|
||||
self.state.move_up_wrap(len);
|
||||
self.state.ensure_visible(len, MAX_RESULTS.min(len));
|
||||
}
|
||||
|
||||
/// Move selection cursor down.
|
||||
pub(crate) fn move_down(&mut self) {
|
||||
let len = self.visible_rows().len();
|
||||
self.state.move_down_wrap(len);
|
||||
self.state.ensure_visible(len, MAX_RESULTS.min(len));
|
||||
}
|
||||
|
||||
/// Currently selected model name, if any.
|
||||
pub(crate) fn selected_model(&self) -> Option<String> {
|
||||
let rows = self.visible_rows();
|
||||
self.state
|
||||
.selected_idx
|
||||
.and_then(|idx| rows.get(idx).map(|r| r.name.clone()))
|
||||
}
|
||||
|
||||
/// Preferred height (rows) including border.
|
||||
pub(crate) fn calculate_required_height(&self) -> u16 {
|
||||
self.visible_rows().len().clamp(1, MAX_RESULTS) as u16
|
||||
}
|
||||
|
||||
/// Compute rows to display applying fuzzy filtering and pinning current model.
|
||||
fn visible_rows(&self) -> Vec<GenericDisplayRow> {
|
||||
// Rebuild items on the fly to use the unified selection list behavior.
|
||||
use super::selection_list::{SelectionItem, SelectionList};
|
||||
let mut items: Vec<SelectionItem<String>> = Vec::new();
|
||||
items.push(SelectionItem::new(self.current_model.clone(), self.current_model.clone()).mark_current(true));
|
||||
for m in self
|
||||
.options
|
||||
.iter()
|
||||
.filter(|s| *s != &self.current_model)
|
||||
{
|
||||
items.push(SelectionItem::new(m.clone(), m.clone()));
|
||||
}
|
||||
|
||||
let mut list = SelectionList::new(items);
|
||||
list.state.selected_idx = self.state.selected_idx;
|
||||
list.state.scroll_top = self.state.scroll_top;
|
||||
list.set_query(&self.query);
|
||||
list.visible_rows().into_iter().map(|(row, _)| row).collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl WidgetRef for &ModelSelectionPopup {
|
||||
fn render_ref(&self, area: Rect, buf: &mut Buffer) {
|
||||
let rows_all = self.visible_rows();
|
||||
render_rows(area, buf, &rows_all, &self.state, MAX_RESULTS);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
//! Shared popup-related constants for bottom pane widgets.
|
||||
|
||||
/// Maximum number of rows any popup should attempt to display.
|
||||
/// Keep this consistent across all popups for a uniform feel.
|
||||
pub(crate) const MAX_POPUP_ROWS: usize = 8;
|
||||
@@ -1,5 +1,13 @@
|
||||
//! Generic selection-list abstraction shared by model/execution selectors and other popups.
|
||||
//!
|
||||
//! This module provides `SelectionItem` (a value with name/description/aliases),
|
||||
//! and `SelectionList` which maintains filtering and scroll/selection state.
|
||||
//! The UI layer can convert items to `GenericDisplayRow` for rendering via
|
||||
//! `selection_popup_common::render_rows`.
|
||||
|
||||
use codex_common::fuzzy_match::fuzzy_match;
|
||||
|
||||
use super::popup_consts::MAX_POPUP_ROWS;
|
||||
use super::scroll_state::ScrollState;
|
||||
use super::selection_popup_common::GenericDisplayRow;
|
||||
|
||||
@@ -56,7 +64,8 @@ impl<T: Clone> SelectionList<T> {
|
||||
};
|
||||
let visible_len = this.visible_rows().len();
|
||||
this.state.clamp_selection(visible_len);
|
||||
this.state.ensure_visible(visible_len, visible_len.min(8));
|
||||
this.state
|
||||
.ensure_visible(visible_len, visible_len.min(MAX_POPUP_ROWS));
|
||||
this
|
||||
}
|
||||
|
||||
@@ -71,20 +80,21 @@ impl<T: Clone> SelectionList<T> {
|
||||
self.state.reset();
|
||||
} else {
|
||||
self.state.selected_idx = Some(0);
|
||||
self.state.ensure_visible(visible_len, visible_len.min(8));
|
||||
self.state
|
||||
.ensure_visible(visible_len, visible_len.min(MAX_POPUP_ROWS));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn move_up(&mut self) {
|
||||
let len = self.visible_rows().len();
|
||||
self.state.move_up_wrap(len);
|
||||
self.state.ensure_visible(len, len.min(8));
|
||||
self.state.ensure_visible(len, len.min(MAX_POPUP_ROWS));
|
||||
}
|
||||
|
||||
pub fn move_down(&mut self) {
|
||||
let len = self.visible_rows().len();
|
||||
self.state.move_down_wrap(len);
|
||||
self.state.ensure_visible(len, len.min(8));
|
||||
self.state.ensure_visible(len, len.min(MAX_POPUP_ROWS));
|
||||
}
|
||||
|
||||
pub fn selected_value(&self) -> Option<T> {
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
//! Generic selection popup for multiple use-cases (models, execution modes, etc.).
|
||||
//!
|
||||
//! Construct with `new_model` or `new_execution_modes`, pass key events to move
|
||||
//! selection and update the query via `set_query`, then render with
|
||||
//! `selection_popup_common::render_rows`.
|
||||
use codex_core::protocol::AskForApproval;
|
||||
use codex_core::protocol::SandboxPolicy;
|
||||
use ratatui::buffer::Buffer;
|
||||
use ratatui::layout::Rect;
|
||||
use ratatui::widgets::WidgetRef;
|
||||
|
||||
use super::popup_consts::MAX_POPUP_ROWS;
|
||||
use super::selection_list::SelectionItem;
|
||||
use super::selection_list::SelectionList;
|
||||
use super::selection_popup_common::GenericDisplayRow;
|
||||
@@ -30,8 +36,6 @@ pub(crate) struct SelectionPopup {
|
||||
list: SelectionList<SelectionValue>,
|
||||
}
|
||||
|
||||
const MAX_RESULTS: usize = 8;
|
||||
|
||||
impl SelectionPopup {
|
||||
pub(crate) fn new_model(current_model: &str, options: Vec<String>) -> Self {
|
||||
let mut items: Vec<SelectionItem<SelectionValue>> = Vec::new();
|
||||
@@ -106,7 +110,7 @@ impl SelectionPopup {
|
||||
self.list.move_down();
|
||||
}
|
||||
pub(crate) fn calculate_required_height(&self) -> u16 {
|
||||
self.list.visible_rows().len().clamp(1, MAX_RESULTS) as u16
|
||||
self.list.visible_rows().len().clamp(1, MAX_POPUP_ROWS) as u16
|
||||
}
|
||||
pub(crate) fn selected_value(&self) -> Option<SelectionValue> {
|
||||
self.list.selected_value()
|
||||
@@ -124,7 +128,7 @@ impl SelectionPopup {
|
||||
impl WidgetRef for &SelectionPopup {
|
||||
fn render_ref(&self, area: Rect, buf: &mut Buffer) {
|
||||
let rows_all = self.visible_rows();
|
||||
render_rows(area, buf, &rows_all, &self.list.state, MAX_RESULTS);
|
||||
render_rows(area, buf, &rows_all, &self.list.state, MAX_POPUP_ROWS);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -538,39 +538,42 @@ impl ChatWidget<'_> {
|
||||
|
||||
/// Open the model selection view in the bottom pane.
|
||||
pub(crate) fn show_model_selector(&mut self) {
|
||||
use std::collections::HashSet;
|
||||
|
||||
let current = self.config.model.clone();
|
||||
|
||||
let mut options = get_all_model_names()
|
||||
// Collect unique options from built-ins, current config, CLI, and config.toml.
|
||||
let mut set: HashSet<String> = get_all_model_names()
|
||||
.into_iter()
|
||||
.map(|s| s.to_string())
|
||||
.collect::<Vec<_>>();
|
||||
.collect();
|
||||
|
||||
// Always include the currently configured model (covers custom values).
|
||||
options.push(current.clone());
|
||||
set.insert(current.clone());
|
||||
|
||||
// Include model specified via --model if present.
|
||||
if let Some(m) = &self.cli_model {
|
||||
set.insert(m.clone());
|
||||
}
|
||||
|
||||
// Append any models found in config.toml profiles and top-level model.
|
||||
let config_path = self.config.codex_home.join("config.toml");
|
||||
if let Ok(contents) = std::fs::read_to_string(&config_path) {
|
||||
if let Ok(cfg) = toml::from_str::<ConfigToml>(&contents) {
|
||||
let mut config_models: Vec<String> = Vec::new();
|
||||
if let Some(m) = cfg.model {
|
||||
config_models.push(m);
|
||||
set.insert(m);
|
||||
}
|
||||
for (_name, profile) in cfg.profiles.into_iter() {
|
||||
if let Some(m) = profile.model {
|
||||
config_models.push(m);
|
||||
set.insert(m);
|
||||
}
|
||||
}
|
||||
// Alphabetical ordering for config models.
|
||||
config_models.sort();
|
||||
options.extend(config_models);
|
||||
}
|
||||
}
|
||||
|
||||
// Include model specified via --model if present.
|
||||
if let Some(m) = &self.cli_model {
|
||||
options.push(m.clone());
|
||||
}
|
||||
// Present options in a stable order for the UI.
|
||||
let mut options: Vec<String> = set.into_iter().collect();
|
||||
options.sort();
|
||||
|
||||
self.bottom_pane.show_model_selector(¤t, options);
|
||||
}
|
||||
|
||||
@@ -201,4 +201,33 @@ mod tests {
|
||||
assert_eq!(parse("unknown"), None);
|
||||
assert!(parse(" AUTO ").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn execution_preset_round_trip() {
|
||||
// For each preset, ensure to_policies -> from_policies -> label/description are consistent
|
||||
let presets = [
|
||||
ExecutionPreset::ReadOnly,
|
||||
ExecutionPreset::Untrusted,
|
||||
ExecutionPreset::Auto,
|
||||
ExecutionPreset::FullYolo,
|
||||
];
|
||||
|
||||
for p in presets {
|
||||
let (a, s) = p.to_policies();
|
||||
// Back to preset
|
||||
assert_eq!(ExecutionPreset::from_policies(a, &s), Some(p));
|
||||
// Labels and descriptions are non-empty and stable
|
||||
assert!(!p.label().is_empty());
|
||||
assert!(!p.description().is_empty());
|
||||
|
||||
// Parsing the canonical token yields the same preset
|
||||
let token = match p {
|
||||
ExecutionPreset::ReadOnly => "read-only",
|
||||
ExecutionPreset::Untrusted => "untrusted",
|
||||
ExecutionPreset::Auto => "auto",
|
||||
ExecutionPreset::FullYolo => "full-yolo",
|
||||
};
|
||||
assert_eq!(ExecutionPreset::parse_token(token), Some(p));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use std::str::FromStr;
|
||||
use strum::IntoEnumIterator;
|
||||
use strum_macros::AsRefStr;
|
||||
use strum_macros::EnumIter;
|
||||
@@ -50,3 +51,71 @@ impl SlashCommand {
|
||||
pub fn built_in_slash_commands() -> Vec<(&'static str, SlashCommand)> {
|
||||
SlashCommand::iter().map(|c| (c.command(), c)).collect()
|
||||
}
|
||||
|
||||
/// Parsed representation of a line that may start with a slash command.
|
||||
pub enum ParsedSlash<'a> {
|
||||
/// A recognized command along with the left-trimmed arguments.
|
||||
Command { cmd: SlashCommand, args: &'a str },
|
||||
/// A leading slash and a token were present, but the token is not a known command.
|
||||
Incomplete { token: &'a str },
|
||||
/// Line does not represent a slash command.
|
||||
None,
|
||||
}
|
||||
|
||||
/// Parse the first line of input and detect a leading slash command.
|
||||
///
|
||||
/// Returns:
|
||||
/// - ParsedSlash::Command if the token matches a known command; `args` is the
|
||||
/// remainder of the line after the token, with leading whitespace trimmed.
|
||||
/// - ParsedSlash::Incomplete if there is a token after '/', but it does not
|
||||
/// correspond to a known command.
|
||||
/// - ParsedSlash::None if the line does not start with '/'.
|
||||
pub fn parse_slash_line(line: &str) -> ParsedSlash<'_> {
|
||||
let Some(stripped) = line.strip_prefix('/') else {
|
||||
return ParsedSlash::None;
|
||||
};
|
||||
let token_with_ws = stripped.trim_start();
|
||||
let token = token_with_ws.split_whitespace().next().unwrap_or("");
|
||||
if token.is_empty() {
|
||||
return ParsedSlash::Incomplete { token: "" };
|
||||
}
|
||||
match SlashCommand::from_str(token) {
|
||||
Ok(cmd) => {
|
||||
let rest = &token_with_ws[token.len()..];
|
||||
let args = rest.trim_start();
|
||||
ParsedSlash::Command { cmd, args }
|
||||
}
|
||||
Err(_) => ParsedSlash::Incomplete { token },
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_known_command_and_args() {
|
||||
let p = parse_slash_line("/model gpt-4o");
|
||||
match p {
|
||||
ParsedSlash::Command { cmd, args } => {
|
||||
assert_eq!(cmd, SlashCommand::Model);
|
||||
assert_eq!(args, "gpt-4o");
|
||||
}
|
||||
_ => panic!("expected Command"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incomplete_for_unknown_token() {
|
||||
let p = parse_slash_line("/not-a-cmd something");
|
||||
match p {
|
||||
ParsedSlash::Incomplete { token } => assert_eq!(token, "not-a-cmd"),
|
||||
_ => panic!("expected Incomplete"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn none_for_non_command() {
|
||||
matches!(parse_slash_line("hello"), ParsedSlash::None);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user