Skip to main content

agentmux_srv_core/backend/file_icons/
pool.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The helper processes that call the operating system, and the way srv talks to them.
5//!
6//! The shell loads third-party code (icon handlers, codecs, cloud providers), so
7//! none of it runs in srv: srv re-runs its own executable as a small helper
8//! ([`super::CHILD_ARG`]), sends it one request at a time over its pipes and
9//! kills it when it doesn't answer in time (spec ยง4.2). The helper dies with
10//! srv: its stdin closes.
11//!
12//! Protocol, one request in flight per helper. Request: one JSON line,
13//! `{"kind":"file","ext":"rs","px":16}`. Answer: one JSON line, either
14//! `{"ok":true,"len":N}` followed by N bytes of PNG, or `{"ok":false,"err":"..."}`.
15
16use std::sync::atomic::{AtomicUsize, Ordering};
17use std::sync::Arc;
18use std::time::Duration;
19
20use serde::{Deserialize, Serialize};
21use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader};
22use tokio::process::Child;
23
24use super::request::IconRequest;
25use super::IconError;
26
27/// How long one request may take before its helper is killed.
28pub const DEADLINE: Duration = Duration::from_secs(3);
29/// Helpers kept: one slow icon shouldn't hold up every other.
30pub const WORKERS: usize = 2;
31/// Requests allowed to wait for a helper before the rest are refused.
32pub const QUEUE_MAX: usize = 64;
33/// The most a picture may weigh. A 256 px RGBA PNG is far smaller.
34pub const MAX_PNG_BYTES: usize = 1024 * 1024;
35/// The longest answer line read.
36const MAX_LINE: usize = 512;
37
38#[derive(Serialize)]
39pub struct WireRequest<'a> {
40    pub kind: &'a str,
41    pub ext: &'a str,
42    pub px: u32,
43}
44
45#[derive(Deserialize)]
46pub struct WireAnswer {
47    pub ok: bool,
48    #[serde(default)]
49    pub len: usize,
50    #[serde(default)]
51    pub err: String,
52}
53
54/// What the helper says when it has no icon for a request.
55pub const ERR_NO_ICON: &str = "no-icon";
56
57/// Send `req` and read the answer. A helper-reported error leaves the helper usable.
58pub async fn exchange<W, R>(to: &mut W, from: &mut R, req: &IconRequest) -> Result<Vec<u8>, IconError>
59where
60    W: AsyncWrite + Unpin,
61    R: AsyncRead + AsyncBufRead + Unpin,
62{
63    let mut line = serde_json::to_vec(&WireRequest { kind: req.kind.as_str(), ext: &req.ext, px: req.px })
64        .map_err(|_| IconError::Failed)?;
65    line.push(b'\n');
66    to.write_all(&line).await.map_err(|_| IconError::Failed)?;
67    to.flush().await.map_err(|_| IconError::Failed)?;
68
69    let mut answer = String::new();
70    let n = from.take(MAX_LINE as u64).read_line(&mut answer).await.map_err(|_| IconError::Failed)?;
71    if n == 0 || !answer.ends_with('\n') {
72        return Err(IconError::Failed);
73    }
74    let answer: WireAnswer = serde_json::from_str(answer.trim_end()).map_err(|_| IconError::Failed)?;
75    if !answer.ok {
76        return Err(if answer.err == ERR_NO_ICON { IconError::NoIcon } else { IconError::Failed });
77    }
78    if answer.len == 0 || answer.len > MAX_PNG_BYTES {
79        return Err(IconError::Failed);
80    }
81    let mut png = vec![0u8; answer.len];
82    from.read_exact(&mut png).await.map_err(|_| IconError::Failed)?;
83    Ok(png)
84}
85
86/// `exchange` that gives up after `deadline`.
87pub async fn exchange_within<W, R>(
88    to: &mut W,
89    from: &mut R,
90    req: &IconRequest,
91    deadline: Duration,
92) -> Result<Vec<u8>, IconError>
93where
94    W: AsyncWrite + Unpin,
95    R: AsyncRead + AsyncBufRead + Unpin,
96{
97    tokio::time::timeout(deadline, exchange(to, from, req)).await.unwrap_or(Err(IconError::Timeout))
98}
99
100type Writer = Box<dyn AsyncWrite + Send + Unpin>;
101type Reader = BufReader<Box<dyn AsyncRead + Send + Unpin>>;
102
103/// One helper process and its pipes.
104struct Worker {
105    /// `None` for a stand-in in tests.
106    child: Option<Child>,
107    stdin: Writer,
108    stdout: Reader,
109}
110
111impl Worker {
112    fn spawn() -> std::io::Result<Self> {
113        let exe = std::env::current_exe()?;
114        let mut std_cmd = std::process::Command::new(exe);
115        // It only asks the shell about file types: none of this instance's identity goes with it.
116        crate::backend::pane_env::sanitize_external_std_command(&mut std_cmd);
117        std_cmd.arg(super::CHILD_ARG);
118        let mut cmd = tokio::process::Command::from(std_cmd);
119        {
120            use agentmux_common::win32::NoWindow;
121            cmd.no_window();
122        }
123        cmd.stdin(std::process::Stdio::piped())
124            .stdout(std::process::Stdio::piped())
125            .stderr(std::process::Stdio::null())
126            .kill_on_drop(true);
127        let mut child = cmd.spawn()?;
128        let stdin = child.stdin.take().ok_or_else(|| std::io::Error::other("no stdin"))?;
129        let stdout = child.stdout.take().ok_or_else(|| std::io::Error::other("no stdout"))?;
130        let stdout: Box<dyn AsyncRead + Send + Unpin> = Box::new(stdout);
131        Ok(Worker { child: Some(child), stdin: Box::new(stdin), stdout: BufReader::new(stdout) })
132    }
133}
134
135type Slot = Arc<tokio::sync::Mutex<Option<Worker>>>;
136
137/// The helpers and the line of requests waiting for one.
138pub struct Pool {
139    slots: Vec<Slot>,
140    waiting: Arc<tokio::sync::Semaphore>,
141    next: AtomicUsize,
142    /// Starts a helper when a slot has none (a test swaps it).
143    start: fn() -> std::io::Result<Worker>,
144}
145
146impl Pool {
147    pub fn new() -> Self {
148        Self::with_slots((0..WORKERS).map(|_| None).collect(), Worker::spawn)
149    }
150
151    fn with_slots(workers: Vec<Option<Worker>>, start: fn() -> std::io::Result<Worker>) -> Self {
152        Pool {
153            slots: workers.into_iter().map(|w| Arc::new(tokio::sync::Mutex::new(w))).collect(),
154            waiting: Arc::new(tokio::sync::Semaphore::new(QUEUE_MAX)),
155            next: AtomicUsize::new(0),
156            start,
157        }
158    }
159
160    /// Ask a helper for `req`'s picture. A helper that doesn't answer in [`DEADLINE`]
161    /// is killed, the next request starts a new one, and this one is a timeout.
162    ///
163    /// The exchange runs in its own task, not in the caller's future: a page that
164    /// scrolls on aborts its request, which drops the HTTP handler, and a helper
165    /// dropped mid-exchange would keep its answer unread in the pipe and give the
166    /// next request the previous one's picture. The task finishes the exchange and
167    /// frees the slot whether or not anyone is still waiting for the result.
168    pub async fn render(&self, req: &IconRequest) -> Result<Vec<u8>, IconError> {
169        let place = self.waiting.clone().try_acquire_owned().map_err(|_| IconError::Busy)?;
170        let free = self.slots.iter().find_map(|s| s.clone().try_lock_owned().ok());
171        let queued = self.slots[self.next.fetch_add(1, Ordering::Relaxed) % self.slots.len()].clone();
172        let (req, start) = (req.clone(), self.start);
173        tokio::spawn(async move {
174            let _place = place;
175            let mut slot = match free {
176                Some(g) => g,
177                None => queued.lock_owned().await,
178            };
179            if slot.is_none() {
180                *slot = Some(start().map_err(|e| {
181                    tracing::warn!(error = %e, "file icons: could not start the helper");
182                    IconError::Failed
183                })?);
184            }
185            let worker = slot.as_mut().expect("just started");
186            match exchange_within(&mut worker.stdin, &mut worker.stdout, &req, DEADLINE).await {
187                Ok(png) => Ok(png),
188                Err(e @ IconError::NoIcon) => Err(e),
189                Err(e) => {
190                    // Timed out or broke mid-answer: its pipes may hold half an answer, so it goes.
191                    if let Some(mut dead) = slot.take() {
192                        if let Some(mut child) = dead.child.take() {
193                            let _ = child.start_kill();
194                            tokio::spawn(async move {
195                                let _ = child.wait().await;
196                            });
197                        }
198                    }
199                    if e == IconError::Timeout {
200                        tracing::warn!(kind = req.kind.as_str(), ext = %req.ext, "file icons: the helper did not answer in time and was stopped");
201                    }
202                    Err(e)
203                }
204            }
205        })
206        .await
207        .unwrap_or(Err(IconError::Failed))
208    }
209}
210
211#[cfg(test)]
212mod tests {
213    use super::super::request::Kind;
214    use super::*;
215    use tokio::io::{duplex, AsyncBufReadExt, AsyncWriteExt};
216
217    fn req() -> IconRequest {
218        IconRequest { kind: Kind::File, ext: "rs".into(), px: 16 }
219    }
220
221    /// Run `peer` as the helper's end of a pair of pipes and `exchange_within` as srv's.
222    async fn run<F, Fut>(deadline: Duration, peer: F) -> Result<Vec<u8>, IconError>
223    where
224        F: FnOnce(String, tokio::io::DuplexStream) -> Fut + Send + 'static,
225        Fut: std::future::Future<Output = ()> + Send + 'static,
226    {
227        let (mut srv_w, helper_r) = duplex(4096);
228        let (helper_w, srv_r) = duplex(4096);
229        // The helper reads the request first, as the real one does; `peer` gets the line and its output pipe.
230        tokio::spawn(async move {
231            let mut helper_r = BufReader::new(helper_r);
232            let mut line = String::new();
233            helper_r.read_line(&mut line).await.unwrap();
234            peer(line, helper_w).await;
235            drop(helper_r);
236        });
237        let mut srv_r = BufReader::new(srv_r);
238        exchange_within(&mut srv_w, &mut srv_r, &req(), deadline).await
239    }
240
241    #[tokio::test]
242    async fn a_request_is_one_json_line_and_the_answer_is_a_line_then_the_png() {
243        let got = run(DEADLINE, |line, mut w| async move {
244            assert_eq!(line, "{\"kind\":\"file\",\"ext\":\"rs\",\"px\":16}\n");
245            w.write_all(b"{\"ok\":true,\"len\":4}\n\x89PNG").await.unwrap();
246        })
247        .await;
248        assert_eq!(got, Ok(b"\x89PNG".to_vec()));
249    }
250
251    #[tokio::test]
252    async fn a_helper_that_has_no_icon_says_so_and_a_broken_one_is_a_failure() {
253        let none = run(DEADLINE, |_line, mut w| async move {
254            w.write_all(b"{\"ok\":false,\"err\":\"no-icon\"}\n").await.unwrap();
255        })
256        .await;
257        assert_eq!(none, Err(IconError::NoIcon));
258        let other = run(DEADLINE, |_line, mut w| async move {
259            w.write_all(b"{\"ok\":false,\"err\":\"com\"}\n").await.unwrap();
260        })
261        .await;
262        assert_eq!(other, Err(IconError::Failed));
263        let garbage = run(DEADLINE, |_line, mut w| async move { w.write_all(b"not json\n").await.unwrap() }).await;
264        assert_eq!(garbage, Err(IconError::Failed));
265        let closed = run(DEADLINE, |_line, w| async move { drop(w) }).await;
266        assert_eq!(closed, Err(IconError::Failed), "a helper that exited");
267    }
268
269    #[tokio::test]
270    async fn a_picture_that_is_empty_oversized_or_cut_short_is_refused() {
271        let zero = run(DEADLINE, |_line, mut w| async move { w.write_all(b"{\"ok\":true,\"len\":0}\n").await.unwrap() }).await;
272        assert_eq!(zero, Err(IconError::Failed));
273        let huge = run(DEADLINE, |_line, mut w| async move {
274            w.write_all(format!("{{\"ok\":true,\"len\":{}}}\n", MAX_PNG_BYTES + 1).as_bytes()).await.unwrap();
275        })
276        .await;
277        assert_eq!(huge, Err(IconError::Failed), "before reading a byte of it");
278        let short = run(DEADLINE, |_line, mut w| async move {
279            w.write_all(b"{\"ok\":true,\"len\":10}\nabc").await.unwrap();
280            drop(w);
281        })
282        .await;
283        assert_eq!(short, Err(IconError::Failed));
284        let long_line = run(DEADLINE, |_line, mut w| async move { w.write_all(&vec![b'x'; 2000]).await.unwrap() }).await;
285        assert_eq!(long_line, Err(IconError::Failed), "an answer line has a limit");
286    }
287
288    #[tokio::test]
289    async fn a_helper_that_never_answers_is_a_timeout_at_the_deadline() {
290        let started = std::time::Instant::now();
291        let got = run(Duration::from_millis(150), |_line, w| async move {
292            // Holds the pipes open and says nothing, like a hung icon handler.
293            let _keep = w;
294            tokio::time::sleep(Duration::from_secs(5)).await;
295        })
296        .await;
297        assert_eq!(got, Err(IconError::Timeout));
298        assert!(started.elapsed() < Duration::from_secs(2));
299    }
300
301    /// A stand-in helper: answers each request after `delay_ms[n]` with the PNG magic and the request's ext.
302    fn fake_worker(delay_ms: Vec<u64>) -> Worker {
303        let (srv_w, helper_r) = duplex(4096);
304        let (helper_w, srv_r) = duplex(4096);
305        tokio::spawn(async move {
306            let mut helper_r = BufReader::new(helper_r);
307            let mut helper_w = helper_w;
308            for delay in delay_ms {
309                let mut line = String::new();
310                if helper_r.read_line(&mut line).await.unwrap_or(0) == 0 {
311                    return;
312                }
313                let ext = serde_json::from_str::<serde_json::Value>(&line).unwrap()["ext"].as_str().unwrap().to_string();
314                tokio::time::sleep(Duration::from_millis(delay)).await;
315                let body = [b"\x89PNG".as_slice(), ext.as_bytes()].concat();
316                helper_w.write_all(format!("{{\"ok\":true,\"len\":{}}}\n", body.len()).as_bytes()).await.unwrap();
317                helper_w.write_all(&body).await.unwrap();
318            }
319        });
320        let reader: Box<dyn AsyncRead + Send + Unpin> = Box::new(srv_r);
321        Worker { child: None, stdin: Box::new(srv_w), stdout: BufReader::new(reader) }
322    }
323
324    fn no_helper() -> std::io::Result<Worker> {
325        Err(std::io::Error::other("tests start no process"))
326    }
327
328    fn req_ext(ext: &str) -> IconRequest {
329        IconRequest { kind: Kind::File, ext: ext.into(), px: 16 }
330    }
331
332    #[tokio::test]
333    async fn a_request_dropped_mid_exchange_does_not_give_the_next_one_its_picture() {
334        let pool = Arc::new(Pool::with_slots(vec![Some(fake_worker(vec![150, 0]))], no_helper));
335        // The page scrolled on: the handler future is dropped while the helper is still working.
336        let first = tokio::spawn({
337            let pool = pool.clone();
338            async move { pool.render(&req_ext("aa")).await }
339        });
340        tokio::time::sleep(Duration::from_millis(30)).await;
341        first.abort();
342        let second = pool.render(&req_ext("bb")).await.unwrap();
343        assert_eq!(second, b"\x89PNGbb".to_vec(), "the second request gets its own answer");
344    }
345
346    #[tokio::test]
347    async fn requests_beyond_the_queue_are_refused_and_a_finished_one_gives_its_place_back() {
348        let pool = Pool::with_slots(vec![Some(fake_worker(vec![0, 0]))], no_helper);
349        assert_eq!(pool.render(&req_ext("aa")).await.unwrap(), b"\x89PNGaa".to_vec());
350        assert_eq!(pool.waiting.available_permits(), QUEUE_MAX);
351        assert_eq!(pool.render(&req_ext("bb")).await.unwrap(), b"\x89PNGbb".to_vec());
352        let held = pool.waiting.clone().try_acquire_many_owned(QUEUE_MAX as u32).unwrap();
353        assert_eq!(pool.render(&req_ext("cc")).await, Err(IconError::Busy));
354        drop(held);
355    }
356}