Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(agent-cli-tui): @path autocomplete popup in TUI input

tikikunf6da7edc4518
diff --git a/src-tauri/src/core/cli/path_refs.rs b/src-tauri/src/core/cli/path_refs.rs
index 4789d0625..86e3317f7 100644
--- a/src-tauri/src/core/cli/path_refs.rs
+++ b/src-tauri/src/core/cli/path_refs.rs
@@ -179,6 +179,67 @@ pub fn resolve_references(text: &str, project_root: &Path) -> (String, String) {
(clean, block)
}
+/// Synchronous file search for path-hint autocomplete.
+///
+/// Searches `root_dir` for files/directories whose path or name contains
+/// `query` (case-insensitive). Returns `(relative_path, basename, is_dir)`
+/// tuples, up to `max_results`. Performs a limited walk (up to 3 levels deep)
+/// so it returns quickly enough for interactive use.
+pub fn search_files_sync(
+ root_dir: &Path,
+ query: &str,
+ max_results: usize,
+) -> Vec<(String, String, bool)> {
+ let mut results = Vec::new();
+ let query_lower = query.to_lowercase();
+
+ // If the query contains slashes, use the last segment as the name filter
+ // and the prefix as the subdirectory to search.
+ let (search_dir, name_filter) = if let Some(last_slash) = query.rfind('/') {
+ let dir_part = &query[..last_slash];
+ let name_part = &query[last_slash + 1..];
+ let subdir = root_dir.join(dir_part);
+ (subdir, name_part.to_lowercase())
+ } else {
+ (root_dir.to_path_buf(), query_lower.clone())
+ };
+
+ // Search the search_dir's immediate children
+ let entries = match std::fs::read_dir(&search_dir) {
+ Ok(d) => d,
+ Err(_) => return results,
+ };
+
+ for entry in entries.flatten() {
+ if results.len() >= max_results {
+ break;
+ }
+ let name = entry.file_name().to_string_lossy().into_owned();
+ let name_lower = name.to_lowercase();
+ if !name_lower.contains(&name_filter) {
+ continue;
+ }
+ let is_dir = entry.file_type().map(|t| t.is_dir()).unwrap_or(false);
+ let full_path = entry.path();
+ let rel = full_path
+ .strip_prefix(root_dir)
+ .unwrap_or(&full_path)
+ .to_string_lossy()
+ .into_owned();
+ results.push((rel, name, is_dir));
+ }
+
+ // Sort: directories first, then by name
+ results.sort_by(|a, b| {
+ b.2.cmp(&a.2).then(a.1.cmp(&b.1))
+ });
+
+ if results.len() > max_results {
+ results.truncate(max_results);
+ }
+ results
+}
+
// ── Internal helpers ─────────────────────────────────────────────────────────
/// Read an image file and return a text note with mime type.
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index a26c622eb..1a06f0d8d 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -253,6 +253,16 @@ struct PendingImage {
data_url: String,
}
+/// One entry in the file-path hint popup triggered by typing `@`.
+struct PathHintItem {
+ /// Display path (relative to project root).
+ path: String,
+ /// Basename for display.
+ name: String,
+ /// Whether this is a directory.
+ is_dir: bool,
+}
+
struct App {
model: String,
/// Fast model for the `smol` role, used by `/goal` evaluation. Defaults to
@@ -332,6 +342,12 @@ struct App {
/// Set by Esc to hide the hint popup without clearing the buffer; cleared on
/// the next keystroke that edits the input so typing re-shows it.
slash_dismissed: bool,
+ /// File-path hint entries matching the current `@query` in the input buffer.
+ path_hints: Vec<PathHintItem>,
+ /// Highlighted row in the path-hint popup (clamped to matches).
+ path_hint_selected: usize,
+ /// Set by Esc to dismiss the path-hint popup; cleared on next char edit.
+ path_hint_dismissed: bool,
status: Status,
turn: (u32, u32),
tokens: u64,
@@ -472,6 +488,9 @@ impl App {
cursor: 0,
slash_selected: 0,
slash_dismissed: false,
+ path_hints: Vec::new(),
+ path_hint_selected: 0,
+ path_hint_dismissed: false,
status: Status::Idle,
turn: (0, 0),
tokens: 0,
@@ -725,12 +744,16 @@ impl App {
self.input.clear();
self.cursor = 0;
self.reset_slash_hint();
+ self.path_hints.clear();
+ self.path_hint_selected = 0;
}
fn input_insert(&mut self, c: char) {
self.input.insert(self.cursor, c);
self.cursor += c.len_utf8();
self.reset_slash_hint();
+ // Refresh path hints on any character edit
+ self.refresh_path_hints();
}
/// Delete the char before the caret (Backspace).
@@ -740,6 +763,7 @@ impl App {
self.input.remove(self.cursor);
}
self.reset_slash_hint();
+ self.refresh_path_hints();
}
/// Delete the char at the caret (Delete); caret stays put.
@@ -748,12 +772,14 @@ impl App {
self.input.remove(self.cursor);
}
self.reset_slash_hint();
+ self.refresh_path_hints();
}
/// Reset hint selection and un-dismiss so an edited buffer re-shows the popup.
fn reset_slash_hint(&mut self) {
self.slash_selected = 0;
self.slash_dismissed = false;
+ self.path_hint_dismissed = false;
}
/// Slash commands whose name prefixes the current buffer, or empty when the
@@ -796,6 +822,92 @@ impl App {
self.slash_selected = 0;
}
+ /// Extract the current `@query` from the input buffer, if any.
+ /// Returns `None` when the cursor is not inside or immediately after
+ /// a `@`-prefixed token (no space since the `@`).
+ fn path_hint_query(&self) -> Option<String> {
+ let before = &self.input[..self.cursor];
+ let at_idx = before.rfind('@')?;
+ let after_at = &before[at_idx + 1..];
+ if after_at.contains(' ') {
+ return None; // space after @ means the token ended
+ }
+ if after_at.is_empty() {
+ return Some(String::new());
+ }
+ Some(after_at.to_string())
+ }
+
+ /// Whether the path-hint popup is eligible to show right now.
+ fn path_hints_active(&self) -> bool {
+ if self.path_hint_dismissed || self.status != Status::Idle {
+ return false;
+ }
+ self.path_hint_query().is_some()
+ }
+
+ /// Refresh path hints from the input buffer: detect `@query`, search files.
+ fn refresh_path_hints(&mut self) {
+ if self.path_hint_dismissed || self.status != Status::Idle {
+ self.path_hints.clear();
+ return;
+ }
+ let Some(query) = self.path_hint_query() else {
+ self.path_hints.clear();
+ return;
+ };
+
+ let entries = path_refs::search_files_sync(&self.project_root, &query, 30);
+ self.path_hints = entries
+ .into_iter()
+ .map(|(path, name, is_dir)| PathHintItem {
+ path,
+ name,
+ is_dir,
+ })
+ .collect();
+ self.path_hint_selected = 0;
+ }
+
+ /// Accept the highlighted path hint: replace the `@query` token with the
+ /// selected path.
+ fn accept_path_hint(&mut self) {
+ if self.path_hints.is_empty() {
+ return;
+ }
+ let sel = self.path_hint_selected.min(self.path_hints.len() - 1);
+ let selected = &self.path_hints[sel];
+ let before = &self.input[..self.cursor];
+ let at_idx = match before.rfind('@') {
+ Some(i) => i,
+ None => return,
+ };
+ let after = &self.input[self.cursor..];
+ let replacement = &selected.path;
+ let new_input = format!("{}{}{}", &self.input[..at_idx], replacement, after);
+ self.input = new_input;
+ self.cursor = at_idx + replacement.len();
+ self.path_hints.clear();
+ self.path_hint_dismissed = false;
+ }
+
+ fn path_hint_move(&mut self, delta: isize) {
+ if self.path_hints.is_empty() {
+ return;
+ }
+ let len = self.path_hints.len();
+ let cur = self.path_hint_selected.min(len - 1) as isize;
+ self.path_hint_selected = (cur + delta).rem_euclid(len as isize) as usize;
+ }
+
+ /// True when the path-hint popup has entries to show.
+ fn has_path_hints(&self) -> bool {
+ if self.path_hint_dismissed || self.status != Status::Idle {
+ return false;
+ }
+ self.path_hint_query().is_some() && !self.path_hints.is_empty()
+ }
+
fn cursor_left(&mut self) {
if let Some(prev) = self.input[..self.cursor].chars().next_back() {
self.cursor -= prev.len_utf8();
@@ -2557,6 +2669,31 @@ async fn handle_key(
}
}
+ // Path-hint popup: while `@query` is active with at least one match,
+ // it owns Up/Down/Tab/Esc/Enter in the same pattern as slash hints.
+ if app.has_path_hints() {
+ match key.code {
+ KeyCode::Up => {
+ app.path_hint_move(-1);
+ return;
+ }
+ KeyCode::Down => {
+ app.path_hint_move(1);
+ return;
+ }
+ KeyCode::Tab | KeyCode::Enter => {
+ app.accept_path_hint();
+ return;
+ }
+ KeyCode::Esc => {
+ app.path_hint_dismissed = true;
+ app.path_hints.clear();
+ return;
+ }
+ _ => {}
+ }
+ }
+
match key.code {
KeyCode::Esc => {
// Esc cancels a run or clears typed input; it never quits (that's
@@ -3792,6 +3929,18 @@ fn draw(f: &mut Frame, app: &mut App) {
height,
};
draw_slash_hints(f, rect, &matches, app.slash_selected);
+ } else if app.has_path_hints() {
+ // Dock the file-path hints above the input box, same layout as
+ // slash hints. Only shows when no slash hints are active.
+ let height = (app.path_hints.len() as u16 + 2).min(chunks[1].height);
+ let y = chunks[2].y.saturating_sub(height).max(chunks[1].y);
+ let rect = ratatui::layout::Rect {
+ x: chunks[2].x,
+ y,
+ width: chunks[2].width,
+ height,
+ };
+ draw_path_hints(f, rect, &app.path_hints, app.path_hint_selected);
}
}
}
@@ -3832,6 +3981,52 @@ fn draw_slash_hints(
f.render_stateful_widget(list, area, &mut state);
}
+/// File-path hint popup docked above the input when typing `@query`.
+/// Shows matching files/directories; arrow keys to navigate, Tab/Enter to
+/// select, Esc to dismiss.
+fn draw_path_hints(
+ f: &mut Frame,
+ area: ratatui::layout::Rect,
+ entries: &[PathHintItem],
+ selected: usize,
+) {
+ use ratatui::widgets::{Clear, List, ListItem, ListState};
+
+ let dim = Style::new().dark_gray();
+ let items: Vec<ListItem> = entries
+ .iter()
+ .map(|e| {
+ let icon = if e.is_dir {
+ Span::styled("", Style::new().yellow())
+ } else {
+ Span::styled("", Style::new().cyan())
+ };
+ let mut spans = vec![
+ icon,
+ Span::raw(" "),
+ Span::styled(&e.name, Style::new().bold()),
+ ];
+ let rel = &e.path;
+ if rel != &e.name {
+ spans.push(Span::styled(format!(" ({rel})"), dim));
+ }
+ ListItem::new(Line::from(spans))
+ })
+ .collect();
+ let block = Block::default()
+ .borders(Borders::ALL)
+ .border_style(Style::new().dark_gray())
+ .title(Span::styled(" path ", dim));
+ f.render_widget(Clear, area);
+ let list = List::new(items)
+ .block(block)
+ .highlight_style(Style::new().reversed())
+ .highlight_symbol("▶ ");
+ let mut state = ListState::default();
+ state.select(Some(selected.min(entries.len().saturating_sub(1))));
+ f.render_stateful_widget(list, area, &mut state);
+}
+
/// Permission prompt docked above the input: names the tool, capability, and
/// target path, then an arrow-navigable option list (Enter confirms the
/// highlighted choice; `y`/`a`/`n` still work as shortcuts).