Skip to main content

agentmux_srv_core/backend/file_icons/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The system's own icons for the Files pane: the picture the operating
5//! system shows for a file type, served as a PNG the page draws in a row or tile.
6//! docs/specs/SPEC_FILES_SYSTEM_FILE_ICONS_2026_10_27.md.
7//!
8//! Phase 1: Windows, by file type (an extension, or a folder). The shell is asked
9//! in a helper process ([`pool`]) so a misbehaving shell extension can't take srv
10//! down, the answer is kept in memory and on disk ([`cache`]), and only the PNG
11//! leaves ([`crate::server`] `file_icons`). Elsewhere there is no source yet and
12//! the route answers 501, which the page reads as "use the built-in icons".
13
14pub mod assoc;
15#[cfg(windows)]
16pub(crate) use assoc::registry_string;
17pub mod cache;
18pub mod child;
19pub mod pool;
20pub mod request;
21#[cfg(windows)]
22pub mod shell_windows;
23
24use std::collections::HashMap;
25use std::path::PathBuf;
26use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
27use std::sync::{Arc, Mutex, OnceLock};
28
29use request::IconRequest;
30
31/// The argument that turns a re-run of srv into the helper (`srv __file_icons`).
32pub const CHILD_ARG: &str = "__file_icons";
33
34/// Why no picture was made.
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36pub enum IconError {
37    /// This operating system has no source yet.
38    Unsupported,
39    /// The system has no icon for it.
40    NoIcon,
41    /// The helper didn't answer in time and was stopped.
42    Timeout,
43    /// Too many requests are waiting.
44    Busy,
45    /// The helper broke or answered nonsense.
46    Failed,
47}
48
49type Flight = Arc<tokio::sync::OnceCell<Result<Arc<Vec<u8>>, IconError>>>;
50
51struct Service {
52    pool: pool::Pool,
53    mem: Mutex<cache::MemCache>,
54    /// Requests being made now, so a screenful of rows of one type asks the helper once.
55    flights: Mutex<HashMap<String, Flight>>,
56    dir: PathBuf,
57    /// Icons written since the disk cache was last trimmed.
58    written: AtomicUsize,
59    /// A trim is running, so only one at a time.
60    trimming: AtomicBool,
61}
62
63fn service() -> &'static Service {
64    static SERVICE: OnceLock<Service> = OnceLock::new();
65    SERVICE.get_or_init(|| {
66        let dir = crate::backend::base::get_mux_data_dir().join("cache").join("file-icons").join("v1");
67        let prune_dir = dir.clone();
68        std::thread::spawn(move || cache::prune(&prune_dir, cache::DISK_CAP_BYTES));
69        Service {
70            pool: pool::Pool::new(),
71            mem: Mutex::default(),
72            flights: Mutex::default(),
73            dir,
74            written: AtomicUsize::new(0),
75            trimming: AtomicBool::new(false),
76        }
77    })
78}
79
80impl Service {
81    /// Count a file written to the disk cache and, every [`TRIM_EVERY`] of them, trim it to its
82    /// cap on a blocking thread (one trim at a time), so a long session can't outgrow the cap.
83    fn note_written(&'static self) {
84        if self.written.fetch_add(1, Ordering::Relaxed) % TRIM_EVERY != TRIM_EVERY - 1 {
85            return;
86        }
87        if self.trimming.swap(true, Ordering::Acquire) {
88            return;
89        }
90        tokio::task::spawn_blocking(move || {
91            cache::prune(&self.dir, cache::DISK_CAP_BYTES);
92            self.trimming.store(false, Ordering::Release);
93        });
94    }
95}
96
97/// Files written between trims of the disk cache.
98const TRIM_EVERY: usize = 32;
99
100/// The PNG of `req`'s icon: from memory, then disk, then the system.
101pub async fn icon_png(req: &IconRequest) -> Result<Arc<Vec<u8>>, IconError> {
102    if !cfg!(windows) {
103        return Err(IconError::Unsupported);
104    }
105    let svc = service();
106    let assoc = assoc::fingerprint(req);
107    let key = cache::key(req, &assoc);
108    if let Some(hit) = svc.mem.lock().unwrap_or_else(|e| e.into_inner()).get(&key) {
109        return Ok(hit);
110    }
111    let flight = svc.flights.lock().unwrap_or_else(|e| e.into_inner()).entry(key.clone()).or_default().clone();
112    let made = flight
113        .get_or_init(|| async {
114            let path = cache::disk_path(&svc.dir, req, &assoc);
115            let png = match tokio::fs::read(&path).await {
116                Ok(bytes) if !bytes.is_empty() => Arc::new(bytes),
117                _ => {
118                    let png = Arc::new(svc.pool.render(req).await?);
119                    let bytes = png.clone();
120                    tokio::spawn(async move {
121                        if let Some(parent) = path.parent() {
122                            let _ = tokio::fs::create_dir_all(parent).await;
123                        }
124                        let tmp = path.with_extension("tmp");
125                        if tokio::fs::write(&tmp, bytes.as_slice()).await.is_ok() {
126                            let _ = tokio::fs::rename(&tmp, &path).await;
127                            svc.note_written();
128                        }
129                    });
130                    png
131                }
132            };
133            svc.mem.lock().unwrap_or_else(|e| e.into_inner()).put(key.clone(), png.clone(), cache::MEM_CAP_BYTES);
134            Ok(png)
135        })
136        .await
137        .clone();
138    svc.flights.lock().unwrap_or_else(|e| e.into_inner()).remove(&key);
139    made
140}