Skip to main content

agentmux_srv_core/backend/file_icons/
cache.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Where finished icons are kept: a byte-bounded memory LRU, and a small disk
5//! cache so a restart doesn't ask the shell again (spec ยง4.4). A type icon's
6//! file name carries a hash of the file associations behind it, so changing a
7//! default app makes a new file instead of needing a notification.
8
9use std::collections::HashMap;
10use std::path::{Path, PathBuf};
11use std::sync::Arc;
12
13use super::request::IconRequest;
14
15/// Memory kept for encoded icons.
16pub const MEM_CAP_BYTES: usize = 32 * 1024 * 1024;
17/// Disk kept for type icons (a few hundred small files).
18pub const DISK_CAP_BYTES: u64 = 20 * 1024 * 1024;
19
20/// Encoded PNGs by key, least recently used out first once over the cap.
21#[derive(Default)]
22pub struct MemCache {
23    entries: HashMap<String, (Arc<Vec<u8>>, u64)>,
24    bytes: usize,
25    tick: u64,
26}
27
28impl MemCache {
29    pub fn get(&mut self, key: &str) -> Option<Arc<Vec<u8>>> {
30        self.tick += 1;
31        let tick = self.tick;
32        self.entries.get_mut(key).map(|(v, t)| {
33            *t = tick;
34            v.clone()
35        })
36    }
37
38    pub fn put(&mut self, key: String, value: Arc<Vec<u8>>, cap: usize) {
39        self.tick += 1;
40        self.bytes += value.len();
41        if let Some((old, _)) = self.entries.insert(key, (value, self.tick)) {
42            self.bytes -= old.len();
43        }
44        while self.bytes > cap && self.entries.len() > 1 {
45            let Some(oldest) = self.entries.iter().min_by_key(|(_, (_, t))| *t).map(|(k, _)| k.clone()) else { break };
46            if let Some((v, _)) = self.entries.remove(&oldest) {
47                self.bytes -= v.len();
48            }
49        }
50    }
51
52    #[cfg(test)]
53    pub fn len(&self) -> usize {
54        self.entries.len()
55    }
56}
57
58/// The key a finished icon is kept under (memory and, hashed into the file name, disk).
59pub fn key(req: &IconRequest, assoc: &str) -> String {
60    format!("{}|{}|{}|{}", req.kind.as_str(), req.ext, req.px, assoc)
61}
62
63/// FNV-1a over the bytes: the same answer on every toolchain, since it names files that outlive a build.
64pub fn stable_hash(s: &str) -> String {
65    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
66    for b in s.as_bytes() {
67        h ^= u64::from(*b);
68        h = h.wrapping_mul(0x0100_0000_01b3);
69    }
70    format!("{h:016x}")
71}
72
73/// `<root>/ext/<px>/<kind>-<ext>.<assoc>.png`. The extension is validated to
74/// `[a-z0-9_+-]` and the kind prefix keeps a name like `con` from being a
75/// reserved device name on Windows.
76pub fn disk_path(root: &Path, req: &IconRequest, assoc: &str) -> PathBuf {
77    root.join("ext").join(req.px.to_string()).join(format!("{}-{}.{}.png", req.kind.as_str(), req.ext, stable_hash(assoc)))
78}
79
80/// Delete the oldest files under `root` until what is left is at most `cap` bytes.
81pub fn prune(root: &Path, cap: u64) {
82    let mut files: Vec<(std::time::SystemTime, u64, PathBuf)> = Vec::new();
83    let mut stack = vec![root.to_path_buf()];
84    while let Some(dir) = stack.pop() {
85        let Ok(rd) = std::fs::read_dir(&dir) else { continue };
86        for entry in rd.flatten() {
87            let Ok(meta) = entry.metadata() else { continue };
88            if meta.is_dir() {
89                stack.push(entry.path());
90            } else {
91                files.push((meta.modified().unwrap_or(std::time::UNIX_EPOCH), meta.len(), entry.path()));
92            }
93        }
94    }
95    let mut total: u64 = files.iter().map(|f| f.1).sum();
96    files.sort();
97    for (_, len, path) in files {
98        if total <= cap {
99            break;
100        }
101        if std::fs::remove_file(&path).is_ok() {
102            total -= len;
103        }
104    }
105}
106
107#[cfg(test)]
108mod tests {
109    use super::super::request::Kind;
110    use super::*;
111
112    fn req(ext: &str, px: u32) -> IconRequest {
113        IconRequest { kind: Kind::File, ext: ext.to_string(), px }
114    }
115
116    #[test]
117    fn the_least_recently_used_icon_leaves_first_and_a_read_counts_as_use() {
118        let mut c = MemCache::default();
119        let png = |n: usize| Arc::new(vec![0u8; n]);
120        c.put("a".into(), png(40), 100);
121        c.put("b".into(), png(40), 100);
122        assert!(c.get("a").is_some(), "touch a, so b is now the oldest");
123        c.put("c".into(), png(40), 100);
124        assert!(c.get("b").is_none(), "b was evicted");
125        assert!(c.get("a").is_some() && c.get("c").is_some());
126        assert_eq!(c.len(), 2);
127    }
128
129    #[test]
130    fn replacing_an_entry_does_not_count_its_bytes_twice() {
131        let mut c = MemCache::default();
132        c.put("a".into(), Arc::new(vec![0; 60]), 100);
133        c.put("a".into(), Arc::new(vec![0; 60]), 100);
134        c.put("b".into(), Arc::new(vec![0; 30]), 100);
135        assert_eq!(c.len(), 2, "60 + 30 fits in 100: nothing was evicted");
136    }
137
138    #[test]
139    fn the_hash_is_stable_and_the_disk_name_changes_with_the_association() {
140        assert_eq!(stable_hash(""), "cbf29ce484222325");
141        assert_eq!(stable_hash("a"), "af63dc4c8601ec8c");
142        let root = Path::new("cache");
143        let a = disk_path(root, &req("rs", 16), "ProgA|icon1");
144        let b = disk_path(root, &req("rs", 16), "ProgB|icon1");
145        assert_ne!(a, b, "a new default app is a new file");
146        assert_eq!(a, disk_path(root, &req("rs", 16), "ProgA|icon1"));
147        assert!(a.ends_with(format!("file-rs.{}.png", stable_hash("ProgA|icon1"))));
148        assert!(disk_path(root, &req("con", 16), "x").file_name().unwrap().to_string_lossy().starts_with("file-con."));
149    }
150
151    #[test]
152    fn prune_removes_the_oldest_until_under_the_cap() {
153        let dir = std::env::temp_dir().join(format!("agentmux-icons-prune-{}", std::process::id()));
154        let _ = std::fs::remove_dir_all(&dir);
155        std::fs::create_dir_all(dir.join("ext").join("16")).unwrap();
156        for (i, name) in ["old", "mid", "new"].iter().enumerate() {
157            let p = dir.join("ext").join("16").join(name);
158            std::fs::write(&p, vec![0u8; 100]).unwrap();
159            let when = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_000_000 + i as u64);
160            std::fs::File::options().write(true).open(&p).unwrap().set_modified(when).unwrap();
161        }
162        prune(&dir, 250);
163        let left: Vec<String> = std::fs::read_dir(dir.join("ext").join("16"))
164            .unwrap()
165            .flatten()
166            .map(|e| e.file_name().to_string_lossy().into_owned())
167            .collect();
168        assert!(!left.contains(&"old".to_string()), "the oldest went: {left:?}");
169        assert_eq!(left.len(), 2);
170        let _ = std::fs::remove_dir_all(&dir);
171    }
172}