Skip to main content

windows_headless/
vision.rs

1//! Guest-screen vision: capture, classify, motion, cadence. Everything
2//! between pixels and verdicts lives here; `commands` orchestrates (run
3//! flows, SSH waits, reporting composition) and never touches a frame
4//! directly.
5//!
6//! Layers, innermost first: `screen_knn` (embeddings + cluster centers)
7//! → `classify_screen` (nearest center to `ScreenState`) → `ScreenSampler` (frames, motion, phase
8//! clocks on a `SamplingProfile`) → `capture_frame`/`take_screenshot`
9//! (frame acquisition). `report_sample` stays with the orchestrator: it
10//! composes vision with `ActivityMonitor`, and composition belongs there.
11
12use anyhow::{Context, Result};
13use std::path::{Path, PathBuf};
14use std::time::Duration;
15
16use crate::timeouts;
17
18pub(crate) const SCREENSHOT_PREFIX: &str = "screenshot-";
19
20/// Per-process shot sequence: two takes inside one epoch second (sampler
21/// save tick + an ad-hoc status/failure shot) must not share a filename.
22/// Epoch keeps names sortable, the counter keeps them unique.
23static SHOT_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
24
25pub(crate) fn screenshot_path(screenshots_dir: &Path) -> PathBuf {
26    let n = SHOT_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
27    screenshots_dir.join(format!(
28        "{SCREENSHOT_PREFIX}{}-{n}.png",
29        crate::provenance::now_epoch()
30    ))
31}
32
33/// Coarse verdict on what the guest screen shows — the one-line answer
34/// boot failures print so they are readable without VNC. Every frame is
35/// judged alone by nearest-exemplar match: no history, no motion rules.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub(crate) enum ScreenState {
38    /// No pixel visibly lit anywhere: literally nothing on screen. A
39    /// spinner dot or a line of text on black is *content*, not this.
40    Dark,
41    /// A bare color field fills the frame with no visible text or UI
42    /// (firmware/GPU output, test patterns). Deliberately NOT an error
43    /// claim: the Windows Setup progress screen is a flat saturated blue
44    /// too — color uniformity alone cannot tell the two apart (live
45    /// 2026-10-04: the main installer screen was 99% #005A9E and the old
46    /// 80% rule announced it as a "BSOD/recovery-like error"). Any
47    /// text-bearing screen — setup, BSOD, recovery — maps to its own
48    /// phase state, never this.
49    FlatField,
50    /// Error UI needing input: modal failure dialogs and bugcheck screens.
51    /// One variant on purpose — the operational response is identical, and
52    /// neither has enough captures to stand alone.
53    ErrorScreen,
54    /// The UEFI shell prompt is up (yellow shell text on black): no
55    /// bootable device was found, so this boot is going nowhere. A shell
56    /// is never routine progress — it is the boot having failed.
57    ErrorShell,
58    /// Windows Recovery screens (WinRE menus and failure text), identified
59    /// by nearest-exemplar match — see [`crate::screen_knn`] for the
60    /// class map. Recovery always needs input, so it is never content.
61    ErrorRecovery,
62    /// Windows Setup / installer progress screens (language select,
63    /// progress bars, spinner). Routine forward motion.
64    InstallerStep,
65    /// First-boot OOBE transitionals ("Just a moment", logo splash,
66    /// "Welcome"): post-install, pre-logon. Progress, never errors.
67    OobeStep,
68    /// Firmware boot art: TianoCore splash, boot logos. Transient screens
69    /// between firmware handoff and the OS.
70    FirmwareBoot,
71    /// Lock screen / idle gradient. The guest is up but waiting; never an
72    /// error in this flow (no desktop ever appears, so this bucket also
73    /// covers miscellaneous idle gradients).
74    Lockscreen,
75}
76
77impl std::fmt::Display for ScreenState {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        f.write_str(match self {
80            ScreenState::Dark => "screen is black (no visible output)",
81            ScreenState::FlatField => "screen shows a solid color field (no UI visible)",
82            ScreenState::ErrorScreen => "screen shows an ERROR (needs input)",
83            ScreenState::ErrorShell => "screen shows the UEFI SHELL (no bootable device)",
84            ScreenState::ErrorRecovery => "screen shows RECOVERY (Windows recovery, needs input)",
85            ScreenState::InstallerStep => "screen shows Windows Setup / installer progress",
86            ScreenState::OobeStep => "screen shows first-boot OOBE (post-install, pre-logon)",
87            ScreenState::FirmwareBoot => {
88                "screen shows firmware boot art (TianoCore splash / boot logo)"
89            }
90            ScreenState::Lockscreen => "screen shows lock screen / idle (guest up, waiting)",
91        })
92    }
93}
94
95/// Classify raw RGB (as parsed by [`parse_ppm_p6`]). Every frame goes
96/// through the k-NN index ([`crate::screen_knn`]): embed, cosine against
97/// the baked cluster centers, top-1. Single frame, no history, no pixel
98/// gates. Returns the state plus the cosine gap (`best` minus best of
99/// any other class): wording hedges below
100/// [`crate::screen_knn::KNN_UNCERTAIN_GAP`], never gating.
101pub(crate) fn classify_screen(rgb: &[u8], width: u32) -> (ScreenState, f32) {
102    use crate::screen_knn::ScreenClass as C;
103    // Degenerate empty frame: nothing captured = nothing to see.
104    if rgb.is_empty() || width == 0 {
105        return (ScreenState::Dark, 1.0);
106    }
107    let height = rgb.len() / 3 / width as usize;
108    assert_eq!(
109        rgb.len(),
110        width as usize * height * 3,
111        "classify_screen size mismatch"
112    );
113    let q = crate::screen_knn::KnnIndex::embed_frame(rgb, width, height as u32);
114    let (class, gap, _) = crate::screen_knn::shared_index()
115        .predict(&q, None)
116        .unwrap_or((C::Dark, 1.0, String::new()));
117    let state = match class {
118        C::Dark => ScreenState::Dark,
119        C::FlatField => ScreenState::FlatField,
120        C::ErrorShell => ScreenState::ErrorShell,
121        C::InstallerStep => ScreenState::InstallerStep,
122        C::Lockscreen => ScreenState::Lockscreen,
123        C::FirmwareBoot => ScreenState::FirmwareBoot,
124        C::OobeStep => ScreenState::OobeStep,
125        C::ErrorRecovery => ScreenState::ErrorRecovery,
126        C::ErrorScreen => ScreenState::ErrorScreen,
127    };
128    (state, gap)
129}
130
131/// Log-line wording for a classified frame: the [`ScreenState`] message,
132/// hedged when an error read is uncertain. Uncertainty never gates —
133/// the activity conjunction alone decides WARNINGs.
134pub(crate) fn describe(state: ScreenState, gap: f32) -> String {
135    let base = state.to_string();
136    let is_error = matches!(
137        state,
138        ScreenState::ErrorScreen | ScreenState::ErrorShell | ScreenState::ErrorRecovery
139    );
140    if is_error && gap < crate::screen_knn::KNN_UNCERTAIN_GAP {
141        format!("{base} (uncertain — may need input)")
142    } else {
143        base
144    }
145}
146
147/// Raw frame capture shared by the sampler and [`take_screenshot`]:
148/// screendump to a temp PPM inside the screenshots dir, parsed to RGB,
149/// PPM deleted. The PPM lives beside the PNGs (never /tmp —
150/// world-writable-sticky, symlink squatting, cross-VM collisions) under a
151/// `frame-` prefix that never collides with `screenshot-*.png`.
152async fn capture_frame(
153    mon: &crate::ipc::Monitor,
154    screenshots_dir: &Path,
155) -> Option<(u32, u32, Vec<u8>)> {
156    if std::fs::create_dir_all(screenshots_dir).is_err() {
157        return None;
158    }
159    // O_EXCL temp file, never a hand-built epoch name: the sampler task
160    // and ad-hoc takes run concurrently in one process, and two
161    // same-second captures sharing `frame-<pid>-<epoch>.ppm` made one
162    // delete the other's screendump mid-read (observed class: transient
163    // parse failures). Drop at the end deletes it on every path.
164    let ppm_file = match tempfile::Builder::new()
165        .prefix("frame-")
166        .suffix(".ppm")
167        .tempfile_in(screenshots_dir)
168    {
169        Ok(f) => f,
170        Err(e) => {
171            eprintln!("warning: frame temp file failed ({e:#})");
172            return None;
173        }
174    };
175    let ppm = ppm_file.path().to_path_buf();
176    // Quote the path: HMP splits unquoted args on whitespace and the cache
177    // path routinely contains spaces (observed live: screendump "succeeded"
178    // but the file never appeared, failing the PNG step with ENOENT).
179    let shot = mon
180        .command(&format!("screendump \"{}\"", ppm.display()))
181        .await;
182    if let Err(e) = shot {
183        eprintln!("warning: screendump failed: {e:#}");
184        return None;
185    }
186    // Always clean up the raw PPM: a failed conversion must not leak
187    // multi-MB dumps on every cadence tick (drop deletes the temp file).
188    let result = std::fs::read(&ppm)
189        .map_err(anyhow::Error::from)
190        .and_then(|d| {
191            let (w, h, rgb) = parse_ppm_p6(&d)?;
192            Ok((w, h, rgb))
193        });
194    drop(ppm_file);
195    match result {
196        Ok(ok) => Some(ok),
197        Err(e) => {
198            eprintln!("warning: ppm parse failed ({e:#})");
199            None
200        }
201    }
202}
203
204/// One screendump frame: `screendump` to PPM, converted in-crate to PNG
205/// (README-displayable; tens to low hundreds of KB depending on screen
206/// content vs 1.4 MB raw), PPM deleted. Frames land as
207/// `<screenshots_dir>/screenshot-<epoch>.png`, each paired with the
208/// [`ScreenState`] verdict from [`classify_screen`] so callers can
209/// announce *what* the screen shows, not just where the file is.
210/// Best-effort (logs, never fails): the monitor may be busy mid-command
211/// and a missed frame is not worth failing an install over.
212/// Returns the PNG path + state + margin on success so callers can
213/// announce it.
214pub(crate) async fn take_screenshot(
215    mon: &crate::ipc::Monitor,
216    screenshots_dir: &Path,
217) -> Option<(PathBuf, ScreenState, f32)> {
218    let (w, h, rgb) = capture_frame(mon, screenshots_dir).await?;
219    // Single frame straight from the index: no history, no motion
220    // rules. What the nearest center says is what gets reported.
221    let (state, margin) = classify_screen(&rgb, w);
222    let png_path = screenshot_path(screenshots_dir);
223    match write_png(&png_path, w, h, &rgb) {
224        Ok(()) => Some((png_path, state, margin)),
225        Err(e) => {
226            eprintln!("warning: png write failed ({e:#})");
227            None
228        }
229    }
230}
231
232/// Parse binary P6 PPM → (width, height, RGB bytes). QEMU screendump
233/// writes plain `P6\n<w> <h>\n255\n` + pixels; the parser also tolerates
234/// comments and stray whitespace per the spec.
235fn parse_ppm_p6(data: &[u8]) -> Result<(u32, u32, Vec<u8>)> {
236    let mut pos = 0;
237    let mut token = || -> Result<String> {
238        // Skip whitespace and `#` comments.
239        loop {
240            while pos < data.len() && data[pos].is_ascii_whitespace() {
241                pos += 1;
242            }
243            if pos < data.len() && data[pos] == b'#' {
244                while pos < data.len() && data[pos] != b'\n' {
245                    pos += 1;
246                }
247                continue;
248            }
249            break;
250        }
251        let start = pos;
252        while pos < data.len() && !data[pos].is_ascii_whitespace() {
253            pos += 1;
254        }
255        if start == pos {
256            anyhow::bail!("truncated PPM header");
257        }
258        Ok(String::from_utf8_lossy(&data[start..pos]).into_owned())
259    };
260    if token()? != "P6" {
261        anyhow::bail!("not a P6 PPM");
262    }
263    let w: u32 = token()?.parse().context("PPM width")?;
264    let h: u32 = token()?.parse().context("PPM height")?;
265    let max: u32 = token()?.parse().context("PPM maxval")?;
266    if max != 255 {
267        anyhow::bail!("unsupported PPM maxval {max} (want 255)");
268    }
269    // Exactly one whitespace byte separates header from pixels.
270    if pos < data.len() && data[pos].is_ascii_whitespace() {
271        pos += 1;
272    }
273    let expect = w as usize * h as usize * 3;
274    if data.len() - pos < expect {
275        anyhow::bail!(
276            "truncated PPM pixels (have {}, want {expect})",
277            data.len() - pos
278        );
279    }
280    Ok((w, h, data[pos..pos + expect].to_vec()))
281}
282
283fn write_png(path: &Path, w: u32, h: u32, rgb: &[u8]) -> Result<()> {
284    // Screenshots are flat UI: usually < 256 distinct colors, so exact
285    // palette encoding (no dithering, no loss) beats RGB by ~7x
286    // (measured: 42 KB RGB → 5.7 KB palette on a Setup screen).
287    // Falls back to RGB when the frame is richer than 256 colors.
288    use std::collections::HashMap;
289    let mut palette: Vec<[u8; 3]> = Vec::new();
290    let mut index_of: HashMap<[u8; 3], u8> = HashMap::new();
291    let mut indexed = Vec::with_capacity(rgb.len() / 3);
292    let mut fits = true;
293    let (chunks, remainder) = rgb.as_chunks::<3>();
294    if !remainder.is_empty() {
295        fits = false;
296    }
297    for px in chunks {
298        if !fits {
299            break;
300        }
301        let key = [px[0], px[1], px[2]];
302        let idx = match index_of.get(&key) {
303            Some(&i) => i,
304            None => {
305                if palette.len() >= 256 {
306                    fits = false;
307                    break;
308                }
309                let i = palette.len() as u8;
310                palette.push(key);
311                index_of.insert(key, i);
312                i
313            }
314        };
315        indexed.push(idx);
316    }
317    let file = std::fs::File::create(path)?;
318    let mut enc = png::Encoder::new(std::io::BufWriter::new(file), w, h);
319    enc.set_depth(png::BitDepth::Eight);
320    enc.set_compression(png::Compression::High);
321    if fits {
322        let flat: Vec<u8> = palette.iter().flatten().copied().collect();
323        enc.set_color(png::ColorType::Indexed);
324        enc.set_palette(flat);
325        enc.write_header()?.write_image_data(&indexed)?;
326    } else {
327        enc.set_color(png::ColorType::Rgb);
328        enc.write_header()?.write_image_data(rgb)?;
329    }
330    Ok(())
331}
332
333/// Cadence policy: answers "how often", owns no state, no I/O, no ticker.
334/// The loops tick on [`SamplingProfile::tick`] and gate each layer on its
335/// own due-check — one scheduler, three rates, zero alternate capture
336/// paths.
337pub struct SamplingProfile {
338    /// Disk PNG cadence (zero = off).
339    pub save_every: Duration,
340    /// In-memory match cadence (zero = off).
341    pub classify_every: Duration,
342    /// Status-line narration cadence.
343    pub narrate_every: Duration,
344}
345
346impl SamplingProfile {
347    /// TCG classify default: pegged software emulation earns 3x spacing.
348    pub const TCG_CLASSIFY_SECS: u64 = 30;
349
350    /// Resolve after accelerator detection finalizes (post any KVM→TCG
351    /// fallback): explicit flag wins, else accel default. Same predicate
352    /// `cpu_model()` uses — no new detection, later call.
353    pub fn resolve(save_secs: u64, classify: Option<u64>, accel: &str) -> Self {
354        let classify_secs = classify.unwrap_or(if accel == "tcg" {
355            Self::TCG_CLASSIFY_SECS
356        } else {
357            timeouts::DEFAULT_CLASSIFY_EVERY_SECS
358        });
359        Self {
360            save_every: Duration::from_secs(save_secs),
361            classify_every: Duration::from_secs(classify_secs),
362            narrate_every: Duration::from_secs(timeouts::DEFAULT_BOOT_NARRATION_SECS),
363        }
364    }
365
366    /// Single tick authority: min over active cadences (zero = that layer
367    /// off). `None` when everything is off: nothing to schedule.
368    pub fn tick(&self) -> Option<Duration> {
369        [self.save_every, self.classify_every, self.narrate_every]
370            .into_iter()
371            .filter(|d| !d.is_zero())
372            .min()
373    }
374}
375
376/// What one sampler tick produced. The reporter announces; the sampler
377/// never prints.
378#[derive(Clone)]
379pub(crate) enum SampleOutcome {
380    /// PNG saved (doubles as the status line): path, state, prob margin.
381    Saved(PathBuf, ScreenState, f32),
382    /// In-memory classification only.
383    Classified(ScreenState, f32),
384    /// Nothing due, or the capture failed best-effort.
385    Skipped,
386}
387
388/// What the guest looks like now. Owns the screendump, the frame buffer,
389/// classification, and motion diff. Answers, never announces, never
390/// policies: the loop ticks on the profile and reports via the
391/// orchestrator's status line.
392pub(crate) struct ScreenSampler {
393    pub(crate) mon: std::sync::Arc<crate::ipc::Monitor>,
394    dir: PathBuf,
395    pub(crate) started: std::time::Instant,
396    pub(crate) shot_n: u64,
397    pub(crate) status_n: u64,
398    last_save: Option<std::time::Instant>,
399    last_classify: Option<std::time::Instant>,
400    /// Previous tick's grid frame + geometry, for the motion diff.
401    prev_grid: Option<(Vec<u8>, u32, u32)>,
402    last_state: Option<(ScreenState, f32)>,
403    pub(crate) last_outcome: SampleOutcome,
404    state_since: std::time::Instant,
405    static_since: std::time::Instant,
406}
407
408impl ScreenSampler {
409    /// Tile-max diff per pixel (0–255 scale) below which the screen
410    /// counts as static. Sits above VNC compression noise and cursor
411    /// blink (verify against a real parked capture); an edge spinner
412    /// tripping one tile clears it — a global mean would not.
413    const MOTION_NOISE_FLOOR: f32 = 1.5;
414
415    pub(crate) fn new(mon: std::sync::Arc<crate::ipc::Monitor>, dir: PathBuf) -> Self {
416        let now = std::time::Instant::now();
417        Self {
418            mon,
419            dir,
420            started: now,
421            shot_n: 0,
422            status_n: 0,
423            // `None` = due immediately: the first poll captures instead of
424            // special-casing startup.
425            last_save: None,
426            last_classify: None,
427            prev_grid: None,
428            last_state: None,
429            last_outcome: SampleOutcome::Skipped,
430            state_since: now,
431            static_since: now,
432        }
433    }
434
435    /// One tick: at most one screendump, serving save or classify,
436    /// whichever the profile says is due. No tick ever double-captures.
437    pub(crate) async fn poll(&mut self, profile: &SamplingProfile) {
438        let save_due = !profile.save_every.is_zero()
439            && self
440                .last_save
441                .is_none_or(|t| t.elapsed() >= profile.save_every);
442        if save_due {
443            let Some((w, h, rgb)) = capture_frame(&self.mon, &self.dir).await else {
444                self.last_outcome = SampleOutcome::Skipped;
445                return;
446            };
447            let (state, margin) = classify_screen(&rgb, w);
448            self.observe_frame(&rgb, w, h, state);
449            let png_path = screenshot_path(&self.dir);
450            match write_png(&png_path, w, h, &rgb) {
451                Ok(()) => {
452                    self.shot_n += 1;
453                    self.status_n += 1;
454                    self.last_save = Some(std::time::Instant::now());
455                    self.last_classify = Some(std::time::Instant::now());
456                    self.last_state = Some((state, margin));
457                    self.last_outcome = SampleOutcome::Saved(png_path, state, margin);
458                }
459                Err(e) => {
460                    eprintln!("warning: png write failed ({e:#})");
461                    self.last_outcome = SampleOutcome::Skipped;
462                }
463            }
464            return;
465        }
466        let classify_due = !profile.classify_every.is_zero()
467            && self
468                .last_classify
469                .is_none_or(|t| t.elapsed() >= profile.classify_every);
470        if classify_due && let Some((w, h, rgb)) = capture_frame(&self.mon, &self.dir).await {
471            let (state, margin) = classify_screen(&rgb, w);
472            self.observe_frame(&rgb, w, h, state);
473            self.status_n += 1;
474            self.last_classify = Some(std::time::Instant::now());
475            self.last_state = Some((state, margin));
476            self.last_outcome = SampleOutcome::Classified(state, margin);
477            return;
478        }
479        self.last_outcome = SampleOutcome::Skipped;
480    }
481
482    /// Fold one captured frame into motion + phase tracking. Motion runs
483    /// on the FULL frame (not a center crop): progress
484    /// spinners live on edges (observed: installer spinner at ~4% from
485    /// the left), and a crop reused for motion is blind to them. Tile-max
486    /// keeps the noise immunity a full-frame mean would lose: localized
487    /// animation trips one tile while flat background dilutes nothing.
488    /// New geometry (driver handoff) or first frame: no baseline, so no
489    /// claim — the buffer adopts the new geometry and the static timer
490    /// holds.
491    fn observe_frame(&mut self, rgb: &[u8], w: u32, h: u32, state: ScreenState) {
492        let grid = crate::screen_knn::downsample_to_grid_rgb(rgb, w as usize, h as usize);
493        let moved = match &self.prev_grid {
494            Some((prev, pw, ph)) if *pw == w && *ph == h => {
495                tile_max_diff(prev, &grid, crate::screen_knn::GRID) >= Self::MOTION_NOISE_FLOOR
496            }
497            _ => false,
498        };
499        // Hold the static timer across geometry changes and failed
500        // captures (no frame = no evidence either way).
501        if moved {
502            self.static_since = std::time::Instant::now();
503        }
504        self.prev_grid = Some((grid.to_vec(), w, h));
505        if self.last_state.map(|(s, _)| s) != Some(state) {
506            self.state_since = std::time::Instant::now();
507        }
508    }
509
510    /// Seconds in the current screen state.
511    pub(crate) fn phase_secs(&self) -> u64 {
512        self.state_since.elapsed().as_secs()
513    }
514
515    /// Latest classified state, if any frame has been captured yet.
516    pub(crate) fn state(&self) -> Option<ScreenState> {
517        self.last_state.map(|(s, _)| s)
518    }
519
520    /// Seconds since pixels last moved beyond the noise floor.
521    pub(crate) fn static_secs(&self) -> u64 {
522        self.static_since.elapsed().as_secs()
523    }
524}
525
526/// Max over tiles of mean abs per-pixel diff (0–255 scale): localized
527/// motion (an edge spinner moving dozens of pixels) trips its tile even
528/// when a global mean would dilute it into the background. `dim` is the
529/// square grid edge; RGB-interleaved, 8×8 tiles. Degenerate input reads
530/// as maximum motion, never a panic.
531fn tile_max_diff(a: &[u8], b: &[u8], dim: usize) -> f32 {
532    const TILES: usize = 8;
533    if a.len() != b.len() || a.is_empty() || a.len() != dim * dim * 3 || !dim.is_multiple_of(TILES)
534    {
535        return 255.0;
536    }
537    let tile = dim / TILES;
538    let mut max = 0.0f32;
539    for ty in 0..TILES {
540        for tx in 0..TILES {
541            let mut sum = 0u64;
542            for y in 0..tile {
543                for x in 0..tile {
544                    let base = ((ty * tile + y) * dim + (tx * tile + x)) * 3;
545                    for c in 0..3 {
546                        sum += a[base + c].abs_diff(b[base + c]) as u64;
547                    }
548                }
549            }
550            let mean = sum as f32 / (tile * tile * 3) as f32;
551            if mean > max {
552                max = mean;
553            }
554        }
555    }
556    max
557}
558
559/// Compact durations, always HH:MM:SS: readable at 3 hours, no math.
560pub(crate) fn fmt_secs(s: u64) -> String {
561    format!("{:02}:{:02}:{:02}", s / 3600, (s / 60) % 60, s % 60)
562}
563
564/// Compact byte counts: 512B, 12MB, 1.2GB (one decimal under 10 units).
565pub(crate) fn fmt_bytes(b: u64) -> String {
566    const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
567    let mut v = b as f64;
568    let mut u = 0;
569    while v >= 1024.0 && u < 4 {
570        v /= 1024.0;
571        u += 1;
572    }
573    if v < 10.0 && u > 0 {
574        format!("{v:.1}{}", UNITS[u])
575    } else {
576        format!("{v:.0}{}", UNITS[u])
577    }
578}
579
580pub(crate) fn is_error_state(s: ScreenState) -> bool {
581    matches!(
582        s,
583        ScreenState::ErrorScreen | ScreenState::ErrorShell | ScreenState::ErrorRecovery
584    )
585}
586
587#[cfg(test)]
588mod tests {
589    use super::*;
590
591    fn flat(w: usize, h: usize, rgb: [u8; 3]) -> Vec<u8> {
592        let mut v = Vec::with_capacity(w * h * 3);
593        for _ in 0..w * h {
594            v.extend_from_slice(&rgb);
595        }
596        v
597    }
598
599    #[test]
600    fn screen_state_black_means_nothing_visible() {
601        assert_eq!(
602            classify_screen(&flat(64, 64, [0, 0, 0]), 64).0,
603            ScreenState::Dark
604        );
605        // Degenerate empty frame: nothing captured = nothing to see.
606        assert_eq!(classify_screen(&[], 0).0, ScreenState::Dark);
607    }
608
609    #[test]
610    fn uncertain_errors_hedge_confident_ones_do_not() {
611        // Gap scale, not prob scale: the hedge threshold is
612        // KNN_UNCERTAIN_GAP (0.01), so 0.005 hedges and 0.5 states.
613        let hedged = describe(ScreenState::ErrorScreen, 0.005);
614        assert!(hedged.contains("uncertain"), "{hedged}");
615        let firm = describe(ScreenState::ErrorScreen, 0.5);
616        assert!(!firm.contains("uncertain"), "{firm}");
617        // Progress states never hedge: only error reads carry doubt.
618        let progress = describe(ScreenState::InstallerStep, 0.0);
619        assert!(!progress.contains("uncertain"), "{progress}");
620    }
621
622    #[test]
623    fn durations_read_hh_mm_ss() {
624        assert_eq!(fmt_secs(0), "00:00:00");
625        assert_eq!(fmt_secs(95), "00:01:35");
626        assert_eq!(fmt_secs(252), "00:04:12");
627        assert_eq!(fmt_secs(3600), "01:00:00");
628        assert_eq!(fmt_secs(3 * 3600 + 41 * 60 + 7), "03:41:07");
629    }
630
631    #[test]
632    fn byte_counts_stay_compact() {
633        assert_eq!(fmt_bytes(0), "0B");
634        assert_eq!(fmt_bytes(512), "512B");
635        assert_eq!(fmt_bytes(1536), "1.5KB");
636        assert_eq!(fmt_bytes(12 * 1024 * 1024), "12MB");
637    }
638
639    #[test]
640    fn tile_max_catches_edge_motion_global_mean_misses() {
641        // The installer-spinner case: a small changed block in the
642        // corner tile. Global mean stays under the floor while the hot
643        // tile clears it — a crop/full-mean-only metric reads static.
644        let dim = 32usize;
645        let still = vec![10u8; dim * dim * 3];
646        let mut moved = still.clone();
647        for y in 0..2 {
648            for x in 0..2 {
649                for c in 0..3 {
650                    moved[(y * dim + x) * 3 + c] = 210;
651                }
652            }
653        }
654        let global: f32 = still
655            .iter()
656            .zip(moved.iter())
657            .map(|(&x, &y)| x.abs_diff(y) as u64)
658            .sum::<u64>() as f32
659            / still.len() as f32;
660        assert!(global < ScreenSampler::MOTION_NOISE_FLOOR);
661        assert!(tile_max_diff(&still, &moved, dim) >= ScreenSampler::MOTION_NOISE_FLOOR);
662        assert_eq!(tile_max_diff(&still, &still, dim), 0.0);
663        assert_eq!(tile_max_diff(&[], &[], dim), 255.0);
664        assert_eq!(tile_max_diff(&still, &moved, 30), 255.0);
665    }
666
667    #[test]
668    fn ppm_p6_roundtrip() {
669        // 2x1 red/green pixels with a comment in the header.
670        let mut raw = b"P6\n# qemu screendump\n2 1\n255\n".to_vec();
671        raw.extend_from_slice(&[255, 0, 0, 0, 255, 0]);
672        let (w, h, rgb) = parse_ppm_p6(&raw).unwrap();
673        assert_eq!((w, h), (2, 1));
674        assert_eq!(rgb, vec![255, 0, 0, 0, 255, 0]);
675        let dir = tempfile::tempdir().unwrap();
676        let p = dir.path().join("t.png");
677        write_png(&p, w, h, &rgb).unwrap();
678        let back = std::fs::read(&p).unwrap();
679        assert_eq!(&back[1..4], b"PNG", "not a PNG");
680        // 2 colors → indexed palette (IHDR color type 3), exact pixels.
681        assert_eq!(
682            back[25], 3,
683            "expected palette PNG, got color type {}",
684            back[25]
685        );
686        assert!(
687            back.len() < 100,
688            "2px palette PNG should be tiny, got {}",
689            back.len()
690        );
691    }
692
693    #[test]
694    fn ppm_rejects_bad_magic_and_truncation() {
695        assert!(parse_ppm_p6(b"P5\n2 1\n255\n\x00\x00").is_err());
696        assert!(parse_ppm_p6(b"P6\n2 1\n255\n\xff").is_err());
697    }
698}