返回 CodeWhale
file_picker_relevance.rs
根目录 / crates / tui / src / tui / file_picker_relevance.rs
1 //! Helpers that decide which workspace files to surface in the
2 //! `/files` picker.
3 //!
4 //! The picker ranks files by three signals harvested from the running
5 //! session:
6 //!
7 //! * `modified` — files git reports as staged/unstaged or untracked
8 //! * `mentioned` — files the user @-referenced in the composer
9 //! * `tool` — files that recent tool calls touched (input or output)
10 //!
11 //! [`build_relevance`] composes those signals into a
12 //! `FilePickerRelevance` that the picker view uses to order results.
13 //! The remaining helpers are deterministic string/path utilities that
14 //! make path discovery resilient to quoting, leading `./`, and
15 //! trailing `:line` markers.
16
17 use codewhale_dependencies::Git;
18 use std::collections::HashSet;
19 use std::path::{Path, PathBuf};
20
21 use crate::tui::app::App;
22 use crate::tui::app::ToolDetailRecord;
23 use crate::tui::file_picker::FilePickerRelevance;
24 use crate::tui::file_picker::FilePickerView;
25 use codewhale_core::{ContextReferenceKind, ContextReferenceSource};
26
27 /// Push the `/files` picker onto the view stack, pre-populated with
28 /// per-session relevance ranks (modified, @-mentioned, tool-touched).
29 pub(super) fn open_file_picker(app: &mut App) {
30 let relevance = build_relevance(app);
31 // Honor the configured `mention_walk_depth` (0 = unlimited) so the picker
32 // and `@`-mention completion agree, and files in deeply nested trees stay
33 // discoverable (#2488).
34 app.view_stack
35 .push(FilePickerView::new_with_relevance_and_depth(
36 &app.workspace,
37 relevance,
38 app.mention_walk_depth,
39 app.ui_locale,
40 ));
41 }
42
43 /// Compose the in-memory relevance signals (@-mentions, tool-touched paths).
44 ///
45 /// The git-reported `modified` signal is deliberately *not* gathered here: it
46 /// costs a subprocess, so the picker folds it in from its background scan
47 /// (#3905).
48 pub(super) fn build_relevance(app: &App) -> FilePickerRelevance {
49 let mut relevance = FilePickerRelevance::default();
50
51 for record in app.session_context_references.iter().rev().take(64) {
52 let reference = &record.reference;
53 if reference.source != ContextReferenceSource::AtMention {
54 continue;
55 }
56 if !matches!(reference.kind, ContextReferenceKind::File) {
57 continue;
58 }
59 for raw in [&reference.target, &reference.label] {
60 if let Some(path) = workspace_file_candidate(raw, &app.workspace) {
61 relevance.mark_mentioned(path);
62 }
63 }
64 }
65
66 let mut seen_tool_paths = HashSet::new();
67 for detail in app.active_tool_details.values() {
68 mark_tool_detail_paths(detail, &app.workspace, &mut seen_tool_paths, &mut relevance);
69 }
70 let mut rows: Vec<_> = app.tool_details_by_cell.iter().collect();
71 rows.sort_by_key(|(idx, _)| std::cmp::Reverse(**idx));
72 for (_, detail) in rows.into_iter().take(48) {
73 mark_tool_detail_paths(detail, &app.workspace, &mut seen_tool_paths, &mut relevance);
74 }
75
76 relevance
77 }
78
79 /// Paths git reports as staged/unstaged/untracked.
80 ///
81 /// Blocking: spawns `git status` and waits. The picker runs this on a blocking
82 /// task rather than the event loop (#3905), so it lives here but is called
83 /// from `file_picker.rs`.
84 pub(super) fn modified_workspace_paths(workspace: &Path) -> Vec<String> {
85 let Ok(mut cmd) = Git::status_command(workspace) else {
86 return Vec::new();
87 };
88 let Ok(output) = cmd.args(["--short", "--untracked-files=normal"]).output() else {
89 return Vec::new();
90 };
91 if !output.status.success() {
92 return Vec::new();
93 }
94
95 String::from_utf8_lossy(&output.stdout)
96 .lines()
97 .filter_map(parse_git_status_path)
98 .filter_map(|path| workspace_file_candidate(&path, workspace))
99 .collect()
100 }
101
102 pub(super) fn parse_git_status_path(line: &str) -> Option<String> {
103 if line.len() < 4 {
104 return None;
105 }
106 let raw = line.get(3..)?.trim();
107 let raw = raw.rsplit(" -> ").next().unwrap_or(raw).trim();
108 let raw = raw.trim_matches('"');
109 if raw.is_empty() {
110 None
111 } else {
112 Some(raw.to_string())
113 }
114 }
115
116 fn mark_tool_detail_paths(
117 detail: &ToolDetailRecord,
118 workspace: &Path,
119 seen: &mut HashSet<String>,
120 relevance: &mut FilePickerRelevance,
121 ) {
122 let mut budget = 256usize;
123 mark_tool_paths_from_value(&detail.input, workspace, seen, relevance, &mut budget);
124 if let Some(output) = detail
125 .output
126 .as_deref()
127 .filter(|output| output.len() <= 8_192)
128 {
129 mark_tool_paths_from_text(output, workspace, seen, relevance, &mut budget);
130 }
131 }
132
133 fn mark_tool_paths_from_value(
134 value: &serde_json::Value,
135 workspace: &Path,
136 seen: &mut HashSet<String>,
137 relevance: &mut FilePickerRelevance,
138 budget: &mut usize,
139 ) {
140 if *budget == 0 {
141 return;
142 }
143 match value {
144 serde_json::Value::String(text) => {
145 mark_tool_paths_from_text(text, workspace, seen, relevance, budget);
146 }
147 serde_json::Value::Array(items) => {
148 for item in items {
149 mark_tool_paths_from_value(item, workspace, seen, relevance, budget);
150 if *budget == 0 {
151 break;
152 }
153 }
154 }
155 serde_json::Value::Object(map) => {
156 for item in map.values() {
157 mark_tool_paths_from_value(item, workspace, seen, relevance, budget);
158 if *budget == 0 {
159 break;
160 }
161 }
162 }
163 _ => {}
164 }
165 }
166
167 pub(super) fn mark_tool_paths_from_text(
168 text: &str,
169 workspace: &Path,
170 seen: &mut HashSet<String>,
171 relevance: &mut FilePickerRelevance,
172 budget: &mut usize,
173 ) {
174 if *budget == 0 || text.len() > 8_192 {
175 return;
176 }
177 if let Some(path) = workspace_file_candidate(text, workspace)
178 && seen.insert(path.clone())
179 {
180 relevance.mark_tool(path);
181 *budget = (*budget).saturating_sub(1);
182 }
183 for token in text.split_whitespace().take(128) {
184 if *budget == 0 {
185 break;
186 }
187 if let Some(path) = workspace_file_candidate(token, workspace)
188 && seen.insert(path.clone())
189 {
190 relevance.mark_tool(path);
191 *budget = (*budget).saturating_sub(1);
192 }
193 }
194 }
195
196 pub(super) fn workspace_file_candidate(raw: &str, workspace: &Path) -> Option<String> {
197 let cleaned = clean_path_token(raw)?;
198 let path = Path::new(&cleaned);
199 let absolute = if path.is_absolute() {
200 PathBuf::from(path)
201 } else {
202 workspace.join(path)
203 };
204 if !absolute.is_file() {
205 return None;
206 }
207 let rel = absolute.strip_prefix(workspace).ok()?;
208 workspace_path_to_picker_string(rel)
209 }
210
211 fn clean_path_token(raw: &str) -> Option<String> {
212 let mut trimmed = raw.trim().trim_matches(|ch: char| {
213 ch.is_ascii_whitespace()
214 || matches!(
215 ch,
216 '"' | '\'' | '`' | '<' | '>' | '(' | ')' | '[' | ']' | '{' | '}' | ',' | ';'
217 )
218 });
219 if let Some(stripped) = trimmed.strip_prefix("./") {
220 trimmed = stripped;
221 }
222 if let Some((before, after)) = trimmed.rsplit_once(':')
223 && !before.is_empty()
224 && after.chars().all(|ch| ch.is_ascii_digit())
225 {
226 trimmed = before;
227 }
228 if trimmed.is_empty() {
229 None
230 } else {
231 Some(trimmed.to_string())
232 }
233 }
234
235 fn workspace_path_to_picker_string(path: &Path) -> Option<String> {
236 let mut out = String::new();
237 for (idx, component) in path.components().enumerate() {
238 if matches!(
239 component,
240 std::path::Component::ParentDir
241 | std::path::Component::RootDir
242 | std::path::Component::Prefix(_)
243 ) {
244 return None;
245 }
246 if idx > 0 {
247 out.push('/');
248 }
249 out.push_str(&component.as_os_str().to_string_lossy());
250 }
251 if out.is_empty() { None } else { Some(out) }
252 }
253
254 #[cfg(all(test, unix))]
255 mod tests {
256 use super::*;
257 use codewhale_dependencies::ExternalTool;
258 use std::os::unix::fs::PermissionsExt;
259
260 #[test]
261 fn modified_paths_run_no_repository_configured_monitor() {
262 let workspace = tempfile::tempdir().unwrap();
263 let outside = tempfile::tempdir().unwrap();
264 let path = workspace.path();
265 let marker = outside.path().join("marker");
266 let git = |args: &[&str]| {
267 let output = Git::output(args, path).expect("git spawns");
268 assert!(
269 output.status.success(),
270 "{args:?}: {}",
271 String::from_utf8_lossy(&output.stderr)
272 );
273 };
274 git(&["init", "-q"]);
275 git(&["config", "user.name", "Test"]);
276 git(&["config", "user.email", "test@example.com"]);
277 git(&["config", "commit.gpgsign", "false"]);
278 std::fs::write(path.join("a.md"), "original\n").unwrap();
279 git(&["add", "."]);
280 git(&["commit", "-qm", "init"]);
281 let monitor = outside.path().join("fsmonitor.sh");
282 std::fs::write(
283 &monitor,
284 format!(
285 "#!/bin/sh\nprintf touched > '{}'\nexit 1\n",
286 marker.display()
287 ),
288 )
289 .unwrap();
290 std::fs::set_permissions(&monitor, std::fs::Permissions::from_mode(0o700)).unwrap();
291 git(&["config", "core.fsmonitor", monitor.to_str().unwrap()]);
292 std::fs::write(path.join("a.md"), "changed\n").unwrap();
293
294 let control = Git::output(&["status", "--short"], path).expect("status");
295 assert!(control.status.success());
296 assert!(marker.exists(), "positive control: repository monitor");
297 std::fs::remove_file(&marker).unwrap();
298
299 assert_eq!(modified_workspace_paths(path), ["a.md"]);
300 assert!(
301 !marker.exists(),
302 "the file picker ran the repository monitor"
303 );
304 }
305 }
306
306 lines RUST