Skip to main content

jump_core/
frecency.rs

1// Copyright 2026 entro314-labs
2// SPDX-License-Identifier: MPL-2.0
3
4//! Usage-weighted re-ranking.
5//!
6//! pop-launcher sorts by match quality alone, so the app you launch twenty
7//! times a day sits below a closer string match you have never opened. This
8//! module records activations and boosts results accordingly.
9//!
10//! The scoring is Mozilla's frecency shape: a visit count weighted by how
11//! recently each visit happened, so a burst of use decays rather than pinning an
12//! entry to the top forever. Bucketed decay is used instead of a continuous
13//! exponential because it is stable — a result does not drift down the list
14//! while the user is looking at it.
15
16use std::collections::HashMap;
17use std::path::PathBuf;
18use std::time::{Duration, SystemTime, UNIX_EPOCH};
19
20use serde::{Deserialize, Serialize};
21
22use crate::model::{Item, ItemKey};
23
24/// How much a maximally-used entry may add to its match quality.
25///
26/// Base scores from [`crate::rank`] are normalised into 0.0..=1.0, so half a
27/// point lets usage reorder results of *similar* quality — the app you open
28/// daily rises above one you never touch — without letting a favourite outrank
29/// something that matched the query far better.
30const MAX_BOOST: f32 = 0.5;
31
32/// Visits older than this contribute nothing.
33const MAX_AGE_DAYS: f64 = 90.0;
34
35#[derive(Debug, Clone, Default, Serialize, Deserialize)]
36struct Entry {
37    /// Number of times this entry was activated.
38    count: u32,
39    /// Unix timestamp, seconds, of the most recent activation.
40    last_used: u64,
41}
42
43impl Entry {
44    /// Weight in 0.0..=1.0 from recency alone.
45    fn recency_weight(&self, now: u64) -> f32 {
46        let age_days = (now.saturating_sub(self.last_used) as f64) / 86_400.0;
47        // Mozilla-style buckets: same day, this week, this month, this quarter.
48        let weight = if age_days < 1.0 {
49            1.0
50        } else if age_days < 7.0 {
51            0.7
52        } else if age_days < 30.0 {
53            0.4
54        } else if age_days < MAX_AGE_DAYS {
55            0.2
56        } else {
57            0.0
58        };
59        weight as f32
60    }
61
62    fn score(&self, now: u64) -> f32 {
63        // Saturating log growth: the difference between 1 and 5 launches should
64        // matter far more than between 200 and 400.
65        let volume = (f64::from(self.count) + 1.0).ln() as f32;
66        volume * self.recency_weight(now)
67    }
68}
69
70/// One key's usage history, rendered for a person rather than for the
71/// ranker. See [`Frecency::explain`].
72#[derive(Debug, Clone, PartialEq)]
73pub struct Usage {
74    /// Times this entry has been activated.
75    pub count: u32,
76    /// How long ago the most recent activation was.
77    pub age: Duration,
78    /// What that age is currently worth, in `0.0..=1.0`. The bucket edges
79    /// are why this moves in steps rather than smoothly.
80    pub recency_weight: f32,
81    /// Volume times recency — the raw number the boost is derived from,
82    /// before it is normalised against the rest of the visible list.
83    pub score: f32,
84}
85
86/// Persistent activation history.
87#[derive(Debug, Default)]
88pub struct Frecency {
89    entries: HashMap<ItemKey, Entry>,
90    path: Option<PathBuf>,
91    /// Set when `entries` has changed since the last successful save.
92    dirty: bool,
93}
94
95impl Frecency {
96    /// Load history from the user's data directory, or start empty when the
97    /// file is missing or unreadable. A corrupt history is never fatal — the
98    /// launcher must still open.
99    #[must_use]
100    pub fn load() -> Self {
101        let Some(path) = Self::default_path() else {
102            tracing::warn!("no data directory; frecency will not persist");
103            return Self::default();
104        };
105
106        let entries = match std::fs::read_to_string(&path) {
107            Ok(contents) => serde_json::from_str(&contents).unwrap_or_else(|error| {
108                tracing::warn!(%error, ?path, "discarding unreadable frecency history");
109                HashMap::new()
110            }),
111            Err(error) if error.kind() == std::io::ErrorKind::NotFound => HashMap::new(),
112            Err(error) => {
113                tracing::warn!(%error, ?path, "failed to read frecency history");
114                HashMap::new()
115            }
116        };
117
118        Self {
119            entries,
120            path: Some(path),
121            dirty: false,
122        }
123    }
124
125    fn default_path() -> Option<PathBuf> {
126        dirs::data_dir().map(|dir| dir.join("jump").join("frecency.json"))
127    }
128
129    /// Whether nothing has ever been activated.
130    ///
131    /// The launcher uses this as its "first run" signal. It is a better one
132    /// than a stored flag: a flag has to be set by something and can drift
133    /// out of step with reality, whereas this is simply true until the user
134    /// has used the launcher once, and false forever after.
135    #[must_use]
136    pub fn is_empty(&self) -> bool {
137        self.entries.is_empty()
138    }
139
140    /// What this key's usage history is, for explaining a ranking.
141    ///
142    /// Returns the number of activations, how long ago the last one was, and
143    /// the recency weight that age currently earns. `None` when the key has
144    /// never been activated, which is itself the answer to "why is this not
145    /// higher up".
146    #[must_use]
147    pub fn explain(&self, key: &ItemKey) -> Option<Usage> {
148        let now = now_secs();
149        self.entries.get(key).map(|usage| Usage {
150            count: usage.count,
151            age: Duration::from_secs(now.saturating_sub(usage.last_used)),
152            recency_weight: usage.recency_weight(now),
153            score: usage.score(now),
154        })
155    }
156
157    /// Record an activation.
158    pub fn record(&mut self, key: &ItemKey) {
159        let entry = self.entries.entry(key.clone()).or_default();
160        entry.count = entry.count.saturating_add(1);
161        entry.last_used = now_secs();
162        self.dirty = true;
163    }
164
165    /// Add a usage boost to each item's existing score.
166    ///
167    /// Deliberately additive rather than authoritative: match quality is
168    /// computed by [`crate::rank`] and this only nudges the order. An earlier
169    /// version *set* the score from list position, which silently discarded the
170    /// file-search ranking and pushed good results off the panel.
171    pub fn boost(&self, items: &mut [Item]) {
172        if items.is_empty() {
173            return;
174        }
175
176        let now = now_secs();
177
178        // Normalise against the usage present in *this* result set, so the
179        // boost is relative to the candidates on screen rather than to the
180        // user's most-used application overall.
181        let max_usage = items
182            .iter()
183            .filter_map(|item| self.entries.get(&item.key))
184            .map(|usage| usage.score(now))
185            .fold(0.0_f32, f32::max);
186
187        if max_usage <= 0.0 {
188            return;
189        }
190
191        for item in items.iter_mut() {
192            item.score += self
193                .entries
194                .get(&item.key)
195                .map_or(0.0, |usage| usage.score(now) / max_usage)
196                * MAX_BOOST;
197        }
198    }
199
200    /// Persist history if it changed. Cheap to call on dismiss.
201    pub fn save(&mut self) {
202        if !self.dirty {
203            return;
204        }
205        let Some(path) = self.path.as_ref() else {
206            return;
207        };
208
209        if let Some(parent) = path.parent()
210            && let Err(error) = std::fs::create_dir_all(parent)
211        {
212            tracing::warn!(%error, ?parent, "failed to create data directory");
213            return;
214        }
215
216        let Ok(contents) = serde_json::to_string(&self.entries) else {
217            return;
218        };
219
220        // Write-then-rename so a crash mid-write cannot truncate the history.
221        let temporary = path.with_extension("json.tmp");
222        if let Err(error) = std::fs::write(&temporary, contents) {
223            tracing::warn!(%error, ?temporary, "failed to write frecency history");
224            return;
225        }
226        if let Err(error) = std::fs::rename(&temporary, path) {
227            tracing::warn!(%error, ?path, "failed to replace frecency history");
228            return;
229        }
230
231        self.dirty = false;
232    }
233}
234
235fn now_secs() -> u64 {
236    SystemTime::now()
237        .duration_since(UNIX_EPOCH)
238        .map_or(0, |duration| duration.as_secs())
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244    use crate::model::Source;
245
246    fn item(name: &str) -> Item {
247        Item {
248            key: ItemKey(format!("entry:{name}")),
249            id: 0,
250            title: name.to_owned(),
251            subtitle: String::new(),
252            icon: None,
253            category_icon: None,
254            window: None,
255            source: Source::Launcher,
256            autocomplete: None,
257            score: 0.0,
258        }
259    }
260
261    #[test]
262    fn usage_breaks_ties_between_equal_matches() {
263        let mut frecency = Frecency::default();
264        frecency.record(&ItemKey("entry:Firefox".to_owned()));
265        frecency.record(&ItemKey("entry:Firefox".to_owned()));
266
267        // Both matched the query equally well.
268        let mut items = vec![item("Files"), item("Firefox")];
269        for entry in &mut items {
270            entry.score = 0.6;
271        }
272        frecency.boost(&mut items);
273
274        assert!(
275            items[1].score > items[0].score,
276            "the used entry gains a boost"
277        );
278    }
279
280    #[test]
281    fn usage_cannot_override_a_clearly_better_match() {
282        let mut frecency = Frecency::default();
283        for _ in 0..50 {
284            frecency.record(&ItemKey("entry:Firefox".to_owned()));
285        }
286
287        let mut items = vec![item("Files"), item("Firefox")];
288        // "Files" matched the query exactly; "Firefox" barely matched.
289        items[0].score = 1.0;
290        items[1].score = 0.15;
291        frecency.boost(&mut items);
292
293        assert!(items[0].score > items[1].score);
294    }
295
296    #[test]
297    fn scores_are_untouched_without_history() {
298        let frecency = Frecency::default();
299        let mut items = vec![item("Files"), item("Firefox")];
300        items[0].score = 0.7;
301        items[1].score = 0.3;
302        frecency.boost(&mut items);
303
304        assert!((items[0].score - 0.7).abs() < f32::EPSILON);
305        assert!((items[1].score - 0.3).abs() < f32::EPSILON);
306    }
307
308    #[test]
309    fn stale_usage_stops_contributing() {
310        let usage = Entry {
311            count: 100,
312            last_used: 0,
313        };
314        // Epoch timestamps are far past MAX_AGE_DAYS, so the weight is zero.
315        assert_eq!(usage.score(now_secs()), 0.0);
316    }
317}