Skip to main content

agentmux_srv_core/backend/
task_media.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! The files a Kanban task carries, on disk (docs/specs/SPEC_KANBAN_TASK_MEDIA_2026_10_25.md §3.2, §3.3).
5//!
6//! ```text
7//! <shared>/task-media/ab/<sha256>.<ext>        the file, named by its content
8//! <shared>/task-media/ab/<sha256>.thumb.png    a 256 px thumbnail of an image
9//! <shared>/task-media/incoming/<uuid>.part     an upload in flight
10//! ```
11//!
12//! It is in the shared home, not a channel's data dir, because the tasks are shared by every channel.
13//! It is not the attachments store: that store sweeps files by last use, and a picture the operator
14//! has not looked at yet must stay. What a task carries is in `storage/work_media.rs`.
15
16use std::io::Read;
17use std::path::{Path, PathBuf};
18use std::time::{Duration, SystemTime};
19
20use image::ImageFormat;
21
22use super::attachments::process::{self, Sniffed};
23use super::storage::work_media::media_kind;
24
25/// The largest image and recording.
26pub const MAX_IMAGE_BYTES: u64 = 25 * 1024 * 1024;
27pub const MAX_RECORDING_BYTES: u64 = 100 * 1024 * 1024;
28/// The most files in one call.
29pub const MAX_FILES_PER_CALL: usize = 10;
30/// Long edge of a card's thumbnail.
31const THUMB_EDGE: u32 = 256;
32/// An upload left in `incoming/` this long is a leftover.
33const INCOMING_MAX_AGE: Duration = Duration::from_secs(60 * 60);
34/// A stored file no task names, and older than this, is removed (it may be an upload not yet attached).
35const ORPHAN_MAX_AGE: Duration = Duration::from_secs(60 * 60);
36
37/// What a file is, by its content.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct Sniff {
40    pub kind: &'static str,
41    pub mime: &'static str,
42    pub ext: &'static str,
43}
44
45/// What the first bytes of a file say it is, if it is one the Kanban accepts: PNG, JPEG, GIF, WebP, SVG,
46/// MP4, MOV, WebM. Never by the name.
47pub fn sniff(head: &[u8]) -> Option<Sniff> {
48    let image = |mime, ext| Some(Sniff { kind: media_kind::IMAGE, mime, ext });
49    let recording = |mime, ext| Some(Sniff { kind: media_kind::RECORDING, mime, ext });
50    match process::sniff(head) {
51        Sniffed::Image(ImageFormat::Png) => return image("image/png", "png"),
52        Sniffed::Image(ImageFormat::Jpeg) => return image("image/jpeg", "jpg"),
53        Sniffed::Image(ImageFormat::Gif) => return image("image/gif", "gif"),
54        Sniffed::Image(ImageFormat::WebP) => return image("image/webp", "webp"),
55        Sniffed::Svg => return image("image/svg+xml", "svg"),
56        // Other pictures (HEIC, AVIF, BMP, TIFF) are not shown by every pane; ask for a PNG.
57        Sniffed::Image(_) | Sniffed::Heic | Sniffed::Avif => return None,
58        Sniffed::NotImage => {}
59    }
60    if head.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) {
61        return recording("video/webm", "webm");
62    }
63    if head.len() >= 12 && &head[4..8] == b"ftyp" {
64        return match &head[8..12] {
65            b"qt  " => recording("video/quicktime", "mov"),
66            b"heic" | b"heix" | b"hevc" | b"heim" | b"heis" | b"hevm" | b"mif1" | b"msf1" | b"avif" | b"avis" => None,
67            _ => recording("video/mp4", "mp4"),
68        };
69    }
70    None
71}
72
73/// The largest a file of this kind can be.
74pub fn max_bytes(kind: &str) -> u64 {
75    if kind == media_kind::RECORDING {
76        MAX_RECORDING_BYTES
77    } else {
78        MAX_IMAGE_BYTES
79    }
80}
81
82/// The extension a stored file of this MIME type has.
83pub fn ext_of_mime(mime: &str) -> &'static str {
84    match mime {
85        "image/png" => "png",
86        "image/jpeg" => "jpg",
87        "image/gif" => "gif",
88        "image/webp" => "webp",
89        "image/svg+xml" => "svg",
90        "video/webm" => "webm",
91        "video/quicktime" => "mov",
92        _ => "mp4",
93    }
94}
95
96/// Where the folder is, given where the work store is: beside a work store this channel has to itself (a
97/// `task dev` build's), else in the shared home with the store every channel shares. The sweep deletes
98/// what its own store does not name, so two stores must never share one folder.
99pub fn root_beside(isolated_work_store: Option<PathBuf>, shared_dir: Option<PathBuf>) -> Option<PathBuf> {
100    match isolated_work_store {
101        Some(store) => store.parent().map(|dir| dir.join("task-media")),
102        None => shared_dir.map(|dir| dir.join("task-media")),
103    }
104}
105
106/// The folder this srv uses, in step with its work store (see [`root_beside`]).
107#[cfg(not(any(test, feature = "test-support")))]
108pub fn default_root() -> Option<PathBuf> {
109    root_beside(
110        crate::registry::resolve_isolated_work_store_path(&super::base::get_mux_db_dir()),
111        crate::registry::shared_guard::shared_dir(),
112    )
113}
114
115/// In tests, a folder of the test process's own, never the real shared home.
116#[cfg(any(test, feature = "test-support"))]
117pub fn default_root() -> Option<PathBuf> {
118    static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
119    Some(DIR.get_or_init(|| tempfile::tempdir().unwrap()).path().join("task-media"))
120}
121
122fn valid_sha(sha: &str) -> bool {
123    sha.len() == 64 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
124}
125
126/// Where the file with this content is (or would be). `None` for a hash that isn't one: it can never
127/// carry a separator into a path.
128pub fn blob_path(root: &Path, sha: &str, mime: &str) -> Option<PathBuf> {
129    valid_sha(sha).then(|| root.join(&sha[..2]).join(format!("{sha}.{}", ext_of_mime(mime))))
130}
131
132/// Where an image's thumbnail is (or would be).
133pub fn thumb_path(root: &Path, sha: &str) -> Option<PathBuf> {
134    valid_sha(sha).then(|| root.join(&sha[..2]).join(format!("{sha}.thumb.png")))
135}
136
137/// A new path for an upload in flight.
138pub fn new_incoming_path(root: &Path) -> PathBuf {
139    root.join("incoming").join(format!("{}.part", uuid::Uuid::new_v4()))
140}
141
142/// Read the first bytes of a file, enough to sniff it.
143pub fn read_head(path: &Path) -> std::io::Result<Vec<u8>> {
144    let mut f = std::fs::File::open(path)?;
145    let mut buf = vec![0u8; 1024];
146    let mut n = 0;
147    while n < buf.len() {
148        let got = f.read(&mut buf[n..])?;
149        if got == 0 {
150            break;
151        }
152        n += got;
153    }
154    buf.truncate(n);
155    Ok(buf)
156}
157
158/// Move an upload to the place its content names, unless the same content is already there. An image also
159/// gets its thumbnail (a failure to make one is not the upload's: the card falls back to the file).
160pub fn commit(root: &Path, tmp: &Path, sha: &str, found: &Sniff) -> std::io::Result<PathBuf> {
161    let dest = blob_path(root, sha, found.mime).ok_or_else(|| std::io::Error::other("not a content hash"))?;
162    if let Some(dir) = dest.parent() {
163        std::fs::create_dir_all(dir)?;
164    }
165    if dest.exists() {
166        let _ = std::fs::remove_file(tmp);
167    } else if std::fs::rename(tmp, &dest).is_err() {
168        std::fs::copy(tmp, &dest)?;
169        let _ = std::fs::remove_file(tmp);
170    }
171    if found.kind == media_kind::IMAGE && found.mime != "image/svg+xml" {
172        if let Some(thumb) = thumb_path(root, sha).filter(|t| !t.exists()) {
173            let _ = make_thumb(&dest, &thumb);
174        }
175    }
176    Ok(dest)
177}
178
179fn make_thumb(src: &Path, dest: &Path) -> Result<(), String> {
180    process::header_dimensions(src).map_err(|e| e.to_string())?;
181    let mut reader = image::ImageReader::open(src).map_err(|e| e.to_string())?.with_guessed_format().map_err(|e| e.to_string())?;
182    let mut limits = image::Limits::default();
183    limits.max_image_width = Some(process::MAX_SIDE);
184    limits.max_image_height = Some(process::MAX_SIDE);
185    limits.max_alloc = Some(process::MAX_PIXELS * 4 + 64 * 1024 * 1024);
186    reader.limits(limits);
187    let img = reader.decode().map_err(|e| e.to_string())?;
188    img.thumbnail(THUMB_EDGE, THUMB_EDGE).save_with_format(dest, ImageFormat::Png).map_err(|e| e.to_string())
189}
190
191/// Remove the file with this content and its thumbnail. Returns whether a file went.
192pub fn remove_content(root: &Path, sha: &str, mime: &str) -> bool {
193    let mut gone = false;
194    if let Some(p) = blob_path(root, sha, mime) {
195        gone = std::fs::remove_file(p).is_ok();
196    }
197    if let Some(p) = thumb_path(root, sha) {
198        let _ = std::fs::remove_file(p);
199    }
200    gone
201}
202
203/// Clear what is left behind: uploads that never finished, and stored files no task names (`named`
204/// says whether one does) once they are an hour old, so an upload waiting to be attached is not lost.
205/// Returns how many files went.
206pub fn sweep(root: &Path, named: impl Fn(&str) -> bool) -> usize {
207    let mut removed = 0;
208    let old = |meta: &std::fs::Metadata, age: Duration| {
209        meta.modified().ok().and_then(|m| SystemTime::now().duration_since(m).ok()).is_some_and(|a| a > age)
210    };
211    if let Ok(dir) = std::fs::read_dir(root.join("incoming")) {
212        for e in dir.flatten() {
213            if e.metadata().is_ok_and(|m| old(&m, INCOMING_MAX_AGE)) && std::fs::remove_file(e.path()).is_ok() {
214                removed += 1;
215            }
216        }
217    }
218    let Ok(shards) = std::fs::read_dir(root) else { return removed };
219    for shard in shards.flatten() {
220        if shard.file_name() == "incoming" || !shard.path().is_dir() {
221            continue;
222        }
223        let Ok(files) = std::fs::read_dir(shard.path()) else { continue };
224        for f in files.flatten() {
225            let name = f.file_name().to_string_lossy().into_owned();
226            let sha = name.split('.').next().unwrap_or("");
227            if !valid_sha(sha) || named(sha) {
228                continue;
229            }
230            if f.metadata().is_ok_and(|m| old(&m, ORPHAN_MAX_AGE)) && std::fs::remove_file(f.path()).is_ok() {
231                removed += 1;
232            }
233        }
234    }
235    removed
236}
237
238#[cfg(test)]
239#[path = "task_media_tests.rs"]
240mod tests;