Skip to main content

agentmux_srv_core/backend/
editor_probe.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What a file is, for the Editor to pick a viewer before it reads anything:
5//! one stat and the first 8 KB. Content decides first (magic bytes, then
6//! text vs binary), the extension only settles what content leaves open.
7//!
8//! The attachment classifier (`attachments::kind`) supplies the magic-byte
9//! table. Its text test ("valid UTF-8, no NUL") is too strict for an editor
10//! — a CP1252 `.ini` file is text — so the text/binary rule here is its own:
11//! a BOM, then the UTF-16 NUL-parity test, then any NUL, then the share of
12//! WHATWG "binary data bytes".
13//!
14//! docs/specs/SPEC_EDITOR_REVAMP_UNIFIED_VIEWERS_2026_10_15.md §4.2, §5.3.
15
16use std::io::Read;
17use std::path::Path;
18
19use image::ImageFormat;
20
21use crate::backend::attachments::kind::{self as attach_kind, FileKind};
22use crate::backend::attachments::process::{self, Sniffed};
23use crate::backend::base::expand_home_dir_safe;
24use crate::backend::rpc::engine::WshRpcEngine;
25use crate::backend::rpc_types::{FileProbeReq, FileProbeResult, FileProbeText};
26
27/// How many bytes the probe reads from the start of the file.
28pub const PROBE_BYTES: usize = 8192;
29/// The UTF-16 parity test looks at this many bytes (VS Code's window).
30const UTF16_WINDOW: usize = 512;
31
32/// The text side of a probe: how the file is encoded, as far as the first
33/// bytes tell.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct ProbedText {
36    /// "utf-8", "utf-16le", "utf-16be", or "legacy" (not UTF-8; the read
37    /// path's detector decides which single-byte or CJK encoding).
38    pub encoding: &'static str,
39    /// The BOM present: "none" | "utf-8" | "utf-16le" | "utf-16be".
40    pub bom: &'static str,
41}
42
43/// What the probe found.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct Probe {
46    /// One of: image, image_file, svg, pdf, audio, video, archive, word,
47    /// excel, powerpoint, sqlite, font, text, other.
48    pub kind: &'static str,
49    pub mime: &'static str,
50    /// Some for text, None for binary.
51    pub text: Option<ProbedText>,
52    /// Why binary: "nul" or "control_bytes"; None for text, and for a
53    /// binary format recognised by its magic bytes.
54    pub binary_reason: Option<&'static str>,
55}
56
57/// `fileprobe`: what a file is (kind, MIME, text or binary), from one stat
58/// and its first 8 KB, so the Editor picks a viewer before reading it. This
59/// computer's files only: an editor on an SSH host reads as text.
60pub fn register(engine: &std::sync::Arc<WshRpcEngine>) {
61    engine.register_typed("fileprobe", move |cmd: FileProbeReq, _ctx| async move {
62        let path = expand_home_dir_safe(&cmd.path);
63        tokio::task::spawn_blocking(move || {
64            let (meta, probe) = probe_path(&path).map_err(|e| format!("fileprobe: {e}"))?;
65            let mtime = meta
66                .modified()
67                .ok()
68                .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
69                .map(|d| d.as_millis() as i64)
70                .unwrap_or(0);
71            Ok(FileProbeResult {
72                size: meta.len(),
73                mtime,
74                kind: probe.kind.to_string(),
75                mime: probe.mime.to_string(),
76                text: probe.text.map(|t| FileProbeText { encoding: t.encoding.to_string(), bom: t.bom.to_string() }),
77                binary_reason: probe.binary_reason.map(str::to_string),
78                read_only: meta.permissions().readonly(),
79            })
80        })
81        .await
82        .map_err(|e| format!("fileprobe: {e}"))?
83    });
84}
85
86/// Probe the file at `path`.
87pub fn probe_path(path: &Path) -> std::io::Result<(std::fs::Metadata, Probe)> {
88    let meta = std::fs::metadata(path)?;
89    if meta.is_dir() {
90        return Err(std::io::Error::other("is a directory"));
91    }
92    let mut head = Vec::with_capacity(PROBE_BYTES);
93    std::fs::File::open(path)?.take(PROBE_BYTES as u64).read_to_end(&mut head)?;
94    let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
95    let ext = attach_kind::extension_of(name);
96    let probe = probe_bytes(&head, ext.as_deref(), || {
97        // The OOXML/ODF inspection opens the ZIP: only for ZIP magic.
98        let k = attach_kind::classify(path, name).ok()?;
99        matches!(k, FileKind::Word | FileKind::Excel | FileKind::PowerPoint).then_some(k)
100    });
101    Ok((meta, probe))
102}
103
104/// [`probe_path`] on the first bytes, with the ZIP inspection injected (tests).
105pub fn probe_bytes(head: &[u8], ext: Option<&str>, zip_kind: impl FnOnce() -> Option<FileKind>) -> Probe {
106    let binary = |kind: &'static str, mime: &'static str| Probe { kind, mime, text: None, binary_reason: None };
107
108    // 1. Images by magic. Chromium decodes these itself; TIFF and HEIC it
109    //    doesn't (they get the info card until a converter exists). BMP's
110    //    "BM" and GIF's "GIF8" are too short to trust alone: a text file can
111    //    begin with them, so those need their full header.
112    match process::sniff(head) {
113        Sniffed::Image(ImageFormat::Tiff) => return binary("image_file", "image/tiff"),
114        Sniffed::Image(ImageFormat::Bmp) if !is_bmp(head) => {}
115        Sniffed::Image(ImageFormat::Gif) if !(head.starts_with(b"GIF87a") || head.starts_with(b"GIF89a")) => {}
116        Sniffed::Image(f) => return binary("image", image_mime(f, head)),
117        Sniffed::Heic => return binary("image_file", "image/heic"),
118        Sniffed::Avif => return binary("image", "image/avif"),
119        Sniffed::Svg => {
120            return Probe { kind: "svg", mime: "image/svg+xml", text: text_info(head).ok(), binary_reason: None }
121        }
122        Sniffed::NotImage => {}
123    }
124    // ICO starts with NULs, so it has to be checked before the text test.
125    if head.len() >= 6 && head[..4] == [0, 0, 1, 0] && head[4..6] != [0, 0] {
126        return binary("image", "image/x-icon");
127    }
128    // JPEG XL: a bare codestream, or the ISO-BMFF container.
129    if head.starts_with(&[0xFF, 0x0A]) || head.starts_with(b"\0\0\0\x0CJXL \r\n\x87\n") {
130        return binary("image_file", "image/jxl");
131    }
132    // A PDF starts with its header. Readers also accept up to 1 KB of junk
133    // before it, but a text file mentioning "%PDF-" near its top is text:
134    // the late header counts only when the bytes aren't text.
135    if head.starts_with(b"%PDF-")
136        || (text_info(head).is_err() && head[..head.len().min(1024)].windows(5).any(|w| w == b"%PDF-"))
137    {
138        return binary("pdf", "application/pdf");
139    }
140    if head.starts_with(b"SQLite format 3\0") {
141        return binary("sqlite", "application/vnd.sqlite3");
142    }
143    if let Some(mime) = font_mime(head, ext) {
144        return binary("font", mime);
145    }
146
147    // 2. Text or binary.
148    let reason = match text_info(head) {
149        // Text bytes are text, whatever the name says (`.ts` is also MPEG
150        // transport stream; a `.mp3` that holds words is words).
151        Ok(t) => {
152            let mime = match ext {
153                Some("csv") => "text/csv",
154                Some("tsv") => "text/tab-separated-values",
155                _ => "text/plain",
156            };
157            return Probe { kind: "text", mime, text: Some(t), binary_reason: None };
158        }
159        Err(reason) => Some(reason),
160    };
161
162    // 3. Binary: the attachment classifier's magic table, then the extension.
163    let kind = match attach_kind::classify_bytes(head, ext, zip_kind) {
164        FileKind::Word => "word",
165        FileKind::Excel => "excel",
166        FileKind::PowerPoint => "powerpoint",
167        FileKind::Archive => "archive",
168        FileKind::Audio => "audio",
169        FileKind::Video => "video",
170        FileKind::Pdf => "pdf",
171        FileKind::Image(_) | FileKind::ImageFile => "image_file",
172        FileKind::Svg | FileKind::Text | FileKind::Other => "other",
173    };
174    Probe { kind, mime: binary_mime(kind, head, ext), text: None, binary_reason: reason }
175}
176
177/// Text, with its encoding, or the reason it is binary.
178fn text_info(head: &[u8]) -> Result<ProbedText, &'static str> {
179    if head.starts_with(&[0xEF, 0xBB, 0xBF]) {
180        return Ok(ProbedText { encoding: "utf-8", bom: "utf-8" });
181    }
182    if head.starts_with(&[0xFF, 0xFE]) {
183        return Ok(ProbedText { encoding: "utf-16le", bom: "utf-16le" });
184    }
185    if head.starts_with(&[0xFE, 0xFF]) {
186        return Ok(ProbedText { encoding: "utf-16be", bom: "utf-16be" });
187    }
188    if let Some(enc) = utf16_by_parity(&head[..head.len().min(UTF16_WINDOW)]) {
189        return Ok(ProbedText { encoding: enc, bom: "none" });
190    }
191    if head.contains(&0) {
192        return Err("nul");
193    }
194    let control = head.iter().filter(|&&b| is_binary_data_byte(b)).count();
195    // More than 1 in 100 bytes (and at least 2) is not a text file with a
196    // stray bell or form feed in it.
197    if control >= 2 && control * 100 > head.len() {
198        return Err("control_bytes");
199    }
200    let encoding = match std::str::from_utf8(head) {
201        Ok(_) => "utf-8",
202        // A code point cut by the 8 KB window is still UTF-8.
203        Err(e) if e.error_len().is_none() => "utf-8",
204        Err(_) => "legacy",
205    };
206    Ok(ProbedText { encoding, bom: "none" })
207}
208
209/// UTF-16 without a BOM: ASCII-range text puts a NUL in every other byte,
210/// on odd offsets for little-endian and even ones for big-endian.
211fn utf16_by_parity(window: &[u8]) -> Option<&'static str> {
212    let pairs = window.len() / 2;
213    if pairs < 2 {
214        return None;
215    }
216    let (mut even, mut odd) = (0usize, 0usize);
217    for (i, &b) in window[..pairs * 2].iter().enumerate() {
218        if b == 0 {
219            if i % 2 == 0 {
220                even += 1;
221            } else {
222                odd += 1;
223            }
224        }
225    }
226    // Most pairs carry the NUL, and never on the other parity.
227    let most = |n: usize| n * 10 >= pairs * 7;
228    if even == 0 && most(odd) {
229        Some("utf-16le")
230    } else if odd == 0 && most(even) {
231        Some("utf-16be")
232    } else {
233        None
234    }
235}
236
237/// WHATWG MIME Sniffing §7.1: a byte that never appears in text.
238fn is_binary_data_byte(b: u8) -> bool {
239    matches!(b, 0x00..=0x08 | 0x0B | 0x0E..=0x1A | 0x1C..=0x1F)
240}
241
242fn image_mime(f: ImageFormat, head: &[u8]) -> &'static str {
243    match f {
244        ImageFormat::Png if is_apng(head) => "image/apng",
245        ImageFormat::Png => "image/png",
246        ImageFormat::Jpeg => "image/jpeg",
247        ImageFormat::Gif => "image/gif",
248        ImageFormat::WebP => "image/webp",
249        ImageFormat::Bmp => "image/bmp",
250        _ => "application/octet-stream",
251    }
252}
253
254/// A BMP file header: "BM", then a DIB header whose size (at offset 14) is
255/// one of the known versions (OS/2 1.x, Windows 3.x, the V2–V5 extensions).
256fn is_bmp(head: &[u8]) -> bool {
257    head.len() >= 18
258        && head.starts_with(b"BM")
259        && matches!(u32::from_le_bytes([head[14], head[15], head[16], head[17]]), 12 | 16 | 40 | 52 | 56 | 64 | 108 | 124)
260}
261
262/// An animated PNG has an `acTL` chunk before its first `IDAT`.
263fn is_apng(head: &[u8]) -> bool {
264    let actl = head.windows(4).position(|w| w == b"acTL");
265    let idat = head.windows(4).position(|w| w == b"IDAT");
266    matches!((actl, idat), (Some(a), Some(i)) if a < i) || matches!((actl, idat), (Some(_), None))
267}
268
269fn font_mime(head: &[u8], ext: Option<&str>) -> Option<&'static str> {
270    if head.starts_with(b"wOFF") {
271        return Some("font/woff");
272    }
273    if head.starts_with(b"wOF2") {
274        return Some("font/woff2");
275    }
276    if head.starts_with(b"OTTO") {
277        return Some("font/otf");
278    }
279    if head.starts_with(b"ttcf") {
280        return Some("font/collection");
281    }
282    // `00 01 00 00` opens TrueType, but other formats too: trust it with a
283    // font extension only.
284    if head.starts_with(&[0, 1, 0, 0]) && matches!(ext, Some("ttf") | Some("otf") | Some("ttc")) {
285        return Some("font/ttf");
286    }
287    None
288}
289
290fn binary_mime(kind: &str, head: &[u8], ext: Option<&str>) -> &'static str {
291    match (kind, ext) {
292        ("audio", Some("mp3")) => "audio/mpeg",
293        ("audio", Some("wav")) => "audio/wav",
294        ("audio", Some("flac")) => "audio/flac",
295        ("audio", Some("ogg") | Some("oga") | Some("opus")) => "audio/ogg",
296        ("audio", Some("m4a")) => "audio/mp4",
297        ("audio", Some("aac")) => "audio/aac",
298        ("audio", _) if head.starts_with(b"ID3") => "audio/mpeg",
299        ("audio", _) if head.starts_with(b"fLaC") => "audio/flac",
300        ("audio", _) if head.starts_with(b"OggS") => "audio/ogg",
301        ("audio", _) => "audio/wav",
302        ("video", Some("webm") | Some("mkv")) => "video/webm",
303        ("video", Some("mov")) => "video/quicktime",
304        ("video", _) if head.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) => "video/webm",
305        ("video", _) => "video/mp4",
306        ("archive", Some("zip")) => "application/zip",
307        ("archive", _) if head.starts_with(b"PK") => "application/zip",
308        ("archive", Some("gz") | Some("tgz")) => "application/gzip",
309        ("word", _) => "application/msword",
310        ("excel", _) => "application/vnd.ms-excel",
311        ("powerpoint", _) => "application/vnd.ms-powerpoint",
312        ("pdf", _) => "application/pdf",
313        _ => "application/octet-stream",
314    }
315}
316
317#[cfg(test)]
318mod tests {
319    use super::*;
320
321    fn p(head: &[u8], ext: Option<&str>) -> Probe {
322        probe_bytes(head, ext, || None)
323    }
324
325    #[tokio::test]
326    async fn fileprobe_records_its_types() {
327        let (engine, _rx) = WshRpcEngine::new();
328        register(&engine);
329        let schema = engine.schema_json();
330        let row = schema
331            .as_array()
332            .unwrap()
333            .iter()
334            .find(|r| r["command"] == "fileprobe")
335            .expect("fileprobe missing from the schema");
336        assert_eq!(row["requestName"], "FileProbeReq");
337        assert_eq!(row["responseName"], "FileProbeResult");
338    }
339
340    #[test]
341    fn probes_a_real_file_and_refuses_a_folder() {
342        let dir = tempfile::tempdir().unwrap();
343        let file = dir.path().join("a.png");
344        std::fs::write(&file, [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A, 0, 0]).unwrap();
345        let (meta, probe) = probe_path(&file).unwrap();
346        assert_eq!(meta.len(), 10);
347        assert_eq!(probe.kind, "image");
348        assert!(probe_path(dir.path()).is_err());
349    }
350
351    #[test]
352    fn images_by_magic() {
353        assert_eq!(p(&[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A, 0, 0], Some("txt")).kind, "image");
354        assert_eq!(p(&[0xFF, 0xD8, 0xFF, 0xE0, 0, 0x10], Some("png")).mime, "image/jpeg");
355        assert_eq!(p(b"GIF89a\x01\0\x01\0", None).mime, "image/gif");
356        assert_eq!(p(b"RIFF\0\0\0\0WEBPVP8 ", None).mime, "image/webp");
357        assert_eq!(p(b"BM\x36\0\0\0\0\0\0\0\x36\0\0\0\x28\0\0\0\x01\0", None).mime, "image/bmp");
358        assert_eq!(p(&[0, 0, 1, 0, 1, 0, 16, 16], Some("ico")).mime, "image/x-icon");
359        assert_eq!(p(b"\0\0\0\x1cftypavif\0\0\0\0", None).kind, "image");
360        assert_eq!(p(b"\0\0\0\x18ftypheic\0\0\0\0", None).kind, "image_file");
361        assert_eq!(p(b"II*\0\x08\0\0\0", None).kind, "image_file");
362        assert_eq!(p(&[0xFF, 0x0A, 0xFA], None).mime, "image/jxl");
363    }
364
365    #[test]
366    fn text_starting_like_a_weak_magic_stays_text() {
367        // "BM" and "GIF8" alone don't make an image (#5016).
368        assert_eq!(p(b"BMW owners club minutes, 2026\n", Some("txt")).kind, "text");
369        assert_eq!(p(b"GIF8 notes: the format\n", Some("md")).kind, "text");
370        // "%PDF-" in text is text; at the start, or after binary junk, it's a PDF.
371        assert_eq!(p(b"// parses files that start with %PDF-1.7\n", Some("rs")).kind, "text");
372        assert_eq!(p(b"\0\x01junk\0%PDF-1.4\n", None).kind, "pdf");
373    }
374
375    #[test]
376    fn apng_is_told_from_png() {
377        let mut head = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
378        head.extend_from_slice(b"\0\0\0\x0dIHDR.............\0\0\0\x08acTL........\0\0\0\0IDAT");
379        assert_eq!(p(&head, None).mime, "image/apng");
380    }
381
382    #[test]
383    fn svg_is_svg_and_text() {
384        let r = p(b"<?xml version=\"1.0\"?><svg xmlns='http://www.w3.org/2000/svg'/>", Some("svg"));
385        assert_eq!(r.kind, "svg");
386        assert!(r.text.is_some());
387    }
388
389    #[test]
390    fn documents_and_containers() {
391        assert_eq!(p(b"%PDF-1.7\n%\xe2\xe3\xcf\xd3\n", None).kind, "pdf");
392        assert_eq!(p(b"SQLite format 3\0\x10\0", Some("db")).kind, "sqlite");
393        assert_eq!(p(b"wOF2\0\x01\0\0", None).kind, "font");
394        assert_eq!(p(&[0, 1, 0, 0, 0, 0x10], Some("ttf")).kind, "font");
395        assert_eq!(p(b"PK\x03\x04\x14\0\0\0", Some("zip")).kind, "archive");
396        assert_eq!(probe_bytes(b"PK\x03\x04\x14\0\0\0", Some("docx"), || Some(FileKind::Word)).kind, "word");
397        assert_eq!(p(b"ID3\x04\0\0\0\0\0\0", Some("mp3")).mime, "audio/mpeg");
398        assert_eq!(p(b"RIFF\x24\0\0\0WAVEfmt ", None).kind, "audio");
399        assert_eq!(p(b"\0\0\0\x20ftypisom\0\0\x02\0", Some("mp4")).kind, "video");
400        assert_eq!(p(b"\0\0\0\x20ftypM4A \0\0\x02\0", Some("m4a")).kind, "audio");
401        // Raw ADTS AAC isn't an MP4 container: Chromium wants audio/aac.
402        let adts = p(&[0xff, 0xf1, 0x50, 0x80, 0x02, 0x1f, 0xfc], Some("aac"));
403        assert_eq!((adts.kind, adts.mime), ("audio", "audio/aac"));
404    }
405
406    #[test]
407    fn executables_and_unknown_binary_are_other() {
408        let r = p(b"MZ\x90\0\x03\0\0\0\x04\0\0\0\xff\xff", Some("exe"));
409        assert_eq!(r.kind, "other");
410        assert_eq!(r.binary_reason, Some("nul"));
411        let r = p(b"\x7fELF\x02\x01\x01\0\0\0\0\0", Some("so"));
412        assert_eq!(r.kind, "other");
413    }
414
415    #[test]
416    fn text_in_every_encoding() {
417        let r = p(b"fn main() {}\n", Some("rs"));
418        assert_eq!(r.kind, "text");
419        assert_eq!(r.text.unwrap().encoding, "utf-8");
420        // CP1252 (an e-acute as 0xE9) is text, not binary.
421        assert_eq!(p(b"name=caf\xe9\r\n", Some("ini")).text.unwrap().encoding, "legacy");
422        assert_eq!(p(b"\xef\xbb\xbfhello", None).text.unwrap().bom, "utf-8");
423        assert_eq!(p(b"\xff\xfeh\0i\0", None).text.unwrap().encoding, "utf-16le");
424        assert_eq!(p(b"\xfe\xff\0h\0i", None).text.unwrap().encoding, "utf-16be");
425        // UTF-16 with no BOM, by where the NULs fall.
426        let le: Vec<u8> = "hello world, this is text".encode_utf16().flat_map(|u| u.to_le_bytes()).collect();
427        assert_eq!(p(&le, Some("txt")).text.unwrap().encoding, "utf-16le");
428        let be: Vec<u8> = "hello world, this is text".encode_utf16().flat_map(|u| u.to_be_bytes()).collect();
429        assert_eq!(p(&be, Some("txt")).text.unwrap().encoding, "utf-16be");
430        // An emoji cut at the end of the window is still UTF-8.
431        let mut cut = b"ok ".to_vec();
432        cut.extend_from_slice(&"\u{1F600}".as_bytes()[..2]);
433        assert_eq!(p(&cut, None).text.unwrap().encoding, "utf-8");
434        // An empty file is text.
435        assert_eq!(p(b"", None).kind, "text");
436    }
437
438    #[test]
439    fn delimited_text_is_typed_by_its_extension() {
440        assert_eq!(p(b"a,b\n1,2\n", Some("csv")).mime, "text/csv");
441        assert_eq!(p(b"a\tb\n1\t2\n", Some("tsv")).mime, "text/tab-separated-values");
442        assert_eq!(p(b"a,b\n1,2\n", Some("txt")).mime, "text/plain");
443        assert_eq!(p(b"a\tb\n", Some("tsv")).kind, "text");
444    }
445
446    #[test]
447    fn a_text_extension_does_not_make_binary_text() {
448        let mut head = b"looks like text at first ".repeat(400);
449        head[8000] = 0;
450        let r = p(&head, Some("txt"));
451        assert_eq!(r.kind, "other");
452        assert_eq!(r.binary_reason, Some("nul"));
453    }
454
455    #[test]
456    fn a_media_extension_does_not_make_text_media() {
457        // `.ts` is also MPEG transport stream; TypeScript is text.
458        assert_eq!(p(b"export const x = 1;\n", Some("ts")).kind, "text");
459        assert_eq!(p(b"just words", Some("mp3")).kind, "text");
460    }
461
462    #[test]
463    fn control_bytes_mark_binary() {
464        let r = p(b"\x01\x02\x03\x04abcdefgh", None);
465        assert_eq!(r.kind, "other");
466        assert_eq!(r.binary_reason, Some("control_bytes"));
467        // An ANSI-coloured log (ESC is allowed) and one stray bell stay text.
468        assert_eq!(p(b"\x1b[31mred\x1b[0m line\n".repeat(20).as_slice(), Some("log")).kind, "text");
469        assert_eq!(p(&[b"a".repeat(500).as_slice(), b"\x07"].concat(), None).kind, "text");
470    }
471}