Skip to main content

vtcode_commons/
prompt_history.rs

1//! Prompt-history ranking shared by the CLI history picker and the desktop
2//! history palette.
3//!
4//! Both surfaces must find the same prompts for the same query, so the match,
5//! rank, dedup, and cap rules live here instead of being reimplemented per UI.
6//! Matching is [`crate::search::FuzzyQuery`] (nucleo) so a multi-word query
7//! such as `impl chg` finds `Implement current changes`; a plain substring
8//! test cannot express that.
9
10use crate::search::FuzzyQuery;
11
12/// Maximum prompt-history rows any surface shows for one query.
13///
14/// The budget covers the **merged** result, not each section: callers that
15/// split rows into sections must size the later ones from what the earlier
16/// ones consumed, or a long live thread plus cross-session recents could
17/// render twice this many rows.
18pub const MAX_PROMPT_HISTORY_ROWS: usize = 200;
19
20/// Indices of `candidates` matching `query`, best match first.
21///
22/// Callers supply candidates **newest first** (live thread first, then
23/// archived prompts). With an empty query every candidate matches with score
24/// zero, so the stable sort preserves that order; with a query, ties also keep
25/// the newer candidate ahead. Blank prompts never match.
26///
27/// After ranking, duplicate content is collapsed to its best-scoring
28/// occurrence (so on a tie the live/newer entry wins), and the result is
29/// capped at `limit`.
30#[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    // Stable: equal scores keep the caller's newest-first order.
52    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/// Compact history row label: `first line · 3h ago · +2 lines`.
72///
73/// Only the first line is shown, so multi-line prompts stay one row and say
74/// how much they hide. Control characters are replaced so an escape sequence
75/// cannot reach the picker's rows.
76#[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    /// Newest-first, live thread before archived prompts.
106    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        // "impl chg" cannot match by substring; fuzzy must span the phrase.
126        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        // Same two prompts, opposite supply order: the ranker must not sort
138        // them alphabetically or by any property other than arrival order.
139        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        // The duplicate lives further down, i.e. it is the *older* copy.
154        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        // The older entry matches the whole query, so it must outrank the
162        // newer partial match; score trumps newest-first for non-empty queries.
163        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}