Skip to content

When using @ to mention files, it should default to showing a list of all files rather than 'no matches' #2867

Closed as not planned

Description

@0xdevalias

What feature would you like to see?

Currently when we use @ to mention a file, it defaults to showing 'no matches':

▌@
▌no matches

But sometimes I don't remember the name of the file I want to mention straight away, and so need to separately check the folder externally, or prompt with an ls type command or similar.

It would be nice if typing @ defaulted to showing the list of files that I could then select from, rather than the less useful 'no matches'.

A current hacky workaround is to type @ followed by a vowel, and know that at least that way I will see some selection of files that I could pick from, but this feels like a bit of a hack, and there is still a 1 in 5'ish chance I wouldn't see the file I wanted still anyway.

Are you interested in implementing this feature?

Unfortunately I don't have the capacity to currently, nor the familiarity with rust.

Additional information

See Also

Activity

  1. added
    enhancement
    on Aug 29, 2025
  2. 0xdevalias commented on Aug 29, 2025

    @0xdevalias
    Author

    Within sync_file_search_popup, this part looks related to empty query:

    match &mut self.active_popup {
    ActivePopup::File(popup) => {
    if query.is_empty() {
    popup.set_empty_prompt();
    } else {
    popup.set_query(&query);
    }
    }
    _ => {
    let mut popup = FileSearchPopup::new();
    if query.is_empty() {
    popup.set_empty_prompt();
    } else {
    popup.set_query(&query);
    }
    self.active_popup = ActivePopup::File(popup);
    }

    And this is FileSearchPopup's set_empty_prompt that it calls:

    /// Put the popup into an "idle" state used for an empty query (just "@").
    /// Shows a hint instead of matches until the user types more characters.
    pub(crate) fn set_empty_prompt(&mut self) {
    self.display_query.clear();
    self.pending_query.clear();
    self.waiting = false;
    self.matches.clear();
    // Reset selection/scroll state when showing the empty prompt.
    self.state.reset();
    }

    FileSearchPopup's set_query is also used when non-blank:

    /// Update the query and reset state to *waiting*.
    pub(crate) fn set_query(&mut self, query: &str) {
    if query == self.pending_query {
    return;
    }
    // Determine if current matches are still relevant.
    let keep_existing = query.starts_with(&self.display_query);
    self.pending_query.clear();
    self.pending_query.push_str(query);
    self.waiting = true; // waiting for new results
    if !keep_existing {
    self.matches.clear();
    self.state.reset();
    }
    }

    The FileSearchManager's on_user_query function seems to relate to when the user edits the @ token:

    /// Call whenever the user edits the `@` token.
    pub fn on_user_query(&self, query: String) {

    And eventually calls FileSearchManager::spawn_file_search:

    FileSearchManager::spawn_file_search(
    query,
    search_dir,
    tx_clone,
    cancellation_token,
    state,
    );

    Which seems to call file_search::run:

    fn spawn_file_search(
    query: String,
    search_dir: PathBuf,
    tx: AppEventSender,
    cancellation_token: Arc<AtomicBool>,
    search_state: Arc<Mutex<SearchState>>,
    ) {
    let compute_indices = true;
    std::thread::spawn(move || {
    let matches = file_search::run(
    &query,
    MAX_FILE_SEARCH_RESULTS,
    &search_dir,
    Vec::new(),
    NUM_FILE_SEARCH_THREADS,
    cancellation_token.clone(),
    compute_indices,
    )
    .map(|res| res.matches)
    .unwrap_or_default();

    Which calls create_pattern:

    pub fn run(
    pattern_text: &str,
    limit: NonZero<usize>,
    search_directory: &Path,
    exclude: Vec<String>,
    threads: NonZero<usize>,
    cancel_flag: Arc<AtomicBool>,
    compute_indices: bool,
    ) -> anyhow::Result<FileSearchResults> {
    let pattern = create_pattern(pattern_text);

    And then uses the same library that ripgrep uses:

    // Use the same tree-walker library that ripgrep uses. We use it directly so
    // that we can leverage the parallelism it provides.
    let mut walk_builder = WalkBuilder::new(search_directory);

    create_pattern seems to be a basic wrapper/helper:

    fn create_pattern(pattern: &str) -> Pattern {
    Pattern::new(
    pattern,
    CaseMatching::Smart,
    Normalization::Smart,
    AtomKind::Fuzzy,
    )
    }

    If we were just using rg directly we could do something like the following to list the files:

    ⇒ rg --files
    
    AGENTS.md
    foo.json

    So something similar to that as the default when using a raw @ would be useful.


    One potential (naive) suggestion I iterated on with GitHub Copilot + GPT-5:

    A minimal approach is feasible: (1) always dispatch a search event even when the @ token is empty, and (2) short‑circuit spawn_file_search so that an empty query returns a cached (or lazily-built) shallow file list instead of invoking the fuzzy search. This keeps UI + event flow unchanged and avoids adding new event variants.

    Summary of minimal changes:

    1. In ChatComposer::sync_file_search_popup remove the if !query.is_empty() guard so an empty query still triggers AppEvent::StartFileSearch("").

    2. In FileSearchManager::spawn_file_search, detect query.is_empty(). If empty:

      • Build (or reuse) a cached default list (shallow WalkDir up to a small depth; cap length at MAX_FILE_SEARCH_RESULTS).
      • Send AppEvent::FileSearchResult { query: "", matches }.
      • Clear active_search (so later real queries aren’t blocked).
      • Return without calling the expensive fuzzy file_search::run.
    3. Add a small cache container inside SearchState (e.g. default_file_list: Option<Vec<FileMatch>>) so repeated empty queries are instant.

    Trade‑offs / caveats:

    • If the repo changes (new files) you won’t see them until a fresh session (same as current prompts note) unless you add an invalidation condition (optional).
    • Highlight indices: for an empty query we can leave indices: None (makes UI show plain names).
    • Threading: Must manually clear active_search because we skip the normal completion code path.

    Below is a concrete minimal patch (illustrative; adjust paths/imports if needed). It keeps logic tight and avoids introducing new events or popup methods.

    codex-rs/tui/src/file_search.rs

    diff --git a/codex-rs/tui/src/file_search.rs b/codex-rs/tui/src/file_search.rs
    @@
     struct SearchState {
         latest_query: String,
         is_search_scheduled: bool,
         active_search: Option<ActiveSearch>,
    +    /// Cached list of default files for the empty query.
    +    default_file_list: Option<Vec<FileMatch>>,
     }
     
     impl FileSearchManager {
         pub fn new(search_dir: PathBuf, tx: AppEventSender) -> Self {
             Self {
                 state: Arc::new(Mutex::new(SearchState {
                     latest_query: String::new(),
                     is_search_scheduled: false,
                     active_search: None,
    +                default_file_list: None,
                 })),
                 search_dir,
                 app_tx: tx,
             }
         }
    @@
         fn spawn_file_search(
             query: String,
             search_dir: PathBuf,
             tx: AppEventSender,
             cancellation_token: Arc<AtomicBool>,
             search_state: Arc<Mutex<SearchState>>,
         ) {
    -        let compute_indices = true;
    -        std::thread::spawn(move || {
    +        // Fast-path for empty query: return (cached) shallow file list
    +        if query.is_empty() {
    +            // Build or reuse cache synchronously (cheap shallow walk).
    +            let matches_opt = {
    +                #[expect(clippy::unwrap_used)]
    +                let mut st = search_state.lock().unwrap();
    +                if let Some(cached) = &st.default_file_list {
    +                    Some(cached.clone())
    +                } else {
    +                    drop(st); // release lock during IO
    +                    let mut collected: Vec<FileMatch> = Vec::new();
    +                    // Shallow enumeration: depth 2 is usually enough to be useful.
    +                    let max_depth = 2;
    +                    for entry in walkdir::WalkDir::new(&search_dir)
    +                        .max_depth(max_depth)
    +                        .into_iter()
    +                        .filter_map(|e| e.ok())
    +                    {
    +                        if collected.len() >= MAX_FILE_SEARCH_RESULTS {
    +                            break;
    +                        }
    +                        if entry.file_type().is_file() {
    +                            if let Ok(rel) = entry.path().strip_prefix(&search_dir) {
    +                                let path_str = rel.to_string_lossy().to_string();
    +                                collected.push(FileMatch {
    +                                    path: path_str,
    +                                    indices: None, // no highlights for empty query
    +                                });
    +                            }
    +                        }
    +                    }
    +                    #[expect(clippy::unwrap_used)]
    +                    {
    +                        let mut st2 = search_state.lock().unwrap();
    +                        st2.default_file_list = Some(collected.clone());
    +                        // Clear active_search if this empty-query occupied it.
    +                        if let Some(active) = &st2.active_search
    +                            && active.query.is_empty()
    +                            && Arc::ptr_eq(&active.cancellation_token, &cancellation_token)
    +                        {
    +                            st2.active_search = None;
    +                        }
    +                    }
    +                    Some(collected)
    +                }
    +            };
    +            if let Some(matches) = matches_opt {
    +                tx.send(AppEvent::FileSearchResult { query, matches });
    +            }
    +            return;
    +        }
    +
    +        let compute_indices = true;
    +        std::thread::spawn(move || {
                 let matches = file_search::run(
                     &query,
                     MAX_FILE_SEARCH_RESULTS,
                     &search_dir,
                     Vec::new(),
                     NUM_FILE_SEARCH_THREADS,
                     cancellation_token.clone(),
                     compute_indices,
                 )
                 .map(|res| res.matches)
                 .unwrap_or_default();
    @@
                     if let Some(active_search) = &st.active_search
                         && Arc::ptr_eq(&active_search.cancellation_token, &cancellation_token)
                     {
                         st.active_search = None;
                     }
                 }
             });
         }
     }

    codex-rs/tui/src/bottom_pane/chat_composer.rs

    diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs
    @@
    -        if !query.is_empty() {
    -            self.app_event_tx
    -                .send(AppEvent::StartFileSearch(query.clone()));
    -        }
    +        // Always request a search; empty query will yield cached/default file list fast-path.
    +        self.app_event_tx
    +            .send(AppEvent::StartFileSearch(query.clone()));

    Notes:

    • You’ll need walkdir in Cargo.toml for the shallow enumeration if not already present (it’s likely already there; if not, add walkdir = "2").
    • If FileMatch is from codex_file_search and doesn’t have a public constructor or fields, you may need a helper constructor (adjust accordingly).
    • This doesn’t change popup rendering logic: empty query now immediately shows rows, because set_matches will run with query == "" (you currently only apply results if query == pending_query; ensure pending_query for empty query is set by set_query("") instead of set_empty_prompt(). So you should also replace set_empty_prompt() call paths with set_query("") so that pending_query matches. Minimal additional tweak:
      • In sync_file_search_popup replace popup.set_empty_prompt() with popup.set_query("") so empty results can land.

    Optional tiny tweak (not in patch above):
    Replace two occurrences of popup.set_empty_prompt(); with popup.set_query(""); in sync_file_search_popup.

  3. alexx-ftw commented on Aug 29, 2025

    @alexx-ftw

    I can't even get the @ to show up using AltGr+2...

  4. 0xdevalias commented on Sep 3, 2025

    @0xdevalias
    Author
  5. etraut-openai commented on Nov 27, 2025

    @etraut-openai
    Contributor

    Thanks for the feature request. This has received only one upvote in three months, so I'm going to close it.

  6. alexx-ftw commented on Nov 27, 2025

    @alexx-ftw

    @etraut-openai anyway it seems to have been solved in a related PR. Have a good one

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions