Skip to main content

smix_simctl/
lib.rs

1#![doc = include_str!("../README.md")]
2#![deny(missing_docs)]
3#![deny(rustdoc::broken_intra_doc_links)]
4
5//! smix-simctl — xcrun simctl child_process wrapper (outer crate).
6//!
7//! All operations shell out to `xcrun simctl <subcommand>`; JSON-formatted
8//! outputs (list runtimes, list devices, screenshot binary) are parsed with
9//! serde_json / raw bytes. Tokio's `process::Command` is the async spawn
10//! primitive.
11//!
12//! This is an outer crate — allowed to depend on the wider tokio ecosystem.
13//! Use it from cement (smix-cli / smix-mcp) or from a higher-level driver
14//! wrapper.
15
16#![doc(html_root_url = "https://docs.smix.dev/smix-simctl")]
17
18pub mod registry;
19/// Adaptive `xcrun simctl io screenshot` pacer. See
20/// [`screenshot_pacer::ScreenshotPacer`].
21pub mod screenshot_pacer;
22/// Persistent CoreSimulator framebuffer capture via a resident
23/// `smix-capture-host`. See [`surface_capture::SurfaceCaptureHost`].
24pub mod surface_capture;
25
26use screenshot_pacer::{ScreenshotPacer, ScreenshotPacerConfig};
27use serde::{Deserialize, Serialize};
28use std::io;
29use std::sync::Arc;
30use std::time::Duration;
31use thiserror::Error;
32use tokio::process::Command;
33use tokio::time::sleep;
34
35/// Failure variants for a device-control invocation.
36///
37/// `DeviceControl` is one trait across iOS and Android, and this is its error
38/// type — `AndroidDeviceControl` raises it as much as the simctl path does.
39/// The messages name the command that actually ran rather than assuming
40/// simctl, so an Android failure does not send the reader to the wrong
41/// toolchain by claiming to come from `xcrun simctl`.
42#[derive(Debug, Error)]
43#[non_exhaustive]
44pub enum DeviceControlError {
45    /// Failed to spawn the device-control process (PATH lookup / fork failure).
46    #[error("spawn failed: {0}")]
47    Spawn(#[from] io::Error),
48    /// The bundle is not installed on the device. `simctl
49    /// get_app_container` exiting non-zero is the canonical signal —
50    /// surfaced as its own variant because "run a flow whose appId
51    /// names an app you have not installed yet" is the single most
52    /// common first-run mistake, and it used to read as a bare
53    /// subprocess error.
54    #[error(
55        "app {bundle_id} is not installed on {udid} — install it \
56         (`smix sim install <device> /path/to/YourApp.app`) or check the \
57         flow's `appId:` matches what is actually installed"
58    )]
59    AppNotInstalled {
60        /// The bundle the caller asked about.
61        bundle_id: String,
62        /// The device it is missing from.
63        udid: String,
64    },
65    /// The device-control command exited non-zero.
66    ///
67    /// Carries the full `argv` and `wall_ms` so the `Display` impl
68    /// surfaces every argument needed to reproduce the failure or file
69    /// a precise upstream bug — the subcommand name alone (e.g.
70    /// `"spawn"`) does not say which binary or paths were touched.
71    #[error("{} exited {code} ({wall_ms}ms): {stderr}", .argv.join(" "))]
72    NonZeroExit {
73        /// Subcommand name (e.g. `"boot"`, `"launch"`).
74        subcommand: String,
75        /// The full command as invoked, binary first — `["xcrun", "simctl",
76        /// "boot", …]` from simctl, `["adb", …]` from the Android side.
77        ///
78        /// The binary belongs here rather than in the `Display` format
79        /// string: this error type serves both platforms, and hard-coding
80        /// `xcrun simctl` made every Android failure name a tool that never
81        /// ran, sending the reader to the wrong toolchain.
82        ///
83        /// Since smix 1.0.7.
84        argv: Vec<String>,
85        /// Exit code from `xcrun simctl`.
86        code: i32,
87        /// Captured stderr (truncated for log-friendliness).
88        stderr: String,
89        /// Wall-clock milliseconds the invocation ran before failing.
90        ///
91        /// Since smix 1.0.7.
92        #[allow(dead_code)]
93        wall_ms: u64,
94    },
95    /// `xcrun simctl <sub>` exited 0 but stdout didn't match the expected shape.
96    #[error("{subcommand} returned malformed output: {detail}")]
97    Malformed {
98        /// Subcommand name.
99        subcommand: String,
100        /// Parser-side detail.
101        detail: String,
102    },
103    /// `xcrun simctl <sub>` did not complete within the deadline.
104    #[error("{subcommand} timed out after {ms}ms")]
105    Timeout {
106        /// Subcommand name.
107        subcommand: String,
108        /// Deadline that was exceeded (milliseconds).
109        ms: u64,
110    },
111    /// The screenshot pacer's circuit is open — a recent screenshot
112    /// wall time exceeded the circuit threshold, or a screenshot
113    /// failed. Callers should back off for `retry_after` and try
114    /// again. See [`screenshot_pacer::ScreenshotPacer`].
115    ///
116    /// Since smix 1.0.4.
117    #[error("screenshot pacer circuit open; retry after {retry_after:?}")]
118    CaptureBackpressure {
119        /// Suggested minimum delay before the next attempt.
120        retry_after: Duration,
121    },
122}
123
124impl DeviceControlError {
125    /// Synthetic `NonZeroExit` for callers translating a foreign
126    /// subprocess error into `DeviceControlError` (e.g.
127    /// AndroidDeviceControl adapting adb failures). Fills
128    /// `argv = [subcommand]` + `wall_ms = 0`; when the caller has a
129    /// real argv, prefer the struct literal.
130    pub fn non_zero_exit(
131        subcommand: impl Into<String>,
132        code: i32,
133        stderr: impl Into<String>,
134    ) -> Self {
135        let sub = subcommand.into();
136        Self::NonZeroExit {
137            argv: vec![sub.clone()],
138            subcommand: sub,
139            code,
140            stderr: stderr.into(),
141            wall_ms: 0,
142        }
143    }
144}
145
146/// Handle to an active `xcrun simctl io recordVideo` child process. Pair
147/// with [`SimctlClient::record_video_stop`] for SIGINT-and-wait shutdown
148/// (so the mp4 trailer is flushed). Dropping the handle without `stop`
149/// would tokio-SIGKILL on Drop and truncate the output file.
150#[derive(Debug)]
151pub struct RecordingHandle {
152    pub(crate) child: tokio::process::Child,
153    /// Output mp4 path verbatim as passed to `record_video_start`.
154    pub path: String,
155    /// Wall-clock start time for "recording in progress for Xs" diagnostics.
156    pub started_at: std::time::Instant,
157}
158
159impl RecordingHandle {
160    /// Pid of the `simctl io … recordVideo` child.
161    ///
162    /// Needed by anything that must record this process somewhere it will
163    /// outlive us: a recording whose only handle is this struct dies with
164    /// the process holding it, and the mp4 it was writing loses its
165    /// trailer with no one left who knows to send the SIGINT that would
166    /// have saved it.
167    ///
168    /// `None` once the child has been reaped.
169    #[must_use]
170    pub fn pid(&self) -> Option<u32> {
171        self.child.id()
172    }
173}
174
175// -------------------- types ----------------------------------------------
176
177/// One iOS / watchOS / tvOS runtime installed on the host.
178#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
179pub struct SimctlRuntime {
180    /// Fully-qualified runtime identifier (e.g. `"com.apple.CoreSimulator.SimRuntime.iOS-17-0"`).
181    pub identifier: String,
182    /// Human-readable name (e.g. `"iOS 17.0"`).
183    pub name: String,
184    /// Version string (e.g. `"17.0"`).
185    pub version: String,
186    /// Whether the runtime is available for booting devices.
187    pub is_available: bool,
188}
189
190/// One simulator device known to `xcrun simctl`.
191#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
192pub struct SimctlDevice {
193    /// Device UDID (stable identifier).
194    pub udid: String,
195    /// Human-readable name.
196    pub name: String,
197    /// Current state (`"Booted"` / `"Shutdown"` / `"Creating"` / etc.).
198    pub state: String,
199    /// Whether the device is available for booting.
200    pub is_available: bool,
201    /// Device-type identifier (e.g. `"com.apple.CoreSimulator.SimDeviceType.iPhone-15"`).
202    #[serde(rename = "deviceTypeIdentifier", default)]
203    pub device_type_identifier: String,
204    /// Runtime identifier this device was created against.
205    #[serde(rename = "runtimeIdentifier", default)]
206    pub runtime_identifier: String,
207}
208
209/// Permission names accepted by `xcrun simctl privacy <udid> grant <name>`.
210#[derive(Clone, Copy, Debug, PartialEq, Eq)]
211pub enum SimctlPermission {
212    /// Camera access.
213    Camera,
214    /// Photos library access.
215    Photos,
216    /// Location access (while-in-use).
217    Location,
218    /// Background location access (always).
219    LocationAlways,
220    /// Notification posting permission.
221    Notifications,
222    /// Microphone access.
223    Microphone,
224    /// Contacts access.
225    Contacts,
226    /// Calendar events access.
227    Calendar,
228    /// Reminders access.
229    Reminders,
230    /// Media library (music / video) access.
231    Media,
232    /// Motion / fitness sensor access.
233    Motion,
234    /// HomeKit accessory access.
235    HomeKit,
236    /// HealthKit data access.
237    Health,
238    /// Bluetooth device discovery / connection.
239    Bluetooth,
240    /// FaceID / TouchID biometric prompt.
241    Faceid,
242    /// Address-book (deprecated alias for `Contacts`).
243    AddressBook,
244}
245
246impl SimctlPermission {
247    /// Wire string used by `xcrun simctl privacy <udid> grant <name>`.
248    pub fn as_str(self) -> &'static str {
249        match self {
250            SimctlPermission::Camera => "camera",
251            SimctlPermission::Photos => "photos",
252            SimctlPermission::Location => "location",
253            SimctlPermission::LocationAlways => "location-always",
254            SimctlPermission::Notifications => "notifications",
255            SimctlPermission::Microphone => "microphone",
256            SimctlPermission::Contacts => "contacts",
257            SimctlPermission::Calendar => "calendar",
258            SimctlPermission::Reminders => "reminders",
259            SimctlPermission::Media => "media-library",
260            SimctlPermission::Motion => "motion",
261            SimctlPermission::HomeKit => "homekit",
262            SimctlPermission::Health => "health",
263            SimctlPermission::Bluetooth => "bluetooth",
264            SimctlPermission::Faceid => "faceid",
265            SimctlPermission::AddressBook => "addressbook",
266        }
267    }
268}
269
270/// UI appearance mode for `xcrun simctl ui <udid> appearance`.
271#[derive(Clone, Copy, Debug, PartialEq, Eq)]
272pub enum Appearance {
273    /// Light mode.
274    Light,
275    /// Dark mode.
276    Dark,
277}
278
279impl Appearance {
280    /// Wire string used by `xcrun simctl ui <udid> appearance <mode>`.
281    pub fn as_str(self) -> &'static str {
282        match self {
283            Appearance::Light => "light",
284            Appearance::Dark => "dark",
285        }
286    }
287}
288
289/// Launched-app result.
290#[derive(Clone, Debug, PartialEq, Eq)]
291pub struct LaunchResult {
292    /// Process ID of the launched app.
293    pub pid: u32,
294}
295
296// -------------------- subprocess ring buffer ----------------------------
297
298/// Recorded snapshot of one `xcrun simctl` invocation.
299/// Exposed so callers can dump the ring buffer for post-mortem when
300/// something upstream fails.
301#[derive(Clone, Debug)]
302pub struct SubprocessRecord {
303    /// argv as passed to `xcrun simctl` (excludes the `xcrun simctl`
304    /// prefix; first entry is the subcommand).
305    pub argv: Vec<String>,
306    /// Exit code; `None` when the process failed to spawn or the
307    /// output-capture path failed before recording the exit.
308    pub exit_code: Option<i32>,
309    /// Wall-clock milliseconds.
310    pub wall_ms: u64,
311    /// First 256 bytes of stderr (truncated).
312    pub stderr_head: String,
313    /// Wall-clock timestamp the invocation completed.
314    pub timestamp: std::time::SystemTime,
315}
316
317/// The three diagnostic records smix keeps between runs.
318///
319/// All three were the same shape and the same two bugs: a write of
320/// `let _ = write_json_atomic(...)`, which could not tell a full disk
321/// from a success, and a read of `let Ok(x) = .. else { return }`,
322/// which read a damaged file as an empty one and then overwrote it.
323///
324/// The swallowing had half a reason — persisting a diagnostic must not
325/// break the `xcrun simctl` call the user actually asked for. That
326/// reason survives here: failures are reported, never propagated. What
327/// does not survive is the silence.
328mod diag_store {
329    use std::path::{Path, PathBuf};
330    use std::sync::{Mutex, OnceLock};
331
332    /// Read a singleton from disk the first time someone needs it.
333    ///
334    /// The three diagnostic singletons used to load at startup: every
335    /// smix command called all three `set_*_persist_path` functions,
336    /// and each one read its value immediately. Measured with a
337    /// backtrace probe on `Store::open`, a plain `smix sim list` opened
338    /// the store four times — three eager loads plus the one write the
339    /// command actually needed. Two of those three were for state that
340    /// command never touches: it runs no flow and resets no app data.
341    ///
342    /// Each open replays the AOF and takes the store's *blocking*
343    /// advisory lock, so the cost is not only work — it is three extra
344    /// chances to queue behind another smix process for nothing.
345    ///
346    /// The flag is only latched once a path exists. A read that happens
347    /// before `set_persist_path` must leave it alone: latching there
348    /// would mean the path, once set, is never read at all — the load
349    /// would be permanently skipped rather than merely deferred.
350    pub(super) fn ensure_loaded(
351        flag: &'static OnceLock<Mutex<bool>>,
352        persist: &'static Mutex<Option<PathBuf>>,
353        load: fn(),
354    ) {
355        let mut done = match flag.get_or_init(|| Mutex::new(false)).lock() {
356            Ok(g) => g,
357            Err(poisoned) => poisoned.into_inner(),
358        };
359        if *done {
360            return;
361        }
362        let has_path = match persist.lock() {
363            Ok(g) => g.is_some(),
364            Err(poisoned) => poisoned.into_inner().is_some(),
365        };
366        if !has_path {
367            return;
368        }
369        load();
370        *done = true;
371    }
372
373    /// Resolve a caller-supplied path to the store root.
374    ///
375    /// Callers pass what used to be a JSON file path. Keeping their
376    /// signatures means the CLI wiring in `main.rs` does not move.
377    pub(super) fn root_of(path: &Path) -> std::path::PathBuf {
378        if path.extension().is_some_and(|e| e == "json") {
379            path.parent().unwrap_or(path).to_path_buf()
380        } else {
381            path.to_path_buf()
382        }
383    }
384
385    /// Read one diagnostic singleton.
386    ///
387    /// A value that will not parse is reported and treated as absent —
388    /// the caller has nothing better to do with it — but it is reported,
389    /// where before it vanished.
390    pub(super) fn load<T: serde::de::DeserializeOwned>(
391        path: &Path,
392        name: &'static str,
393    ) -> Option<T> {
394        let store = match smix_store::Store::open(&root_of(path)) {
395            Ok(s) => s,
396            Err(e) => {
397                eprintln!("smix: read {name}: {e}");
398                return None;
399            }
400        };
401        match store.singleton(name).get_json::<T>() {
402            Ok(v) => v,
403            Err(e) => {
404                eprintln!("smix: read {name}: {e}");
405                None
406            }
407        }
408    }
409
410    /// Write one diagnostic singleton, without making the caller wait.
411    ///
412    /// `try_open` rather than `open`: this runs after every simctl
413    /// invocation, and a diagnostic must never queue behind another
414    /// smix process. Busy means skip — the next call persists, which is
415    /// what the best-effort comment here always promised.
416    pub(super) fn store<T: serde::Serialize>(path: &Path, name: &'static str, value: &T) {
417        match smix_store::Store::try_open(&root_of(path)) {
418            Ok(None) => {}
419            Ok(Some(store)) => {
420                if let Err(e) = store.singleton(name).put_json(value) {
421                    eprintln!("smix: persist {name}: {e}");
422                } else if let Err(e) = store.sync() {
423                    eprintln!("smix: persist {name}: {e}");
424                }
425            }
426            Err(e) => eprintln!("smix: persist {name}: {e}"),
427        }
428    }
429}
430
431mod subprocess_ring {
432    use super::SubprocessRecord;
433    use std::collections::VecDeque;
434    use std::path::PathBuf;
435    use std::sync::{Mutex, OnceLock};
436    use std::time::{Duration, UNIX_EPOCH};
437
438    fn cell() -> &'static Mutex<VecDeque<SubprocessRecord>> {
439        static INSTANCE: OnceLock<Mutex<VecDeque<SubprocessRecord>>> = OnceLock::new();
440        INSTANCE.get_or_init(|| Mutex::new(VecDeque::with_capacity(128)))
441    }
442
443    /// Persist path for the ring buffer. `None` = in-memory only. Set
444    /// once at process startup via [`set_persist_path`]; unchanged for
445    /// the lifetime of the process.
446    ///
447    /// Persistence matters because supervisor cycles can kill the CLI
448    /// faster than a `/diagnostic/dump` can snapshot the in-memory
449    /// buffer, yielding empty payloads. The file survives cycles, so
450    /// post-mortem tools read it rather than the (now-gone) in-memory
451    /// state.
452    fn persist_cell() -> &'static Mutex<Option<PathBuf>> {
453        static INSTANCE: OnceLock<Mutex<Option<PathBuf>>> = OnceLock::new();
454        INSTANCE.get_or_init(|| Mutex::new(None))
455    }
456
457    /// Install a persist path. The stored value is read on first use,
458    /// not here — see [`super::diag_store::ensure_loaded`] for why the
459    /// eager version cost every command three store opens.
460    pub fn set_persist_path(path: PathBuf) {
461        let mut g = match persist_cell().lock() {
462            Ok(g) => g,
463            Err(p) => p.into_inner(),
464        };
465        *g = Some(path);
466    }
467
468    fn loaded_flag() -> &'static OnceLock<Mutex<bool>> {
469        static INSTANCE: OnceLock<Mutex<bool>> = OnceLock::new();
470        &INSTANCE
471    }
472
473    fn ensure_loaded() {
474        super::diag_store::ensure_loaded(loaded_flag(), persist_cell(), load_persisted);
475    }
476
477    fn persist_path_copy() -> Option<PathBuf> {
478        let g = match persist_cell().lock() {
479            Ok(g) => g,
480            Err(p) => p.into_inner(),
481        };
482        g.clone()
483    }
484
485    /// Record one invocation. Ring buffer capped at 128
486    /// entries; oldest evicted on push. When [`set_persist_path`] is
487    /// active, atomically writes the buffer to disk after the mutation
488    /// so a subsequent supervisor-cycle doesn't lose the observation.
489    pub(super) fn record(entry: SubprocessRecord) {
490        ensure_loaded();
491        {
492            let mut g = match cell().lock() {
493                Ok(g) => g,
494                Err(p) => p.into_inner(),
495            };
496            if g.len() >= 128 {
497                g.pop_front();
498            }
499            g.push_back(entry);
500        }
501        if let Some(path) = persist_path_copy() {
502            let snapshot: Vec<PersistedRecord> = snapshot().into_iter().map(Into::into).collect();
503            // Best-effort in the sense that matters: failure never
504            // affects the caller of `xcrun simctl`. It is no longer
505            // best-effort in the sense of being invisible.
506            super::diag_store::store(&path, "subprocess-ring", &snapshot);
507        }
508    }
509
510    /// Snapshot the current ring buffer. Ordered oldest → newest.
511    pub fn snapshot() -> Vec<SubprocessRecord> {
512        ensure_loaded();
513        let g = match cell().lock() {
514            Ok(g) => g,
515            Err(p) => p.into_inner(),
516        };
517        g.iter().cloned().collect()
518    }
519
520    /// Load a previously-persisted ring from disk. No-op
521    /// when the file does not exist. Called by CLI startup after
522    /// [`set_persist_path`] so the in-memory view starts with the
523    /// last-known state. Silently drops parse failures — corrupt files
524    /// are noise, not fatal.
525    pub fn load_persisted() {
526        let Some(path) = persist_path_copy() else {
527            return;
528        };
529        let Some(records) =
530            super::diag_store::load::<Vec<PersistedRecord>>(&path, "subprocess-ring")
531        else {
532            return;
533        };
534        let mut g = match cell().lock() {
535            Ok(g) => g,
536            Err(p) => p.into_inner(),
537        };
538        for r in records.into_iter().rev().take(128).rev() {
539            g.push_back(r.into_record());
540        }
541    }
542
543    /// On-disk representation. Kept separate from
544    /// [`SubprocessRecord`] because the wall-clock timestamp is a
545    /// `SystemTime` which does not serde-derive cleanly; we convert to
546    /// UNIX millis for a stable JSON shape.
547    #[derive(Clone, serde::Serialize, serde::Deserialize)]
548    struct PersistedRecord {
549        argv: Vec<String>,
550        exit_code: Option<i32>,
551        wall_ms: u64,
552        stderr_head: String,
553        timestamp_ms: u64,
554    }
555
556    impl From<SubprocessRecord> for PersistedRecord {
557        fn from(r: SubprocessRecord) -> Self {
558            let timestamp_ms = r
559                .timestamp
560                .duration_since(UNIX_EPOCH)
561                .map(|d| d.as_millis() as u64)
562                .unwrap_or(0);
563            Self {
564                argv: r.argv,
565                exit_code: r.exit_code,
566                wall_ms: r.wall_ms,
567                stderr_head: r.stderr_head,
568                timestamp_ms,
569            }
570        }
571    }
572
573    impl PersistedRecord {
574        fn into_record(self) -> SubprocessRecord {
575            let timestamp = UNIX_EPOCH + Duration::from_millis(self.timestamp_ms);
576            SubprocessRecord {
577                argv: self.argv,
578                exit_code: self.exit_code,
579                wall_ms: self.wall_ms,
580                stderr_head: self.stderr_head,
581                timestamp,
582            }
583        }
584    }
585
586    #[cfg(test)]
587    mod tests {
588        use super::*;
589        use std::time::SystemTime;
590
591        #[test]
592        fn persist_roundtrip_after_supervisor_cycle_simulation() {
593            let dir = tempfile::tempdir().expect("tempdir");
594            let path = dir.path().join("ring.json");
595            set_persist_path(path.clone());
596
597            record(SubprocessRecord {
598                argv: vec!["shutdown".into(), "UDID-A".into()],
599                exit_code: Some(0),
600                wall_ms: 42,
601                stderr_head: String::new(),
602                timestamp: SystemTime::now(),
603            });
604            // The property that matters is survival across a restart,
605            // not which file holds it — asserting the filename made this
606            // test a check on the implementation the record moved out of.
607
608            // Simulate supervisor cycle: clear in-memory then load.
609            {
610                let mut g = cell().lock().unwrap();
611                g.clear();
612            }
613            assert!(snapshot().is_empty());
614
615            load_persisted();
616            let after = snapshot();
617            assert_eq!(after.len(), 1);
618            assert_eq!(after[0].argv, vec!["shutdown".to_string(), "UDID-A".into()]);
619            assert_eq!(after[0].exit_code, Some(0));
620            assert_eq!(after[0].wall_ms, 42);
621        }
622    }
623}
624
625/// Enable subprocess-ring persistence at the given path.
626/// CLI startup wires this to `~/.local/share/smix/subprocess-ring.json`
627/// so `/diagnostic/dump` payloads survive supervisor cycles. Optional;
628/// without this call the ring stays in-memory only.
629pub fn set_subprocess_ring_persist_path(path: std::path::PathBuf) {
630    subprocess_ring::set_persist_path(path);
631    // No eager read here: the value is loaded the first time
632    // something actually uses it. Loading all three at startup cost
633    // every command three store opens, each one an AOF replay and a
634    // blocking lock, for state most commands never touch.
635}
636
637// CLI-side resetAppData counter tracking.
638//
639// The `resetAppData` verb dispatches host-side (simctl openurl + metro
640// log tail, no runner HTTP endpoint) so counters can't come from the
641// runner's `/diagnostic/dump` payload. This module owns them,
642// persisting to `~/.local/share/smix/reset-app-data-counters.json`
643// so counter deltas across `smix run` invocations + `smix diagnostic
644// dump` (later, separate process) all see the same data.
645//
646// Public API mirrors [`subprocess_ring`] shape for consistency.
647mod reset_app_data_counters {
648    use std::path::PathBuf;
649    use std::sync::{Mutex, OnceLock};
650
651    fn cell() -> &'static Mutex<Counters> {
652        static INSTANCE: OnceLock<Mutex<Counters>> = OnceLock::new();
653        INSTANCE.get_or_init(|| Mutex::new(Counters::default()))
654    }
655    fn persist_cell() -> &'static Mutex<Option<PathBuf>> {
656        static INSTANCE: OnceLock<Mutex<Option<PathBuf>>> = OnceLock::new();
657        INSTANCE.get_or_init(|| Mutex::new(None))
658    }
659
660    #[derive(Clone, Copy, Debug, Default, serde::Serialize, serde::Deserialize)]
661    pub struct Counters {
662        pub reset_app_data_total: u64,
663        pub reset_app_data_timed_out: u64,
664    }
665
666    pub fn set_persist_path(path: PathBuf) {
667        let mut g = match persist_cell().lock() {
668            Ok(g) => g,
669            Err(p) => p.into_inner(),
670        };
671        *g = Some(path);
672    }
673
674    fn loaded_flag() -> &'static OnceLock<Mutex<bool>> {
675        static INSTANCE: OnceLock<Mutex<bool>> = OnceLock::new();
676        &INSTANCE
677    }
678
679    fn ensure_loaded() {
680        super::diag_store::ensure_loaded(loaded_flag(), persist_cell(), load_persisted);
681    }
682
683    fn persist_path_copy() -> Option<PathBuf> {
684        let g = match persist_cell().lock() {
685            Ok(g) => g,
686            Err(p) => p.into_inner(),
687        };
688        g.clone()
689    }
690
691    pub fn load_persisted() {
692        let Some(path) = persist_path_copy() else {
693            return;
694        };
695        let Some(loaded) = super::diag_store::load::<Counters>(&path, "reset-app-data-counters")
696        else {
697            return;
698        };
699        let mut g = match cell().lock() {
700            Ok(g) => g,
701            Err(p) => p.into_inner(),
702        };
703        *g = loaded;
704    }
705
706    pub fn increment_total() {
707        ensure_loaded();
708        {
709            let mut g = match cell().lock() {
710                Ok(g) => g,
711                Err(p) => p.into_inner(),
712            };
713            g.reset_app_data_total = g.reset_app_data_total.saturating_add(1);
714        }
715        persist_best_effort();
716    }
717
718    pub fn increment_timed_out() {
719        ensure_loaded();
720        {
721            let mut g = match cell().lock() {
722                Ok(g) => g,
723                Err(p) => p.into_inner(),
724            };
725            g.reset_app_data_timed_out = g.reset_app_data_timed_out.saturating_add(1);
726        }
727        persist_best_effort();
728    }
729
730    pub fn snapshot() -> Counters {
731        ensure_loaded();
732        let g = match cell().lock() {
733            Ok(g) => g,
734            Err(p) => p.into_inner(),
735        };
736        *g
737    }
738
739    fn persist_best_effort() {
740        let Some(path) = persist_path_copy() else {
741            return;
742        };
743        let snapshot = snapshot();
744        super::diag_store::store(&path, "reset-app-data-counters", &snapshot);
745    }
746
747    #[cfg(test)]
748    mod tests {
749        use super::*;
750
751        #[test]
752        fn increment_and_persist_roundtrip() {
753            let dir = tempfile::tempdir().expect("tempdir");
754            let path = dir.path().join("counters.json");
755            set_persist_path(path.clone());
756            // Reset in-memory to avoid cross-test pollution.
757            {
758                let mut g = cell().lock().unwrap();
759                *g = Counters::default();
760            }
761            increment_total();
762            increment_total();
763            increment_timed_out();
764            // Read it back the way a restarted process would, rather
765            // than by opening a file whose path is no longer the
766            // contract.
767            {
768                let mut g = cell().lock().unwrap();
769                *g = Counters::default();
770            }
771            load_persisted();
772            let loaded = snapshot();
773            assert_eq!(loaded.reset_app_data_total, 2);
774            assert_eq!(loaded.reset_app_data_timed_out, 1);
775        }
776    }
777}
778
779/// Public snapshot of CLI-side resetAppData counter state. Populated by [`increment_reset_app_data_total`] +
780/// [`increment_reset_app_data_timed_out`] as the CLI dispatches the
781/// verb; loaded from disk on CLI startup if
782/// [`set_reset_app_data_counters_persist_path`] was called.
783#[derive(Clone, Copy, Debug, Default)]
784pub struct ResetAppDataCounters {
785    /// Total resetAppData dispatches (any outcome).
786    pub reset_app_data_total: u64,
787    /// resetAppData dispatches where the completion signal did not
788    /// arrive inside the timeout window. `> 0` = the URL was fired
789    /// but the app did not emit the expected reset-complete log line.
790    pub reset_app_data_timed_out: u64,
791}
792
793/// Enable resetAppData counter persistence at the given path. Callers pass
794/// `~/.local/share/smix/reset-app-data-counters.json` at CLI startup
795/// so counter state survives across `smix run` → `smix diagnostic
796/// dump` invocations.
797pub fn set_reset_app_data_counters_persist_path(path: std::path::PathBuf) {
798    reset_app_data_counters::set_persist_path(path);
799    // No eager read here: the value is loaded the first time
800    // something actually uses it. Loading all three at startup cost
801    // every command three store opens, each one an AOF replay and a
802    // blocking lock, for state most commands never touch.
803}
804
805/// Advance the resetAppData total counter.
806/// Called by the CLI runtime after each dispatch (success or timeout).
807pub fn increment_reset_app_data_total() {
808    reset_app_data_counters::increment_total();
809}
810
811/// Advance the resetAppData timed-out counter.
812/// Called by the CLI runtime when the completion signal (log-line
813/// pattern match) did not arrive inside the timeout window. Always
814/// paired with a preceding [`increment_reset_app_data_total`] on the
815/// same dispatch.
816pub fn increment_reset_app_data_timed_out() {
817    reset_app_data_counters::increment_timed_out();
818}
819
820/// Snapshot the current counter state for display / wire emission. Returns zero-valued counters when
821/// persistence was never wired.
822pub fn reset_app_data_counters_snapshot() -> ResetAppDataCounters {
823    let s = reset_app_data_counters::snapshot();
824    ResetAppDataCounters {
825        reset_app_data_total: s.reset_app_data_total,
826        reset_app_data_timed_out: s.reset_app_data_timed_out,
827    }
828}
829
830// Flow-attempt persistence for retry attribution. Called by `smix run`
831// after each flow completes (all its attempts done); read by
832// `smix diagnostic dump` to render the attribution table.
833// One record per flow, under `attempt:<flowName>`, written while this
834// process holds the store's own lock.
835//
836// It was a single machine-global blob rewritten whole, on a write that
837// skipped itself when another smix held the lock. `smix run` records
838// once and exits, so "the next attempt will persist" was never true:
839// a busy neighbour meant the record simply did not exist — and the gate
840// that reads these back cannot tell that from a flow that never ran.
841mod flow_attempts {
842    use serde::{Deserialize, Serialize};
843    use std::collections::BTreeMap;
844    use std::path::PathBuf;
845    use std::sync::{Mutex, OnceLock};
846    use std::time::{SystemTime, UNIX_EPOCH};
847
848    /// Enough history to diagnose a batch or two while keeping the dump
849    /// snapshot cheap to serialize.
850    const MAX_PERSISTED_FLOWS: usize = 32;
851
852    #[derive(Clone, Debug, Serialize, Deserialize)]
853    pub struct PersistedAttempt {
854        pub attempt_index: u32,
855        pub status: String,
856        pub error_class: Option<String>,
857        pub ips_generated: Option<String>,
858        pub wall_ms: u64,
859    }
860
861    #[derive(Clone, Debug, Serialize, Deserialize)]
862    pub struct PersistedFlow {
863        pub flow_name: String,
864        pub attempts: Vec<PersistedAttempt>,
865        /// `serde(default)` is load-bearing: the blob written before
866        /// this field existed has no such key, and without a default the
867        /// merge in [`snapshot`] would call that history corrupt —
868        /// losing it to the very change that exists to keep it.
869        #[serde(default)]
870        pub recorded_at_ms: u64,
871    }
872
873    fn persist_cell() -> &'static Mutex<Option<PathBuf>> {
874        static INSTANCE: OnceLock<Mutex<Option<PathBuf>>> = OnceLock::new();
875        INSTANCE.get_or_init(|| Mutex::new(None))
876    }
877
878    pub fn set_persist_path(path: PathBuf) {
879        let mut g = match persist_cell().lock() {
880            Ok(g) => g,
881            Err(p) => p.into_inner(),
882        };
883        *g = Some(path);
884    }
885
886    fn persist_path_copy() -> Option<PathBuf> {
887        let g = match persist_cell().lock() {
888            Ok(g) => g,
889            Err(p) => p.into_inner(),
890        };
891        g.clone()
892    }
893
894    fn now_ms() -> u64 {
895        SystemTime::now()
896            .duration_since(UNIX_EPOCH)
897            .map_or(0, |d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX))
898    }
899
900    /// Blocking, not best-effort. Waiting a few milliseconds behind a
901    /// neighbour is the price of the record existing at all.
902    fn open() -> Option<smix_store::Store> {
903        let path = persist_path_copy()?;
904        match smix_store::Store::open(&super::diag_store::root_of(&path)) {
905            Ok(store) => Some(store),
906            Err(e) => {
907                eprintln!("smix: flow-attempts: {e}");
908                None
909            }
910        }
911    }
912
913    pub fn record(flow_name: &str, attempts: &[PersistedAttempt]) {
914        let Some(store) = open() else {
915            return;
916        };
917        let flow = PersistedFlow {
918            flow_name: flow_name.to_string(),
919            attempts: attempts.to_vec(),
920            recorded_at_ms: now_ms(),
921        };
922        if let Err(e) = store.attempts().put_json(flow_name, &flow) {
923            eprintln!("smix: persist flow-attempts: {e}");
924            return;
925        }
926        trim(&store);
927        if let Err(e) = store.sync() {
928            eprintln!("smix: persist flow-attempts: {e}");
929        }
930    }
931
932    /// Under the lock [`record`] already holds. Opening the store again
933    /// here would be a second read-modify-write window — the shape this
934    /// module exists to no longer have.
935    fn trim(store: &smix_store::Store) {
936        let ns = store.attempts();
937        let mut dated: Vec<(u64, String)> = Vec::new();
938        for id in ns.list() {
939            match ns.get_json::<PersistedFlow>(&id) {
940                Ok(Some(flow)) => dated.push((flow.recorded_at_ms, id)),
941                Ok(None) => {}
942                // Unreadable is not a candidate for eviction: deleting it
943                // erases the evidence of whatever wrote it.
944                Err(e) => eprintln!("smix: read flow-attempts {id}: {e}"),
945            }
946        }
947        let Some(excess) = dated.len().checked_sub(MAX_PERSISTED_FLOWS) else {
948            return;
949        };
950        if excess == 0 {
951            return;
952        }
953        dated.sort();
954        for (_, id) in dated.into_iter().take(excess) {
955            if let Err(e) = ns.delete(&id) {
956                eprintln!("smix: trim flow-attempts {id}: {e}");
957            }
958        }
959    }
960
961    pub fn snapshot() -> Vec<PersistedFlow> {
962        let Some(store) = open() else {
963            return Vec::new();
964        };
965        let mut by_name: BTreeMap<String, PersistedFlow> = BTreeMap::new();
966        // The blob this used to be: read, never rewritten. Migrating it
967        // would mean writing a whole blob again, which is the thing that
968        // lost records in the first place.
969        match store
970            .singleton("flow-attempts")
971            .get_json::<Vec<PersistedFlow>>()
972        {
973            Ok(Some(old)) => {
974                for flow in old {
975                    by_name.insert(flow.flow_name.clone(), flow);
976                }
977            }
978            Ok(None) => {}
979            Err(e) => eprintln!("smix: read flow-attempts: {e}"),
980        }
981        let ns = store.attempts();
982        for id in ns.list() {
983            match ns.get_json::<PersistedFlow>(&id) {
984                Ok(Some(flow)) => {
985                    by_name.insert(flow.flow_name.clone(), flow);
986                }
987                Ok(None) => {}
988                Err(e) => eprintln!("smix: read flow-attempts {id}: {e}"),
989            }
990        }
991        let mut flows: Vec<PersistedFlow> = by_name.into_values().collect();
992        flows.sort_by(|a, b| {
993            a.recorded_at_ms
994                .cmp(&b.recorded_at_ms)
995                .then_with(|| a.flow_name.cmp(&b.flow_name))
996        });
997        flows
998    }
999}
1000
1001/// Enable flow-attempts persistence at the given path.
1002/// CLI startup wires this to `~/.local/share/smix/flow-attempts.json`
1003/// so retry attribution survives across `smix run` → `smix diagnostic
1004/// dump` invocations.
1005pub fn set_flow_attempts_persist_path(path: std::path::PathBuf) {
1006    flow_attempts::set_persist_path(path);
1007    // No eager read here: the value is loaded the first time
1008    // something actually uses it. Loading all three at startup cost
1009    // every command three store opens, each one an AOF replay and a
1010    // blocking lock, for state most commands never touch.
1011}
1012
1013/// Public accessor with just the fields needed by callers.
1014/// Mirrors [`smix_runner_wire::FlowAttempt`] shape.
1015#[derive(Clone, Debug)]
1016pub struct FlowAttemptData {
1017    /// Zero-based retry index.
1018    pub attempt_index: u32,
1019    /// Overall outcome ("ok" / "timeout" / "error" / "crashed").
1020    pub status: String,
1021    /// Free-form error class code (`Some` on non-ok).
1022    pub error_class: Option<String>,
1023    /// `.ips` filename that appeared during this attempt, when detected.
1024    pub ips_generated: Option<String>,
1025    /// Wall-clock milliseconds.
1026    pub wall_ms: u64,
1027}
1028
1029/// Recorded flow with its attempt list.
1030#[derive(Clone, Debug)]
1031pub struct FlowAttemptRecordData {
1032    /// Flow name (yaml basename or explicit id).
1033    pub flow_name: String,
1034    /// Ordered attempts, first try first.
1035    pub attempts: Vec<FlowAttemptData>,
1036}
1037
1038/// Record the outcome of a flow's attempts. Called from
1039/// `smix run` after all retries for that flow have completed. `smix
1040/// diagnostic dump` reads via [`recent_flow_attempts`] later.
1041pub fn record_flow_attempts<A>(flow_name: &str, attempts: &[A])
1042where
1043    A: FlowAttemptShape,
1044{
1045    let converted: Vec<flow_attempts::PersistedAttempt> = attempts
1046        .iter()
1047        .map(|a| flow_attempts::PersistedAttempt {
1048            attempt_index: a.attempt_index(),
1049            status: a.status().to_string(),
1050            error_class: a.error_class().map(str::to_string),
1051            ips_generated: a.ips_generated().map(str::to_string),
1052            wall_ms: a.wall_ms(),
1053        })
1054        .collect();
1055    flow_attempts::record(flow_name, &converted);
1056}
1057
1058/// Abstraction so callers pass either
1059/// [`smix_runner_wire::FlowAttempt`] or a local struct with the same
1060/// shape without a cross-crate dep on smix-runner-wire from smix-simctl.
1061pub trait FlowAttemptShape {
1062    /// Zero-based retry index.
1063    fn attempt_index(&self) -> u32;
1064    /// "ok" / "timeout" / "error" / "crashed".
1065    fn status(&self) -> &str;
1066    /// Error class code, if any.
1067    fn error_class(&self) -> Option<&str>;
1068    /// `.ips` filename attributable to this attempt, if any.
1069    fn ips_generated(&self) -> Option<&str>;
1070    /// Wall-clock milliseconds.
1071    fn wall_ms(&self) -> u64;
1072}
1073
1074/// Snapshot recent flow attempts for display / wire
1075/// emission. Returns empty when persistence was never wired.
1076pub fn recent_flow_attempts() -> Vec<FlowAttemptRecordData> {
1077    flow_attempts::snapshot()
1078        .into_iter()
1079        .map(|f| FlowAttemptRecordData {
1080            flow_name: f.flow_name,
1081            attempts: f
1082                .attempts
1083                .into_iter()
1084                .map(|a| FlowAttemptData {
1085                    attempt_index: a.attempt_index,
1086                    status: a.status,
1087                    error_class: a.error_class,
1088                    ips_generated: a.ips_generated,
1089                    wall_ms: a.wall_ms,
1090                })
1091                .collect(),
1092        })
1093        .collect()
1094}
1095
1096/// Snapshot the process-wide ring buffer of recent
1097/// `xcrun simctl` invocations. Ordered oldest → newest, capped at 128
1098/// entries. Reset on process restart.
1099pub fn recent_subprocesses() -> Vec<SubprocessRecord> {
1100    subprocess_ring::snapshot()
1101}
1102
1103// -------------------- raw spawn primitive --------------------------------
1104
1105/// Execute `xcrun simctl <args>` and capture stdout/stderr.
1106async fn simctl_capture(args: &[&str]) -> Result<(Vec<u8>, String), DeviceControlError> {
1107    simctl_capture_env(args, &[]).await
1108}
1109
1110/// `simctl_capture` with extra envp pairs set on the spawned process.
1111/// The `xcrun simctl launch` subcommand uses this to inject
1112/// `SIMCTL_CHILD_<KEY>=<VAL>` vars that the launched app sees as
1113/// `ProcessInfo().environment["KEY"]`. `env` entries here are passed
1114/// verbatim — caller composes the `SIMCTL_CHILD_` prefix via
1115/// [`compose_child_env`].
1116async fn simctl_capture_env(
1117    args: &[&str],
1118    env: &[(String, String)],
1119) -> Result<(Vec<u8>, String), DeviceControlError> {
1120    let mut cmd = Command::new("xcrun");
1121    cmd.arg("simctl");
1122    for a in args {
1123        cmd.arg(a);
1124    }
1125    for (k, v) in env {
1126        cmd.env(k, v);
1127    }
1128    let started = std::time::Instant::now();
1129    let output = cmd.output().await?;
1130    let wall_ms = started.elapsed().as_millis() as u64;
1131    let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
1132    // Every simctl invocation records to the ring buffer regardless of
1133    // exit status.
1134    subprocess_ring::record(SubprocessRecord {
1135        argv: std::iter::once("xcrun".to_string())
1136            .chain(std::iter::once("simctl".to_string()))
1137            .chain(args.iter().map(|s| s.to_string()))
1138            .collect(),
1139        exit_code: output.status.code(),
1140        wall_ms,
1141        stderr_head: {
1142            let mut s = stderr.clone();
1143            if s.len() > 256 {
1144                s.truncate(256);
1145            }
1146            s
1147        },
1148        timestamp: std::time::SystemTime::now(),
1149    });
1150    if !output.status.success() {
1151        return Err(DeviceControlError::NonZeroExit {
1152            subcommand: args.first().map(|s| s.to_string()).unwrap_or_default(),
1153            argv: std::iter::once("xcrun".to_string())
1154                .chain(std::iter::once("simctl".to_string()))
1155                .chain(args.iter().map(|s| s.to_string()))
1156                .collect(),
1157            code: output.status.code().unwrap_or(-1),
1158            stderr,
1159            wall_ms,
1160        });
1161    }
1162    Ok((output.stdout, stderr))
1163}
1164
1165async fn simctl_run(args: &[&str]) -> Result<String, DeviceControlError> {
1166    let (stdout, _) = simctl_capture(args).await?;
1167    Ok(String::from_utf8_lossy(&stdout).into_owned())
1168}
1169
1170/// Like [`simctl_run`] but injects `child_env` envp on the spawned
1171/// process. Used by the env-aware launch path so the launched app can
1172/// read deploy-time secrets / endpoints via `ProcessInfo`.
1173async fn simctl_run_env(
1174    args: &[&str],
1175    env: &[(String, String)],
1176) -> Result<String, DeviceControlError> {
1177    let (stdout, _) = simctl_capture_env(args, env).await?;
1178    Ok(String::from_utf8_lossy(&stdout).into_owned())
1179}
1180
1181/// Compose user-provided `(key, value)` pairs into the `SIMCTL_CHILD_*`
1182/// envp that `xcrun simctl launch` strips and delivers to the launched
1183/// app. Idempotent: a key that already starts with `SIMCTL_CHILD_` is
1184/// passed through unchanged.
1185///
1186/// # Example
1187///
1188/// ```
1189/// use smix_simctl::compose_child_env;
1190/// let composed = compose_child_env(&[("SMIX_PERF_RECEIVER_URL", "http://h:9999")]);
1191/// assert_eq!(
1192///     composed,
1193///     vec![(
1194///         "SIMCTL_CHILD_SMIX_PERF_RECEIVER_URL".to_string(),
1195///         "http://h:9999".to_string(),
1196///     )]
1197/// );
1198/// ```
1199pub fn compose_child_env(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
1200    pairs
1201        .iter()
1202        .map(|(k, v)| {
1203            let key = if k.starts_with("SIMCTL_CHILD_") {
1204                (*k).to_string()
1205            } else {
1206                format!("SIMCTL_CHILD_{k}")
1207            };
1208            (key, (*v).to_string())
1209        })
1210        .collect()
1211}
1212
1213// -------------------- client --------------------------------------------
1214
1215/// Stateless wrapper around xcrun simctl. Methods are free functions
1216/// in spirit (no instance state beyond optionally-cached `xcrun` path);
1217/// kept as a struct for API ergonomics + future caching.
1218///
1219/// The client also holds a [`ScreenshotPacer`] that
1220/// throttles `xcrun simctl io screenshot` under high-frequency
1221/// load. Defaults are conservative (100 ms interval floor);
1222/// consumers whose flows are already loose are unaffected.
1223#[derive(Debug)]
1224pub struct SimctlClient {
1225    /// Screenshot pacer — enforces the interval floor, slow-path lift,
1226    /// and circuit breaker. Shared via `Arc<Mutex<_>>`
1227    /// so a cloned client (which callers occasionally do) still shares
1228    /// pressure accounting.
1229    screenshot_pacer: Arc<std::sync::Mutex<ScreenshotPacer>>,
1230    /// Resident per-UDID `smix-capture-host` processes for the direct
1231    /// IOSurface capture path. Shared so a cloned client reuses the same
1232    /// warm surfaces. See [`surface_capture`].
1233    capture_hosts: Arc<tokio::sync::Mutex<surface_capture::CaptureHostRegistry>>,
1234}
1235
1236impl Default for SimctlClient {
1237    fn default() -> Self {
1238        Self::new()
1239    }
1240}
1241
1242impl SimctlClient {
1243    /// Construct a new client with default screenshot pacing (100 ms
1244    /// interval floor, adaptive slow-path lift to 1500 ms, circuit
1245    /// breaker on ≥ 1500 ms walls or failures).
1246    pub fn new() -> Self {
1247        SimctlClient {
1248            screenshot_pacer: Arc::new(std::sync::Mutex::new(ScreenshotPacer::new(
1249                ScreenshotPacerConfig::default(),
1250            ))),
1251            capture_hosts: Arc::new(tokio::sync::Mutex::new(
1252                surface_capture::CaptureHostRegistry::default(),
1253            )),
1254        }
1255    }
1256
1257    /// Override the screenshot pacer with a custom config.
1258    ///
1259    /// Since smix 1.0.4.
1260    #[must_use]
1261    pub fn with_screenshot_pacer(self, config: ScreenshotPacerConfig) -> Self {
1262        {
1263            let mut guard = self
1264                .screenshot_pacer
1265                .lock()
1266                .expect("screenshot pacer mutex must not be poisoned");
1267            *guard = ScreenshotPacer::new(config);
1268        }
1269        self
1270    }
1271
1272    /// Attach a [`smix_sim_health::SimHealthMonitor`] to receive
1273    /// screenshot wall-time observations from every `screenshot`
1274    /// call. Composes with the pacer — the pacer still enforces its
1275    /// interval / circuit locally, and the monitor sees the same
1276    /// walls for global state classification.
1277    ///
1278    /// Since smix 1.0.4.
1279    #[must_use]
1280    pub fn with_sim_health(self, monitor: smix_sim_health::SimHealthMonitor) -> Self {
1281        {
1282            let mut guard = self
1283                .screenshot_pacer
1284                .lock()
1285                .expect("screenshot pacer mutex must not be poisoned");
1286            guard.set_monitor(monitor);
1287        }
1288        self
1289    }
1290
1291    // ---- inventory ------------------------------------------------------
1292
1293    /// `xcrun simctl list runtimes -j` → `Vec<SimctlRuntime>`.
1294    pub async fn list_runtimes(&self) -> Result<Vec<SimctlRuntime>, DeviceControlError> {
1295        let raw = simctl_run(&["list", "runtimes", "-j"]).await?;
1296        #[derive(Deserialize)]
1297        struct Wrap {
1298            runtimes: Vec<RawRuntime>,
1299        }
1300        #[derive(Deserialize)]
1301        struct RawRuntime {
1302            identifier: String,
1303            name: String,
1304            version: String,
1305            #[serde(rename = "isAvailable", default)]
1306            is_available: bool,
1307        }
1308        let w: Wrap = serde_json::from_str(&raw).map_err(|e| DeviceControlError::Malformed {
1309            subcommand: "list runtimes".into(),
1310            detail: e.to_string(),
1311        })?;
1312        Ok(w.runtimes
1313            .into_iter()
1314            .map(|r| SimctlRuntime {
1315                identifier: r.identifier,
1316                name: r.name,
1317                version: r.version,
1318                is_available: r.is_available,
1319            })
1320            .collect())
1321    }
1322
1323    /// `xcrun simctl list devices -j` → flattened `Vec<SimctlDevice>`.
1324    pub async fn list_devices(&self) -> Result<Vec<SimctlDevice>, DeviceControlError> {
1325        let raw = simctl_run(&["list", "devices", "-j"]).await?;
1326        #[derive(Deserialize)]
1327        struct Wrap {
1328            devices: std::collections::BTreeMap<String, Vec<RawDevice>>,
1329        }
1330        #[derive(Deserialize)]
1331        struct RawDevice {
1332            udid: String,
1333            name: String,
1334            state: String,
1335            #[serde(rename = "isAvailable", default)]
1336            is_available: bool,
1337            #[serde(rename = "deviceTypeIdentifier", default)]
1338            device_type_identifier: String,
1339        }
1340        let w: Wrap = serde_json::from_str(&raw).map_err(|e| DeviceControlError::Malformed {
1341            subcommand: "list devices".into(),
1342            detail: e.to_string(),
1343        })?;
1344        let mut out = Vec::new();
1345        for (runtime_id, devices) in w.devices {
1346            for d in devices {
1347                out.push(SimctlDevice {
1348                    udid: d.udid,
1349                    name: d.name,
1350                    state: d.state,
1351                    is_available: d.is_available,
1352                    device_type_identifier: d.device_type_identifier,
1353                    runtime_identifier: runtime_id.clone(),
1354                });
1355            }
1356        }
1357        Ok(out)
1358    }
1359
1360    // ---- lifecycle ------------------------------------------------------
1361
1362    /// `xcrun simctl boot <udid>` — fire-and-forget boot request.
1363    pub async fn boot(&self, udid: &str) -> Result<(), DeviceControlError> {
1364        simctl_run(&["boot", udid]).await?;
1365        Ok(())
1366    }
1367
1368    /// `xcrun simctl shutdown <udid>`.
1369    pub async fn shutdown(&self, udid: &str) -> Result<(), DeviceControlError> {
1370        simctl_run(&["shutdown", udid]).await?;
1371        Ok(())
1372    }
1373
1374    /// Read the sim's current BCP-47 locale (first entry of
1375    /// `NSGlobalDomain AppleLanguages`). Returns `Ok(None)` when the
1376    /// preference is unset (defaults read exits non-zero) or unparseable.
1377    /// Wire format: `simctl spawn <udid> defaults read -g AppleLanguages`
1378    /// stdout looks like `"(\n    \"en-US\"\n)\n"`; we extract the first
1379    /// quoted token.
1380    pub async fn current_locale(&self, udid: &str) -> Result<Option<String>, DeviceControlError> {
1381        let out = match simctl_run(&[
1382            "spawn",
1383            udid,
1384            "/usr/bin/defaults",
1385            "read",
1386            "-g",
1387            "AppleLanguages",
1388        ])
1389        .await
1390        {
1391            Ok(s) => s,
1392            // `defaults read` returns non-zero when the key is unset; that
1393            // is a legitimate "no opinion" state, not an error.
1394            Err(DeviceControlError::NonZeroExit { .. }) => return Ok(None),
1395            Err(e) => return Err(e),
1396        };
1397        // First quoted substring.
1398        if let Some(start) = out.find('"') {
1399            let rest = &out[start + 1..];
1400            if let Some(end) = rest.find('"') {
1401                return Ok(Some(rest[..end].to_string()));
1402            }
1403        }
1404        Ok(None)
1405    }
1406
1407    /// Delete a single key from an app's NSUserDefaults domain via
1408    /// `simctl spawn <udid> defaults delete <bundleId> <key>`.
1409    /// Running `defaults` INSIDE the sim (spawn) goes through
1410    /// the sim's cfprefsd, so the deletion is coherent with what the
1411    /// app reads on next launch (editing the container plist from the
1412    /// host would race cfprefsd's cache).
1413    ///
1414    /// Returns `Ok(true)` when the key existed and was deleted,
1415    /// `Ok(false)` when the key (or the whole domain) was absent —
1416    /// the verb contract is "ensure key absent", so an already-absent
1417    /// key is success, not an error. Any other failure surfaces as
1418    /// the underlying [`DeviceControlError`].
1419    ///
1420    /// Motivating case: expo-dev-launcher
1421    /// persists the most recent deep link and re-delivers it after
1422    /// every JS bundle load; deleting its storage key between
1423    /// terminate and relaunch neutralizes the replay at the source.
1424    ///
1425    /// **Terminate the app first** — a running process has its
1426    /// defaults cached in-memory and may rewrite the key at exit.
1427    pub async fn user_defaults_delete(
1428        &self,
1429        udid: &str,
1430        bundle_id: &str,
1431        key: &str,
1432    ) -> Result<bool, DeviceControlError> {
1433        match simctl_run(&["spawn", udid, "/usr/bin/defaults", "delete", bundle_id, key]).await {
1434            Ok(_) => Ok(true),
1435            // `defaults delete` exits non-zero with "does not exist"
1436            // on stderr for both a missing key and a missing domain.
1437            // Both are the target state.
1438            Err(DeviceControlError::NonZeroExit { stderr, .. })
1439                if stderr.contains("does not exist") =>
1440            {
1441                Ok(false)
1442            }
1443            Err(e) => Err(e),
1444        }
1445    }
1446
1447    /// Write `AppleLanguages` (array) + `AppleLocale` (scalar) to the
1448    /// sim's NSGlobalDomain so SpringBoard + apps re-localize on next
1449    /// launch. AppleLocale is BCP-47 with hyphen replaced by underscore
1450    /// (`en_US`); AppleLanguages is the BCP-47 tag verbatim.
1451    /// **The caller must shutdown + reboot the sim for the change to
1452    /// take effect** — running apps cache the locale at process start.
1453    pub async fn set_locale(&self, udid: &str, locale: &str) -> Result<(), DeviceControlError> {
1454        simctl_run(&[
1455            "spawn",
1456            udid,
1457            "/usr/bin/defaults",
1458            "write",
1459            "-g",
1460            "AppleLanguages",
1461            "-array",
1462            locale,
1463        ])
1464        .await?;
1465        let locale_underscore = locale.replace('-', "_");
1466        simctl_run(&[
1467            "spawn",
1468            udid,
1469            "/usr/bin/defaults",
1470            "write",
1471            "-g",
1472            "AppleLocale",
1473            &locale_underscore,
1474        ])
1475        .await?;
1476        Ok(())
1477    }
1478
1479    /// Boot + poll device state == "Booted" within timeout. Tries every
1480    /// 500 ms until success or `timeout_ms` elapses. Idempotent on
1481    /// already-booted devices (`xcrun simctl boot` returns non-zero when
1482    /// the device is already booted; we swallow that).
1483    pub async fn boot_and_wait(
1484        &self,
1485        udid: &str,
1486        timeout: Duration,
1487    ) -> Result<(), DeviceControlError> {
1488        // Issue boot; ignore already-booted error (the only friendly path).
1489        let _ = simctl_run(&["boot", udid]).await;
1490        let start = std::time::Instant::now();
1491        loop {
1492            let devices = self.list_devices().await?;
1493            if devices
1494                .iter()
1495                .any(|d| d.udid == udid && d.state == "Booted")
1496            {
1497                return Ok(());
1498            }
1499            if start.elapsed() > timeout {
1500                return Err(DeviceControlError::Timeout {
1501                    subcommand: format!("boot {}", udid),
1502                    ms: timeout.as_millis() as u64,
1503                });
1504            }
1505            sleep(Duration::from_millis(500)).await;
1506        }
1507    }
1508
1509    /// `xcrun simctl erase <udid>` — wipe device contents.
1510    pub async fn erase(&self, udid: &str) -> Result<(), DeviceControlError> {
1511        simctl_run(&["erase", udid]).await?;
1512        Ok(())
1513    }
1514
1515    /// `xcrun simctl install <udid> <app-path>` — install a `.app` bundle.
1516    pub async fn install(&self, udid: &str, app_path: &str) -> Result<(), DeviceControlError> {
1517        simctl_run(&["install", udid, app_path]).await?;
1518        Ok(())
1519    }
1520
1521    /// `xcrun simctl uninstall <udid> <bundle-id>`.
1522    pub async fn uninstall(&self, udid: &str, bundle_id: &str) -> Result<(), DeviceControlError> {
1523        simctl_run(&["uninstall", udid, bundle_id]).await?;
1524        Ok(())
1525    }
1526
1527    /// `xcrun simctl terminate <udid> <bundle-id>` — kill a running app.
1528    pub async fn terminate(&self, udid: &str, bundle_id: &str) -> Result<(), DeviceControlError> {
1529        simctl_run(&["terminate", udid, bundle_id]).await?;
1530        Ok(())
1531    }
1532
1533    /// `xcrun simctl launch <udid> <bundleId>` → parse `"<bundle>: <pid>"`.
1534    pub async fn launch(
1535        &self,
1536        udid: &str,
1537        bundle_id: &str,
1538    ) -> Result<LaunchResult, DeviceControlError> {
1539        self.launch_with_args(udid, bundle_id, &[]).await
1540    }
1541
1542    /// `xcrun simctl launch <udid> <bundleId> -- <arg>...` — launch with a
1543    /// process-level argument vector. Empty `args` is equivalent to
1544    /// [`Self::launch`]. Mirrors maestro yaml `launchApp.arguments`.
1545    pub async fn launch_with_args(
1546        &self,
1547        udid: &str,
1548        bundle_id: &str,
1549        args: &[String],
1550    ) -> Result<LaunchResult, DeviceControlError> {
1551        self.launch_with_args_and_env(udid, bundle_id, args, &[])
1552            .await
1553    }
1554
1555    /// Like [`Self::launch_with_args`] but also sets `SIMCTL_CHILD_*`
1556    /// envp on the simctl process so the launched app can read
1557    /// deploy-time vars via `ProcessInfo().environment["KEY"]`.
1558    /// `child_env` keys without the `SIMCTL_CHILD_` prefix get it added
1559    /// automatically (per [`compose_child_env`] semantics). Useful for
1560    /// prelaunching an app before any `openLink` so iOS treats the
1561    /// subsequent URL handoff as in-app routing instead of cross-app,
1562    /// side-stepping the SpringBoard "Open in '`<App>`'?" confirmation
1563    /// dialog.
1564    pub async fn launch_with_args_and_env(
1565        &self,
1566        udid: &str,
1567        bundle_id: &str,
1568        args: &[String],
1569        child_env: &[(&str, &str)],
1570    ) -> Result<LaunchResult, DeviceControlError> {
1571        let mut argv: Vec<&str> = vec!["launch", udid, bundle_id];
1572        if !args.is_empty() {
1573            argv.push("--");
1574            for a in args {
1575                argv.push(a.as_str());
1576            }
1577        }
1578        let composed = compose_child_env(child_env);
1579        let out = simctl_run_env(&argv, &composed).await?;
1580        // Output format: `com.example.app: 12345\n`
1581        let pid_str =
1582            out.rsplit(':')
1583                .next()
1584                .map(str::trim)
1585                .ok_or_else(|| DeviceControlError::Malformed {
1586                    subcommand: "launch".into(),
1587                    detail: format!("unexpected stdout shape: {}", out.trim()),
1588                })?;
1589        let pid: u32 = pid_str.parse().map_err(|_| DeviceControlError::Malformed {
1590            subcommand: "launch".into(),
1591            detail: format!("non-numeric pid in stdout: {}", out.trim()),
1592        })?;
1593        Ok(LaunchResult { pid })
1594    }
1595
1596    /// Reset every privacy permission granted to `bundle_id` on the
1597    /// sim: `xcrun simctl privacy <udid> reset all <bundle-id>`.
1598    /// Companion to [`Self::clear_app_sandbox`] on the in-place
1599    /// `launchApp: clearState: true` path, which replaces
1600    /// `simctl uninstall + install` — that pairing triggers iOS 26.5
1601    /// XCUITest binding loss plus a ReportCrash "<app> quit
1602    /// unexpectedly" dialog.
1603    pub async fn privacy_reset_all(
1604        &self,
1605        udid: &str,
1606        bundle_id: &str,
1607    ) -> Result<(), DeviceControlError> {
1608        simctl_run(&["privacy", udid, "reset", "all", bundle_id]).await?;
1609        Ok(())
1610    }
1611
1612    /// Wipe the app's sandbox on the sim: locate the
1613    /// Data container via `simctl get_app_container <udid> <bundle>
1614    /// data`, then `simctl spawn <udid> rm -rf <container>/Documents
1615    /// <container>/Library <container>/tmp`. The app remains installed
1616    /// (no `simctl uninstall`), so the XCUITest binding is preserved
1617    /// and macOS `ReportCrash` does not misinterpret a missing
1618    /// install-receipt as a crash.
1619    pub async fn clear_app_sandbox(
1620        &self,
1621        udid: &str,
1622        bundle_id: &str,
1623    ) -> Result<(), DeviceControlError> {
1624        let raw = simctl_run(&["get_app_container", udid, bundle_id, "data"])
1625            .await
1626            .map_err(|e| match e {
1627                // get_app_container failing IS "not installed" — the
1628                // subprocess text (`NSPOSIXErrorDomain code=2`) says
1629                // nothing a flow author can act on.
1630                DeviceControlError::NonZeroExit { .. } => DeviceControlError::AppNotInstalled {
1631                    bundle_id: bundle_id.to_string(),
1632                    udid: udid.to_string(),
1633                },
1634                other => other,
1635            })?;
1636        let container = raw.trim();
1637        if container.is_empty() {
1638            return Err(DeviceControlError::Malformed {
1639                subcommand: "clear_app_sandbox".into(),
1640                detail: format!("empty Data container path for bundle {bundle_id}"),
1641            });
1642        }
1643        let documents = format!("{container}/Documents");
1644        let library = format!("{container}/Library");
1645        let tmp = format!("{container}/tmp");
1646        // `xcrun simctl spawn <UDID> <cmd>` uses `posix_spawn` inside
1647        // the sim OS; `<cmd>` must be an absolute path (there is no
1648        // PATH resolution). A bare `"rm"` fails with
1649        // `NSPOSIXErrorDomain code 2: No such file or directory` on
1650        // iOS 17+ sims. `/bin/rm` is present on every stock sim image.
1651        //
1652        // Best-effort: any missing subdir is fine (fresh app that never
1653        // wrote to that path). `rm -rf` treats absent targets as no-ops.
1654        simctl_run(&["spawn", udid, "/bin/rm", "-rf", &documents, &library, &tmp]).await?;
1655        Ok(())
1656    }
1657
1658    /// `xcrun simctl openurl <udid> <url>` — open a URL on the device.
1659    ///
1660    /// **URL bytes are passed to `xcrun simctl` verbatim** — no
1661    /// parsing, no percent-encoding rewrite, no query-string
1662    /// stripping. Verified by [`openurl_argv`] (test-visible helper)
1663    /// and its unit test asserting query-params like
1664    /// `?url=http%3A%2F%2Flocalhost%3A8081` reach the argv byte-for-byte.
1665    /// Consequently, if the target app's URL router (e.g.
1666    /// expo-dev-client 57.0.5) shows a picker instead of
1667    /// auto-connecting, the URL reached it intact and the problem
1668    /// lives on the URL-router side.
1669    pub async fn open_url(&self, udid: &str, url: &str) -> Result<(), DeviceControlError> {
1670        let argv = openurl_argv(udid, url);
1671        let refs: Vec<&str> = argv.iter().map(|s| s.as_str()).collect();
1672        simctl_run(&refs).await?;
1673        Ok(())
1674    }
1675}
1676
1677/// Argv construction for `xcrun simctl openurl`. Extracted
1678/// as a test-visible helper so the URL-preservation contract is
1679/// unit-testable without invoking `xcrun`.
1680#[doc(hidden)]
1681pub fn openurl_argv(udid: &str, url: &str) -> [String; 3] {
1682    ["openurl".to_string(), udid.to_string(), url.to_string()]
1683}
1684
1685impl SimctlClient {
1686    /// `xcrun simctl push <udid> <bundle-id> <apns-json-path>`.
1687    /// Deliver an APNS payload to a sim-installed app. The payload file is
1688    /// a JSON document whose top-level dictionary mirrors what an APNS
1689    /// provider would send; `aps.alert.body` / `aps.alert.title` surface
1690    /// as banner content and reach the app's
1691    /// `UNUserNotificationCenterDelegate`.
1692    pub async fn send_push(
1693        &self,
1694        udid: &str,
1695        bundle_id: &str,
1696        apns_json_path: &str,
1697    ) -> Result<(), DeviceControlError> {
1698        simctl_run(&["push", udid, bundle_id, apns_json_path]).await?;
1699        Ok(())
1700    }
1701
1702    /// `xcrun simctl ui <udid> appearance <light|dark>` — set UI appearance.
1703    pub async fn set_appearance(
1704        &self,
1705        udid: &str,
1706        mode: Appearance,
1707    ) -> Result<(), DeviceControlError> {
1708        simctl_run(&["ui", udid, "appearance", mode.as_str()]).await?;
1709        Ok(())
1710    }
1711
1712    /// `xcrun simctl privacy <udid> grant <perm> <bundle-id>`.
1713    pub async fn grant_permission(
1714        &self,
1715        udid: &str,
1716        permission: SimctlPermission,
1717        bundle_id: &str,
1718    ) -> Result<(), DeviceControlError> {
1719        simctl_run(&["privacy", udid, "grant", permission.as_str(), bundle_id]).await?;
1720        Ok(())
1721    }
1722
1723    /// `xcrun simctl privacy <udid> revoke <perm> <bundle-id>` — explicitly
1724    /// deny the permission. Mirrors maestro yaml `permissions: { x: deny }`
1725    /// (the reverse of `grant`). Distinct from `reset`, which returns the
1726    /// permission to "not determined".
1727    pub async fn revoke_permission(
1728        &self,
1729        udid: &str,
1730        permission: SimctlPermission,
1731        bundle_id: &str,
1732    ) -> Result<(), DeviceControlError> {
1733        simctl_run(&["privacy", udid, "revoke", permission.as_str(), bundle_id]).await?;
1734        Ok(())
1735    }
1736
1737    /// `xcrun simctl location <udid> set <lat>,<lng>` — set sim location
1738    /// to a fixed point. Mirrors maestro `setLocation`.
1739    pub async fn location_set(
1740        &self,
1741        udid: &str,
1742        latitude: f64,
1743        longitude: f64,
1744    ) -> Result<(), DeviceControlError> {
1745        let coord = format!("{latitude},{longitude}");
1746        simctl_run(&["location", udid, "set", &coord]).await?;
1747        Ok(())
1748    }
1749
1750    /// `xcrun simctl location <udid> start [--speed=<m/s>] <waypoints>`
1751    /// — interpolate sim location along waypoints. Fire-and-return: simctl
1752    /// injects scenario and returns; sim continues interpolation in background.
1753    /// Mirrors maestro `travel`.
1754    pub async fn location_start(
1755        &self,
1756        udid: &str,
1757        points: &[(f64, f64)],
1758        speed_mps: Option<f64>,
1759    ) -> Result<(), DeviceControlError> {
1760        if points.len() < 2 {
1761            return Err(DeviceControlError::Malformed {
1762                subcommand: "location-start".into(),
1763                detail: format!("requires ≥2 waypoints, got {}", points.len()),
1764            });
1765        }
1766        let mut args: Vec<String> = vec!["location".into(), udid.into(), "start".into()];
1767        if let Some(s) = speed_mps {
1768            args.push(format!("--speed={s}"));
1769        }
1770        for (lat, lng) in points {
1771            args.push(format!("{lat},{lng}"));
1772        }
1773        let args_ref: Vec<&str> = args.iter().map(String::as_str).collect();
1774        simctl_run(&args_ref).await?;
1775        Ok(())
1776    }
1777
1778    /// `xcrun simctl location <udid> clear` — reset active location
1779    /// scenario.
1780    pub async fn location_clear(&self, udid: &str) -> Result<(), DeviceControlError> {
1781        simctl_run(&["location", udid, "clear"]).await?;
1782        Ok(())
1783    }
1784
1785    /// `xcrun simctl addmedia <udid> <path>...` — add photos / videos /
1786    /// contacts to sim library. Mirrors maestro `addMedia` (scalar or
1787    /// array form already flattened on adapter side).
1788    pub async fn add_media(&self, udid: &str, paths: &[String]) -> Result<(), DeviceControlError> {
1789        if paths.is_empty() {
1790            return Err(DeviceControlError::Malformed {
1791                subcommand: "addmedia".into(),
1792                detail: "no paths supplied".into(),
1793            });
1794        }
1795        let mut args: Vec<&str> = vec!["addmedia", udid];
1796        for p in paths {
1797            args.push(p.as_str());
1798        }
1799        simctl_run(&args).await?;
1800        Ok(())
1801    }
1802
1803    /// Start recording sim display to `path`. Spawns
1804    /// `xcrun simctl io <udid> recordVideo <path>` as a long-running child;
1805    /// returns handle immediately. Caller must pair with
1806    /// [`Self::record_video_stop`] for clean SIGINT-and-wait shutdown —
1807    /// dropping the handle would SIGKILL via tokio + lose mp4 trailer.
1808    pub async fn record_video_start(
1809        &self,
1810        udid: &str,
1811        path: &str,
1812    ) -> Result<RecordingHandle, DeviceControlError> {
1813        // Log to a file beside the video, not to pipes.
1814        //
1815        // Piped output with nobody reading it is a trap that only springs
1816        // once the recording has to outlive the process that started it:
1817        // when that process exits, the read ends close, and the next line
1818        // `simctl` writes kills it with SIGPIPE. The recording then stops
1819        // silently, seconds after being reported as started, leaving a
1820        // zero-byte file — which is exactly what `smix record start`
1821        // produced before this changed.
1822        //
1823        // A file also keeps `simctl`'s own diagnostics ("No display
1824        // specified…", "Recording started") somewhere a person can read
1825        // them, which a discarded pipe did not.
1826        let log_path = format!("{path}.log");
1827        let log = std::fs::File::create(&log_path)?;
1828        let log_err = log.try_clone()?;
1829        let child = tokio::process::Command::new("xcrun")
1830            .args(["simctl", "io", udid, "recordVideo", path])
1831            .stdin(std::process::Stdio::null())
1832            .stdout(std::process::Stdio::from(log))
1833            .stderr(std::process::Stdio::from(log_err))
1834            .spawn()?;
1835        // brief settle for simctl to initialize encoder + open output file.
1836        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
1837        Ok(RecordingHandle {
1838            child,
1839            path: path.to_string(),
1840            started_at: std::time::Instant::now(),
1841        })
1842    }
1843
1844    /// Stop a recording via SIGINT + wait (≤10s). SIGINT lets simctl
1845    /// trap and flush the mp4 trailer; SIGKILL would corrupt output.
1846    /// Timeout escalates to SIGKILL with explicit error mentioning truncation.
1847    pub async fn record_video_stop(
1848        &self,
1849        mut handle: RecordingHandle,
1850    ) -> Result<(), DeviceControlError> {
1851        let pid = handle
1852            .child
1853            .id()
1854            .ok_or_else(|| DeviceControlError::Malformed {
1855                subcommand: "recordVideo-stop".into(),
1856                detail: "child already reaped".into(),
1857            })?;
1858        // SAFETY: libc::kill is a thin POSIX syscall wrapper; pid is owned by
1859        // this Child instance (no race) and SIGINT is signal-safe.
1860        let rc = unsafe { libc::kill(pid as i32, libc::SIGINT) };
1861        if rc != 0 {
1862            return Err(DeviceControlError::Malformed {
1863                subcommand: "recordVideo-stop".into(),
1864                detail: format!(
1865                    "kill SIGINT failed: errno={}",
1866                    std::io::Error::last_os_error()
1867                ),
1868            });
1869        }
1870        let wait_result =
1871            tokio::time::timeout(std::time::Duration::from_secs(10), handle.child.wait()).await;
1872        match wait_result {
1873            Ok(Ok(_status)) => Ok(()),
1874            Ok(Err(e)) => Err(DeviceControlError::Malformed {
1875                subcommand: "recordVideo-stop".into(),
1876                detail: format!("wait failed: {e}"),
1877            }),
1878            Err(_timeout) => {
1879                let _ = handle.child.kill().await;
1880                Err(DeviceControlError::Malformed {
1881                    subcommand: "recordVideo-stop".into(),
1882                    detail: "SIGINT timeout (10s) — escalated SIGKILL; output mp4 likely truncated. Inspect simctl recordVideo stderr.".into(),
1883                })
1884            }
1885        }
1886    }
1887
1888    /// `xcrun simctl privacy <udid> reset <perm> <bundle-id>` — return the
1889    /// permission to "not determined" so the next request re-prompts.
1890    /// May terminate a running instance of the target app (Apple
1891    /// behavior) — call before launch, not mid-flow.
1892    pub async fn reset_permission(
1893        &self,
1894        udid: &str,
1895        permission: SimctlPermission,
1896        bundle_id: &str,
1897    ) -> Result<(), DeviceControlError> {
1898        simctl_run(&["privacy", udid, "reset", permission.as_str(), bundle_id]).await?;
1899        Ok(())
1900    }
1901
1902    /// `xcrun simctl keychain <udid> reset` — clear all keychain entries.
1903    pub async fn keychain_reset(&self, udid: &str) -> Result<(), DeviceControlError> {
1904        simctl_run(&["keychain", udid, "reset"]).await?;
1905        Ok(())
1906    }
1907
1908    /// `xcrun simctl pbpaste <udid>` — read clipboard contents.
1909    pub async fn pasteboard_get(&self, udid: &str) -> Result<String, DeviceControlError> {
1910        simctl_run(&["pbpaste", udid]).await
1911    }
1912
1913    /// `xcrun simctl pbcopy <udid>` — write clipboard contents (via piped stdin).
1914    pub async fn pasteboard_set(&self, udid: &str, text: &str) -> Result<(), DeviceControlError> {
1915        // pbcopy reads stdin — we pipe via shell echo for simplicity.
1916        // Long-term: spawn with stdin pipe.
1917        use tokio::io::AsyncWriteExt;
1918        let mut cmd = Command::new("xcrun");
1919        cmd.arg("simctl").arg("pbcopy").arg(udid);
1920        cmd.stdin(std::process::Stdio::piped());
1921        let mut child = cmd.spawn()?;
1922        if let Some(mut stdin) = child.stdin.take() {
1923            stdin.write_all(text.as_bytes()).await?;
1924            drop(stdin); // close stdin so pbcopy returns
1925        }
1926        let status = child.wait().await?;
1927        if !status.success() {
1928            return Err(DeviceControlError::NonZeroExit {
1929                subcommand: "pbcopy".into(),
1930                argv: vec!["pbcopy".to_string()],
1931                code: status.code().unwrap_or(-1),
1932                stderr: String::new(),
1933                wall_ms: 0,
1934            });
1935        }
1936        Ok(())
1937    }
1938
1939    /// Read back the Reduce Motion accessibility setting.
1940    ///
1941    /// `Ok(None)` when the key was never written, which `defaults read`
1942    /// reports by exiting non-zero. Absent is not off and not on — it
1943    /// is the device having no opinion, and a caller that wanted the
1944    /// setting established has to treat it as a failure to establish.
1945    pub async fn reduce_motion(&self, udid: &str) -> Result<Option<String>, DeviceControlError> {
1946        match simctl_run(&[
1947            "spawn",
1948            udid,
1949            "/usr/bin/defaults",
1950            "read",
1951            "com.apple.UIKit",
1952            "UIAccessibilityReduceMotionEnabled",
1953        ])
1954        .await
1955        {
1956            Ok(s) => Ok(Some(s.trim().to_string())),
1957            Err(DeviceControlError::NonZeroExit { .. }) => Ok(None),
1958            Err(e) => Err(e),
1959        }
1960    }
1961
1962    /// Toggle "Reduce Motion" accessibility setting via `defaults write`.
1963    pub async fn set_reduce_motion(
1964        &self,
1965        udid: &str,
1966        enabled: bool,
1967    ) -> Result<(), DeviceControlError> {
1968        // `true`/`false`, not `1`/`0`. `defaults` accepts
1969        // `-bool (true | false | yes | no)` and answers anything else
1970        // by printing its usage and exiting 255 — which is what this
1971        // did from the day it was written. It had no callers until the
1972        // animation switch, so nothing ever ran it.
1973        let val = if enabled { "true" } else { "false" };
1974        // Absolute path, not `defaults`. `simctl spawn` does not run a
1975        // login shell inside the simulator, so a bare name exits 255
1976        // with no stderr — which is exactly what it did the first time
1977        // an animation-quietening run met a device. The same lesson was
1978        // learned in v1.0.7 for `rm`; the reader below and
1979        // `current_locale` already spell it out.
1980        simctl_run(&[
1981            "spawn",
1982            udid,
1983            "/usr/bin/defaults",
1984            "write",
1985            "com.apple.UIKit",
1986            "UIAccessibilityReduceMotionEnabled",
1987            "-bool",
1988            val,
1989        ])
1990        .await?;
1991        Ok(())
1992    }
1993
1994    /// `xcrun simctl io <udid> screenshot <tmpfile>` → raw PNG bytes,
1995    /// with a byte-level sRGB metadata splice if the produced PNG lacks
1996    /// an `sRGB` chunk.
1997    ///
1998    /// Goes through a temp file: current Xcode's `screenshot -` does not
1999    /// treat `-` as stdout — it writes a literal file named `-` in cwd
2000    /// and emits nothing on stdout (observed on Xcode/iOS 26.5).
2001    ///
2002    /// **Pixel-preservation invariant**: the returned bytes are
2003    /// byte-identical to whatever `simctl io screenshot` wrote to disk
2004    /// EXCEPT for one narrow case — if the PNG does not carry an
2005    /// `sRGB` ancillary chunk (observed on iOS 26.5 sub-builds
2006    /// mid-2026), a 13-byte `sRGB` chunk is spliced in immediately
2007    /// before the first `IDAT`. Pixel data (IDAT bytes) is never
2008    /// decoded or modified. See [`ensure_srgb_chunk`] for the exact
2009    /// splice operation.
2010    pub async fn screenshot(&self, udid: &str) -> Result<Vec<u8>, DeviceControlError> {
2011        match self.capture_frame(udid, true).await? {
2012            surface_capture::CapturedFrame::Png(bytes) => Ok(bytes),
2013            // want_png=true only ever produces a PNG (host ImageIO encode or
2014            // the simctl fallback). A raw frame here is a protocol violation.
2015            surface_capture::CapturedFrame::Bgra { .. } => Err(DeviceControlError::Malformed {
2016                subcommand: "screenshot".into(),
2017                detail: "capture returned raw BGRA for a PNG request".into(),
2018            }),
2019        }
2020    }
2021
2022    /// Capture a frame preferring the fast raw-BGRA path.
2023    ///
2024    /// When the resident IOSurface host is available this returns
2025    /// [`CapturedFrame::Bgra`](surface_capture::CapturedFrame::Bgra) —
2026    /// ~0.3 ms per frame, no PNG encode. When the surface can't be resolved
2027    /// (sim not booted, framework layout change) it falls back to
2028    /// `xcrun simctl io screenshot` and returns
2029    /// [`CapturedFrame::Png`](surface_capture::CapturedFrame::Png). The
2030    /// pixels are correct either way; consumers that only need grayscale
2031    /// samples (diff-loop / dhash) skip the PNG encode+decode round-trip.
2032    ///
2033    /// Since smix 2.0.0.
2034    pub async fn capture_bgra(
2035        &self,
2036        udid: &str,
2037    ) -> Result<surface_capture::CapturedFrame, DeviceControlError> {
2038        self.capture_frame(udid, false).await
2039    }
2040
2041    /// Core capture path: try the resident IOSurface host, fall back to
2042    /// `simctl`. `want_png` selects an in-host ImageIO PNG encode over a raw
2043    /// BGRA frame; the fallback is always a PNG.
2044    async fn capture_frame(
2045        &self,
2046        udid: &str,
2047        want_png: bool,
2048    ) -> Result<surface_capture::CapturedFrame, DeviceControlError> {
2049        // Direct path first. No pacer gate: the direct IOSurface read does not
2050        // touch `com.apple.display.captureservice`, so the crash-guard floor
2051        // the pacer enforces for `simctl io screenshot` does not apply here.
2052        // Surface unavailable, or the host transport failed — both fall
2053        // through to the correct-but-slow simctl path below.
2054        if let Ok(Some(frame)) = self.try_capture_direct(udid, want_png).await {
2055            return Ok(frame);
2056        }
2057        let png = self.screenshot_via_simctl(udid).await?;
2058        Ok(surface_capture::CapturedFrame::Png(png))
2059    }
2060
2061    /// Get-or-spawn the resident host for `udid` and grab one frame. Returns
2062    /// `Ok(None)` when the host reports the surface is gone, `Err` on a
2063    /// transport failure. In both non-`Some` cases the host is dropped (and
2064    /// killed) so the next call re-resolves from scratch.
2065    async fn try_capture_direct(
2066        &self,
2067        udid: &str,
2068        want_png: bool,
2069    ) -> Result<Option<surface_capture::CapturedFrame>, surface_capture::HostError> {
2070        // Take the host out from under the lock so a 12.6 MB grab (or a 5s
2071        // spawn) never serializes captures for other sims.
2072        let existing = { self.capture_hosts.lock().await.take(udid) };
2073        let mut host = match existing {
2074            Some(h) => h,
2075            None => surface_capture::SurfaceCaptureHost::spawn(udid).await?,
2076        };
2077        match host.grab(want_png).await {
2078            Ok(Some(frame)) => {
2079                self.capture_hosts.lock().await.put(udid, host);
2080                Ok(Some(frame))
2081            }
2082            // Host is exiting (surface gone) — drop it, fall back.
2083            Ok(None) => Ok(None),
2084            // Transport died — drop it, fall back.
2085            Err(e) => Err(e),
2086        }
2087    }
2088
2089    /// Drop the resident capture host for `udid`, if any. Call this whenever a
2090    /// lifecycle operation may have invalidated the framebuffer surface
2091    /// (shutdown / erase / reboot) so the next capture re-resolves cleanly.
2092    ///
2093    /// Since smix 2.0.0.
2094    pub async fn evict_capture_host(&self, udid: &str) {
2095        let host = { self.capture_hosts.lock().await.evict(udid) };
2096        if let Some(h) = host {
2097            h.shutdown().await;
2098        }
2099    }
2100
2101    /// `xcrun simctl io <udid> screenshot <tmpfile>` → raw PNG bytes, paced +
2102    /// circuit-guarded, with the sRGB metadata splice. The correct-but-slow
2103    /// fallback for [`capture_frame`](Self::capture_frame).
2104    async fn screenshot_via_simctl(&self, udid: &str) -> Result<Vec<u8>, DeviceControlError> {
2105        // Pace + circuit-check before invoking simctl.
2106        let wait = {
2107            let mut pacer = self
2108                .screenshot_pacer
2109                .lock()
2110                .expect("screenshot pacer mutex must not be poisoned");
2111            pacer
2112                .compute_wait()
2113                .map_err(|retry_after| DeviceControlError::CaptureBackpressure { retry_after })?
2114        };
2115        if !wait.is_zero() {
2116            sleep(wait).await;
2117        }
2118
2119        let call_start = std::time::Instant::now();
2120        let tmp =
2121            std::env::temp_dir().join(format!("smix-screenshot-{udid}-{}.png", std::process::id()));
2122        let tmp_str = tmp.display().to_string();
2123        let result = simctl_capture(&["io", udid, "screenshot", &tmp_str]).await;
2124        let bytes = result.and_then(|_| {
2125            std::fs::read(&tmp).map_err(|e| DeviceControlError::Malformed {
2126                subcommand: "screenshot".into(),
2127                detail: format!("read {tmp_str}: {e}"),
2128            })
2129        });
2130        let _ = std::fs::remove_file(&tmp);
2131
2132        let wall = call_start.elapsed();
2133        let failed = bytes.is_err();
2134        {
2135            let mut pacer = self
2136                .screenshot_pacer
2137                .lock()
2138                .expect("screenshot pacer mutex must not be poisoned");
2139            pacer.record(wall, failed);
2140        }
2141
2142        let bytes = bytes?;
2143        if bytes.len() < 8 {
2144            return Err(DeviceControlError::Malformed {
2145                subcommand: "screenshot".into(),
2146                detail: format!("screenshot file too short: {} bytes", bytes.len()),
2147            });
2148        }
2149        Ok(ensure_srgb_chunk(bytes))
2150    }
2151
2152    /// `xcrun simctl create <name> <device-type-id> <runtime-id>` → udid.
2153    pub async fn create_device(
2154        &self,
2155        name: &str,
2156        device_type: &str,
2157        runtime_id: &str,
2158    ) -> Result<String, DeviceControlError> {
2159        let out = simctl_run(&["create", name, device_type, runtime_id]).await?;
2160        Ok(out.trim().to_string())
2161    }
2162
2163    /// `xcrun simctl delete <udid>` — delete a simulator device.
2164    pub async fn delete_device(&self, udid: &str) -> Result<(), DeviceControlError> {
2165        simctl_run(&["delete", udid]).await?;
2166        Ok(())
2167    }
2168}
2169
2170// -------------------- PNG sRGB chunk normalization --------------------
2171//
2172// iOS 26.5 sub-builds (mid-2026) started omitting the `sRGB` ancillary
2173// chunk from `simctl io screenshot` output. macOS Preview.app and other
2174// viewers that fall back to Display P3 when no ICC profile is embedded
2175// then over-saturate the image (red gets pushed, text anti-alias picks
2176// up yellow fringing).
2177//
2178// This does NOT affect pixel-comparison (dhash decodes IDAT to RGBA and
2179// ignores ancillary chunks), but does affect any downstream tool that
2180// renders the PNG for human review. The normalizer runs on the raw byte
2181// stream — walks chunks, and if no `sRGB` chunk is seen before the first
2182// `IDAT`, splices in a synthesized 13-byte `sRGB` chunk (length=1,
2183// type="sRGB", data=[0 = perceptual intent], CRC over type+data).
2184//
2185// Pixel-preservation invariant: IDAT bytes are never decoded. Every
2186// existing chunk is copied verbatim. Only 13 bytes of new metadata are
2187// inserted.
2188
2189const PNG_MAGIC: &[u8; 8] = b"\x89PNG\r\n\x1a\n";
2190
2191/// Ensure the PNG carries an `sRGB` ancillary chunk. Called on the raw
2192/// bytes returned by `xcrun simctl io <udid> screenshot`. If the PNG
2193/// already has an `sRGB` chunk, returns the input unchanged; otherwise
2194/// splices in a 13-byte `sRGB` chunk (rendering intent = 0, perceptual)
2195/// immediately before the first `IDAT`. Returns the input unchanged on
2196/// any structural anomaly (missing magic, malformed chunk) so a
2197/// corrupted PNG is passed through untouched for the caller to diagnose.
2198pub fn ensure_srgb_chunk(bytes: Vec<u8>) -> Vec<u8> {
2199    if bytes.len() < 8 || &bytes[..8] != PNG_MAGIC {
2200        return bytes;
2201    }
2202    let Some((idat_offset, has_srgb)) = scan_png_chunks(&bytes) else {
2203        return bytes;
2204    };
2205    if has_srgb {
2206        return bytes;
2207    }
2208    // Splice the synthesized sRGB chunk right before the first IDAT.
2209    let mut out = Vec::with_capacity(bytes.len() + 13);
2210    out.extend_from_slice(&bytes[..idat_offset]);
2211    out.extend_from_slice(&synthesized_srgb_chunk());
2212    out.extend_from_slice(&bytes[idat_offset..]);
2213    out
2214}
2215
2216/// Walk PNG chunks starting after the 8-byte magic. Returns
2217/// `(offset_of_first_IDAT, has_srgb_chunk_before_it)` when the walk
2218/// reaches an IDAT chunk. Returns `None` if the walk hits EOF or a
2219/// malformed chunk without seeing an IDAT.
2220fn scan_png_chunks(bytes: &[u8]) -> Option<(usize, bool)> {
2221    let mut i: usize = 8;
2222    let mut has_srgb = false;
2223    while i + 8 <= bytes.len() {
2224        let length =
2225            u32::from_be_bytes([bytes[i], bytes[i + 1], bytes[i + 2], bytes[i + 3]]) as usize;
2226        let ctype = &bytes[i + 4..i + 8];
2227        if ctype == b"IDAT" {
2228            return Some((i, has_srgb));
2229        }
2230        if ctype == b"sRGB" {
2231            has_srgb = true;
2232        }
2233        // 4 (length) + 4 (type) + length (data) + 4 (crc)
2234        let end = i.checked_add(12)?.checked_add(length)?;
2235        if end > bytes.len() {
2236            return None;
2237        }
2238        i = end;
2239    }
2240    None
2241}
2242
2243/// Build the 13-byte `sRGB` chunk with rendering intent = 0 (perceptual).
2244/// Format: `[len:4][type:4][data:1][crc:4]` = 13 bytes total.
2245fn synthesized_srgb_chunk() -> [u8; 13] {
2246    // The CRC is computed over `type || data`.
2247    let mut crc_input = [0u8; 5];
2248    crc_input[0..4].copy_from_slice(b"sRGB");
2249    crc_input[4] = 0; // perceptual
2250    let crc = crc32_ieee(&crc_input);
2251    let mut chunk = [0u8; 13];
2252    chunk[0..4].copy_from_slice(&1u32.to_be_bytes()); // length = 1 (data byte)
2253    chunk[4..8].copy_from_slice(b"sRGB");
2254    chunk[8] = 0;
2255    chunk[9..13].copy_from_slice(&crc.to_be_bytes());
2256    chunk
2257}
2258
2259/// Table-less CRC-32 IEEE 802.3 (polynomial 0xEDB88320) as used by
2260/// PNG. Small enough for this crate's single call site — avoids
2261/// pulling in a `crc32fast` dependency.
2262fn crc32_ieee(bytes: &[u8]) -> u32 {
2263    let mut crc: u32 = 0xFFFF_FFFF;
2264    for &b in bytes {
2265        crc ^= u32::from(b);
2266        for _ in 0..8 {
2267            let mask = 0u32.wrapping_sub(crc & 1);
2268            crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
2269        }
2270    }
2271    !crc
2272}
2273
2274#[cfg(test)]
2275mod tests {
2276    use super::*;
2277
2278    #[test]
2279    fn compose_child_env_adds_prefix() {
2280        let composed = compose_child_env(&[
2281            ("SMIX_PERF_RECEIVER_URL", "http://127.0.0.1:9999"),
2282            ("LAUNCH_FORCE_PUSH", "true"),
2283        ]);
2284        assert_eq!(
2285            composed,
2286            vec![
2287                (
2288                    "SIMCTL_CHILD_SMIX_PERF_RECEIVER_URL".to_string(),
2289                    "http://127.0.0.1:9999".to_string(),
2290                ),
2291                (
2292                    "SIMCTL_CHILD_LAUNCH_FORCE_PUSH".to_string(),
2293                    "true".to_string(),
2294                ),
2295            ]
2296        );
2297    }
2298
2299    #[test]
2300    fn compose_child_env_already_prefixed_passes_through() {
2301        // Defensive: caller may pre-prefix; we must not double-prefix.
2302        let composed = compose_child_env(&[("SIMCTL_CHILD_FOO", "bar")]);
2303        assert_eq!(
2304            composed,
2305            vec![("SIMCTL_CHILD_FOO".to_string(), "bar".to_string())]
2306        );
2307    }
2308
2309    #[test]
2310    fn compose_child_env_empty_input_is_empty_output() {
2311        assert!(compose_child_env(&[]).is_empty());
2312    }
2313
2314    // -- openurl URL preservation ---------------------------------------
2315
2316    #[test]
2317    fn openurl_argv_preserves_url_verbatim() {
2318        let udid = "12345678-1234-5678-1234-567812345678";
2319        let url = "exp+focus-ai-app://expo-development-client/?url=http%3A%2F%2Flocalhost%3A8081";
2320        let argv = super::openurl_argv(udid, url);
2321        assert_eq!(argv[0], "openurl");
2322        assert_eq!(argv[1], udid);
2323        // Byte-identical URL — no percent-decoding, no query-strip.
2324        assert_eq!(argv[2], url);
2325        assert!(argv[2].contains("?url="));
2326        assert!(argv[2].contains("%3A"));
2327        assert!(argv[2].contains("%2F"));
2328    }
2329
2330    #[test]
2331    fn openurl_argv_preserves_ampersand_and_hash() {
2332        let udid = "12345678-1234-5678-1234-567812345678";
2333        let url = "myapp://dev-mutate?action=env&value=staging#anchor";
2334        let argv = super::openurl_argv(udid, url);
2335        assert_eq!(argv[2], url);
2336        assert!(argv[2].contains('&'));
2337        assert!(argv[2].contains('#'));
2338    }
2339
2340    #[test]
2341    fn openurl_argv_preserves_unicode() {
2342        let udid = "12345678-1234-5678-1234-567812345678";
2343        let url = "myapp://route?name=%E7%94%B0%E4%B8%AD";
2344        let argv = super::openurl_argv(udid, url);
2345        assert_eq!(argv[2], url);
2346    }
2347
2348    // -- sRGB chunk normalization ---------------------------------------
2349
2350    /// Build a minimal PNG: 1×1 8-bit RGBA, one IDAT (zlib-empty-safe),
2351    /// with or without an sRGB chunk. Returns synthetic bytes suitable
2352    /// for exercising the chunk-walking logic; no rendering intent.
2353    fn synth_png(with_srgb: bool) -> Vec<u8> {
2354        let mut out = Vec::new();
2355        out.extend_from_slice(super::PNG_MAGIC);
2356        // IHDR: 1x1, bit_depth=8, color_type=6 (RGBA), rest=0
2357        let ihdr_data: [u8; 13] = [
2358            0, 0, 0, 1, // width = 1
2359            0, 0, 0, 1, // height = 1
2360            8, // bit depth
2361            6, // color type = RGBA
2362            0, 0, 0,
2363        ];
2364        emit_chunk(&mut out, b"IHDR", &ihdr_data);
2365        if with_srgb {
2366            emit_chunk(&mut out, b"sRGB", &[0]);
2367        }
2368        // Placeholder IDAT — content doesn't matter for chunk-walking tests
2369        emit_chunk(&mut out, b"IDAT", &[0x78, 0x01, 0x00, 0x00]);
2370        emit_chunk(&mut out, b"IEND", &[]);
2371        out
2372    }
2373
2374    fn emit_chunk(out: &mut Vec<u8>, ctype: &[u8; 4], data: &[u8]) {
2375        out.extend_from_slice(&(data.len() as u32).to_be_bytes());
2376        out.extend_from_slice(ctype);
2377        out.extend_from_slice(data);
2378        let mut crc_in = Vec::with_capacity(4 + data.len());
2379        crc_in.extend_from_slice(ctype);
2380        crc_in.extend_from_slice(data);
2381        out.extend_from_slice(&super::crc32_ieee(&crc_in).to_be_bytes());
2382    }
2383
2384    #[test]
2385    fn ensure_srgb_passthrough_when_chunk_present() {
2386        let png = synth_png(true);
2387        let original_len = png.len();
2388        let out = super::ensure_srgb_chunk(png.clone());
2389        assert_eq!(out.len(), original_len);
2390        assert_eq!(out, png);
2391    }
2392
2393    #[test]
2394    fn ensure_srgb_inserts_chunk_when_absent() {
2395        let png = synth_png(false);
2396        let original_len = png.len();
2397        let out = super::ensure_srgb_chunk(png);
2398        assert_eq!(out.len(), original_len + 13);
2399        // First 8 bytes = PNG magic
2400        assert_eq!(&out[..8], super::PNG_MAGIC);
2401        // Search for the injected sRGB chunk
2402        let mut found = false;
2403        for w in out.windows(4) {
2404            if w == b"sRGB" {
2405                found = true;
2406                break;
2407            }
2408        }
2409        assert!(found, "sRGB chunk should have been spliced in");
2410    }
2411
2412    #[test]
2413    fn ensure_srgb_preserves_idat_bytes_verbatim() {
2414        // Any pixel corruption at the IDAT level would break the
2415        // pixel-preservation invariant. Extract IDAT payload from
2416        // input and output, assert byte-identical.
2417        let png = synth_png(false);
2418        let out = super::ensure_srgb_chunk(png.clone());
2419        assert_eq!(extract_idat_data(&png), extract_idat_data(&out));
2420    }
2421
2422    fn extract_idat_data(bytes: &[u8]) -> Vec<u8> {
2423        let mut i = 8;
2424        while i + 8 <= bytes.len() {
2425            let length =
2426                u32::from_be_bytes([bytes[i], bytes[i + 1], bytes[i + 2], bytes[i + 3]]) as usize;
2427            let ctype = &bytes[i + 4..i + 8];
2428            if ctype == b"IDAT" {
2429                return bytes[i + 8..i + 8 + length].to_vec();
2430            }
2431            i += 12 + length;
2432        }
2433        vec![]
2434    }
2435
2436    #[test]
2437    fn ensure_srgb_passthrough_on_bad_magic() {
2438        // Corrupted / non-PNG input must not be modified.
2439        let bytes = vec![0u8; 32];
2440        let out = super::ensure_srgb_chunk(bytes.clone());
2441        assert_eq!(out, bytes);
2442    }
2443
2444    #[test]
2445    fn crc32_matches_known_iend() {
2446        // The empty-data IEND CRC is a well-known constant.
2447        // CRC over "IEND" alone: 0xAE_42_60_82.
2448        assert_eq!(super::crc32_ieee(b"IEND"), 0xAE42_6082);
2449    }
2450}