vtcode_commons/
prompt_history.rs1use crate::search::FuzzyQuery;
11
12pub const MAX_PROMPT_HISTORY_ROWS: usize = 200;
19
20#[must_use]
31pub fn rank_prompt_history(query: &str, candidates: &[&str], limit: usize) -> Vec<usize> {
32 if limit == 0 {
33 return Vec::new();
34 }
35 let query = query.trim();
36 let mut fuzzy = (!query.is_empty()).then(|| FuzzyQuery::new(query));
37 let mut scored = Vec::with_capacity(candidates.len());
38 for (index, candidate) in candidates.iter().enumerate() {
39 if candidate.trim().is_empty() {
40 continue;
41 }
42 let score = match fuzzy.as_mut() {
43 Some(fuzzy) => match fuzzy.score(candidate) {
44 Some(score) => score,
45 None => continue,
46 },
47 None => 0,
48 };
49 scored.push((index, score));
50 }
51 scored.sort_by_key(|&(_, score)| std::cmp::Reverse(score));
53
54 let mut seen = hashbrown::HashSet::with_capacity(scored.len());
55 let mut ranked = Vec::with_capacity(scored.len().min(limit));
56 for (index, _) in scored {
57 let Some(content) = candidates.get(index) else {
58 continue;
59 };
60 if !seen.insert(*content) {
61 continue;
62 }
63 ranked.push(index);
64 if ranked.len() == limit {
65 break;
66 }
67 }
68 ranked
69}
70
71#[must_use]
77pub fn prompt_history_row_label(content: &str, time_label: &str) -> String {
78 let mut lines = content.lines();
79 let first = lines.next().unwrap_or("");
80 let extra_lines = lines.count();
81 let sanitized: String = first.chars().map(|ch| if ch.is_control() { ' ' } else { ch }).collect();
82 let first = if sanitized.is_empty() && extra_lines > 0 {
83 "…"
84 } else {
85 sanitized.as_str()
86 };
87 let mut parts = vec![first.to_owned()];
88 if !time_label.is_empty() {
89 parts.push(time_label.to_owned());
90 }
91 if extra_lines > 0 {
92 if extra_lines == 1 {
93 parts.push("+1 line".to_owned());
94 } else {
95 parts.push(format!("+{extra_lines} lines"));
96 }
97 }
98 parts.join(" \u{b7} ")
99}
100
101#[cfg(test)]
102mod tests {
103 use super::*;
104
105 fn candidates<'a>() -> Vec<&'a str> {
107 vec![
108 "Implement current changes",
109 "Review stale diffs",
110 "git status",
111 "git diff",
112 ]
113 }
114
115 fn ranked_contents(query: &str, limit: usize) -> Vec<String> {
116 let candidates = candidates();
117 rank_prompt_history(query, &candidates, limit)
118 .into_iter()
119 .map(|index| candidates[index].to_owned())
120 .collect()
121 }
122
123 #[test]
124 fn multi_word_query_matches_non_contiguous_text() {
125 assert_eq!(ranked_contents("impl chg", MAX_PROMPT_HISTORY_ROWS), vec!["Implement current changes"]);
127 assert_eq!(ranked_contents("stff", MAX_PROMPT_HISTORY_ROWS), vec!["Review stale diffs"]);
128 }
129
130 #[test]
131 fn empty_query_preserves_newest_first_order() {
132 assert_eq!(ranked_contents(" ", MAX_PROMPT_HISTORY_ROWS), candidates());
133 }
134
135 #[test]
136 fn empty_query_order_is_asymmetric() {
137 let newest_first = ["newer prompt", "older prompt"];
140 let oldest_first = ["older prompt", "newer prompt"];
141 assert_eq!(rank_prompt_history("", &newest_first, MAX_PROMPT_HISTORY_ROWS), vec![0, 1]);
142 assert_eq!(rank_prompt_history("", &oldest_first, MAX_PROMPT_HISTORY_ROWS), vec![0, 1]);
143 }
144
145 #[test]
146 fn blank_and_whitespace_prompts_never_match() {
147 let candidates = ["", " ", "real prompt"];
148 assert_eq!(rank_prompt_history("", &candidates, MAX_PROMPT_HISTORY_ROWS), vec![2]);
149 }
150
151 #[test]
152 fn duplicate_content_collapses_to_newest_occurrence() {
153 let candidates = ["cargo test", "unrelated", "cargo test"];
155 let ranked = rank_prompt_history("", &candidates, MAX_PROMPT_HISTORY_ROWS);
156 assert_eq!(ranked, vec![0, 1], "dedup keeps the first (newest) copy");
157 }
158
159 #[test]
160 fn query_ranking_beats_arrival_order() {
161 let candidates = ["git", "git status"];
164 let ranked = rank_prompt_history("git status", &candidates, MAX_PROMPT_HISTORY_ROWS);
165 assert_eq!(ranked.first().copied().map(|index| candidates[index]), Some("git status"));
166 }
167
168 #[test]
169 fn cap_applies_to_the_merged_result() {
170 let owned: Vec<String> = (0..250).map(|index| format!("prompt {index:03}")).collect();
171 let candidates: Vec<&str> = owned.iter().map(String::as_str).collect();
172 assert_eq!(rank_prompt_history("", &candidates, MAX_PROMPT_HISTORY_ROWS).len(), MAX_PROMPT_HISTORY_ROWS);
173 assert_eq!(rank_prompt_history("", &candidates, 0).len(), 0);
174 }
175
176 #[test]
177 fn no_match_yields_no_rows() {
178 assert!(ranked_contents("zzzznomatch", MAX_PROMPT_HISTORY_ROWS).is_empty());
179 }
180
181 #[test]
182 fn row_label_reports_hidden_lines() {
183 assert_eq!(prompt_history_row_label("cargo test", "3h ago"), "cargo test \u{b7} 3h ago");
184 assert_eq!(prompt_history_row_label("cargo test", ""), "cargo test");
185 assert_eq!(prompt_history_row_label("one\ntwo", "just now"), "one \u{b7} just now \u{b7} +1 line");
186 assert_eq!(prompt_history_row_label("one\ntwo\nthree", ""), "one \u{b7} +2 lines");
187 }
188
189 #[test]
190 fn row_label_sanitizes_control_characters() {
191 let label = prompt_history_row_label("safe\u{1b}[31mevil", "");
192 assert!(!label.contains('\u{1b}'), "escape must not survive: {label:?}");
193 assert!(label.starts_with("safe [31mevil"));
194 }
195
196 #[test]
197 fn row_label_uses_ellipsis_for_continuation_only_prompts() {
198 assert_eq!(prompt_history_row_label("\nsecond line", ""), "… \u{b7} +1 line");
199 }
200}