Skip to main content

smix_error/
lib.rs

1#![doc = include_str!("../README.md")]
2#![deny(missing_docs)]
3#![deny(rustdoc::broken_intra_doc_links)]
4
5//! smix-error — ExpectationFailure + FailureCode + AI-readable
6//! `to_prompt()` + `build_suggestions` (stone, cold path).
7//!
8//! `build_suggestions` behavior: threshold > 0.5, top 3, sort by score
9//! descending → field (name > id > text) → DFS index ascending.
10//!
11//! # Why a separate stone
12//!
13//! SDK / driver / runner-client all throw / catch `ExpectationFailure`. As
14//! the canonical failure type it must live in a leaf crate that everyone
15//! can depend on. Failure messages MUST be AI-readable — `to_prompt()`
16//! is the canonical render.
17
18#![doc(html_root_url = "https://docs.smix.dev/smix-error")]
19
20use serde::{Deserialize, Serialize};
21use smix_screen::ElementSummary;
22use smix_selector::{Selector, describe_selector};
23use std::fmt;
24
25/// All failure codes smix surfaces back to the SDK / MCP / CLI
26/// (SCREAMING_SNAKE_CASE wire).
27#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
28#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
29// New codes keep arriving — two in two releases — and on an exhaustive
30// enum each one is a major, because a consumer matching every arm stops
31// compiling. That is the wrong price for smix naming a failure more
32// precisely, and it was about to be paid for the second time.
33//
34// The cost lands once, here, in a major that was already owed: every
35// downstream `match` needs a catch-all arm from now on. What it buys is
36// that the next code is additive.
37//
38// The guard that made a new variant fail to compile lives inside this
39// crate now (see `the_vocabulary_is_pinned` below). From out here
40// `non_exhaustive` would have made it accept anything, so it moved
41// rather than being weakened.
42#[non_exhaustive]
43pub enum FailureCode {
44    /// Selector matched zero elements in the visible tree.
45    ElementNotFound,
46    /// Element matched but failed the visibility filter.
47    NotVisible,
48    /// Element matched but `enabled = false`.
49    NotEnabled,
50    /// Selector matched multiple elements (when uniqueness was required).
51    Ambiguous,
52    /// Operation exceeded the implicit-wait budget.
53    Timeout,
54    /// `expect` assertion (e.g. `toHaveText`) did not hold.
55    AssertionFailed,
56    /// Target app exited or never launched.
57    AppNotRunning,
58    /// Simulator device is not booted.
59    SimulatorNotBooted,
60    /// The touch was synthesised, and it did not land inside the
61    /// element the selector matched.
62    ///
63    /// Distinct from `ElementNotFound` because the two send a reader
64    /// somewhere different: not-found means fix the selector, missed
65    /// means the element was there and the touch went elsewhere — a
66    /// stale frame, or something moved between the tree fetch and the
67    /// tap.
68    TapMissed,
69    /// The screen is described in one coordinate space and the touch
70    /// would be delivered in another, so no aim can land where the tree
71    /// says the element is.
72    ///
73    /// Distinct from `TapMissed`, and the distinction is the whole
74    /// point: a miss says the element was there and the touch went
75    /// elsewhere, which invites another attempt with a better point.
76    /// There is no better point here — whatever is passed gets
77    /// recomputed against the app's frame and then read against the
78    /// device's. Retrying is the trap, and the consumer who found this
79    /// spent an afternoon in it.
80    CoordinateSpaceMismatch,
81    /// Catch-all for runner / driver / IO failures.
82    DriverError,
83    /// The device's capture path is under load and refusing frames for a
84    /// stated window — the screenshot pacer's circuit is open.
85    ///
86    /// Separate from [`Self::DriverError`] because the two want opposite
87    /// responses and only one of them is a defect. A driver error means
88    /// something is broken; this means "not now, try again shortly", and
89    /// a caller with time left can simply keep waiting. It arrived as a
90    /// `DriverError` until 7.1, which is how a consumer's release gate
91    /// met it: `FAIL [DRIVER_ERROR]` from `waitForAnimationToEnd`, a
92    /// verb whose entire meaning is to wait.
93    CaptureBackpressure,
94}
95
96/// Structured failure thrown by SDK matchers and driver calls. Shape
97/// is AI-feed-back-ready.
98///
99/// `selector` is the typed `Selector` rather than the wire
100/// `serde_json::Value` — callers raising failures from the driver / SDK
101/// side already have the typed selector, and `to_prompt` invokes
102/// `describe_selector` for stable rendering.
103///
104/// Serializes as `{ ok: false, code, message, selector, suggestions,
105/// visibleElements, hint, screenshot, deviceLog }`; the `ok = false`
106/// discriminant identifies the failure branch of a `Result` wire.
107#[derive(Clone, Debug, Serialize, Deserialize)]
108#[serde(rename_all = "camelCase")]
109pub struct ExpectationFailure {
110    /// Always `false` for failures. Round-trip discriminator for
111    /// `Result<T, ExpectationFailure>` wire.
112    pub ok: False,
113    /// Failure code discriminator.
114    pub code: FailureCode,
115    /// Human-readable summary (and AI-readable when fed into `to_prompt`).
116    pub message: String,
117    /// Originating selector, when one is available.
118    #[serde(default, skip_serializing_if = "Option::is_none")]
119    pub selector: Option<Selector>,
120    /// Ranked near-miss suggestions (edit-distance to label / id / etc.).
121    #[serde(default)]
122    pub suggestions: Vec<String>,
123    /// Snapshot of visible+enabled elements at failure time.
124    #[serde(default)]
125    pub visible_elements: Vec<ElementSummary>,
126    /// Optional one-line hint (e.g. "try `app.wait_for(...)` first").
127    #[serde(default, skip_serializing_if = "Option::is_none")]
128    pub hint: Option<String>,
129    /// The smix that produced this failure.
130    ///
131    /// Not decoration. A consumer wrote up two defects against smix
132    /// behaviour that had been fixed hours earlier, quoting an error
133    /// message the current build no longer emits — they had no way to
134    /// tell whether the smix in front of them contained the fix for
135    /// the thing they had just hit. A failure that names its version
136    /// makes that answerable from the failure itself.
137    ///
138    /// Set by [`ExpectationFailure::new`] from the crate version, so no
139    /// call site can forget it.
140    #[serde(default)]
141    pub smix_version: String,
142    /// base64-encoded PNG; omitted from default rendering to keep logs lean.
143    #[serde(default, skip_serializing_if = "Option::is_none")]
144    pub screenshot: Option<String>,
145    /// Last-N-lines of captured device log, folded into AI-readable
146    /// output for failure-window system context.
147    #[serde(default, skip_serializing_if = "Vec::is_empty")]
148    pub device_log: Vec<String>,
149}
150
151/// Newtype around `false` — used as the [`ExpectationFailure::ok`]
152/// discriminator. Serializes/deserializes as the JSON literal `false`.
153#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
154#[serde(transparent)]
155pub struct False(pub bool);
156
157/// Builder/Init form for ergonomic construction.
158#[derive(Default)]
159pub struct FailureInit {
160    /// Optional failure code (defaults to `DriverError` if `None`).
161    pub code: Option<FailureCode>,
162    /// Human-readable / AI-readable message.
163    pub message: String,
164    /// Originating selector, when one is available.
165    pub selector: Option<Selector>,
166    /// Pre-built ranked near-miss suggestions.
167    pub suggestions: Vec<String>,
168    /// Captured visible+enabled elements at failure time.
169    pub visible_elements: Vec<ElementSummary>,
170    /// Optional one-line hint string.
171    pub hint: Option<String>,
172    /// Optional base64 PNG screenshot at failure time.
173    pub screenshot: Option<String>,
174    /// Optional captured device log tail.
175    pub device_log: Vec<String>,
176}
177
178impl ExpectationFailure {
179    /// Construct from an init struct. `code` defaults to `DriverError`
180    /// if `init.code` was None (defensive; SDK callers should always
181    /// set it).
182    pub fn new(init: FailureInit) -> Self {
183        ExpectationFailure {
184            ok: False(false),
185            code: init.code.unwrap_or(FailureCode::DriverError),
186            message: init.message,
187            selector: init.selector,
188            suggestions: init.suggestions,
189            visible_elements: init.visible_elements,
190            hint: init.hint,
191            smix_version: env!("CARGO_PKG_VERSION").to_string(),
192            screenshot: init.screenshot,
193            device_log: init.device_log,
194        }
195    }
196
197    /// AI-facing rendering. Designed so the output can be pasted back
198    /// as a user message into a coding agent.
199    #[must_use]
200    pub fn to_prompt(&self) -> String {
201        let mut lines: Vec<String> = Vec::new();
202        lines.push(format!(
203            "FAIL [{}]: {}",
204            format_code(self.code),
205            self.message
206        ));
207        // The version, on every failure, because the reader's next
208        // question after "what went wrong" is often "is my smix old".
209        // A consumer once wrote up two defects that had been fixed
210        // hours earlier, quoting a message this build no longer emits.
211        if !self.smix_version.is_empty() {
212            lines.push(format!("  smix: {}", self.smix_version));
213        }
214        if let Some(sel) = &self.selector {
215            lines.push(format!("  selector: {}", describe_selector(sel)));
216        }
217        if !self.suggestions.is_empty() {
218            lines.push("  suggestions:".into());
219            for s in &self.suggestions {
220                lines.push(format!("    - {}", s));
221            }
222        }
223        if !self.visible_elements.is_empty() {
224            let n = self.visible_elements.len().min(10);
225            lines.push(format!("  visible elements (top {}):", n));
226            for el in self.visible_elements.iter().take(10) {
227                lines.push(format!("    - {}", render_element(el)));
228            }
229        }
230        if let Some(h) = &self.hint {
231            lines.push(format!("  hint: {}", h));
232        }
233        if !self.device_log.is_empty() {
234            // LOG_PROMPT_CAP — defensive ceiling for AI prompt size.
235            const LOG_PROMPT_CAP: usize = 200;
236            let n = self.device_log.len();
237            lines.push(format!("  device log (last {} lines):", n));
238            let start = n.saturating_sub(LOG_PROMPT_CAP);
239            for dl in &self.device_log[start..] {
240                lines.push(format!("    - {}", dl));
241            }
242        }
243        lines.join("\n")
244    }
245}
246
247impl fmt::Display for ExpectationFailure {
248    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
249        write!(f, "{}", self.to_prompt())
250    }
251}
252
253impl std::error::Error for ExpectationFailure {}
254
255fn format_code(c: FailureCode) -> &'static str {
256    match c {
257        FailureCode::ElementNotFound => "ELEMENT_NOT_FOUND",
258        FailureCode::NotVisible => "NOT_VISIBLE",
259        FailureCode::NotEnabled => "NOT_ENABLED",
260        FailureCode::Ambiguous => "AMBIGUOUS",
261        FailureCode::Timeout => "TIMEOUT",
262        FailureCode::AssertionFailed => "ASSERTION_FAILED",
263        FailureCode::AppNotRunning => "APP_NOT_RUNNING",
264        FailureCode::SimulatorNotBooted => "SIMULATOR_NOT_BOOTED",
265        FailureCode::TapMissed => "TAP_MISSED",
266        FailureCode::CoordinateSpaceMismatch => "COORDINATE_SPACE_MISMATCH",
267        FailureCode::DriverError => "DRIVER_ERROR",
268        FailureCode::CaptureBackpressure => "CAPTURE_BACKPRESSURE",
269    }
270}
271
272fn render_element(el: &ElementSummary) -> String {
273    let role_str = el.role.map(|r| r.as_str()).unwrap_or("unknown");
274    let mut bits: Vec<String> = vec![role_str.to_string()];
275    if let Some(n) = &el.name {
276        bits.push(format!("name={:?}", n));
277    }
278    if let Some(i) = &el.id {
279        bits.push(format!("id=\"{}\"", i));
280    }
281    if let Some(t) = &el.text
282        && Some(t) != el.name.as_ref()
283    {
284        bits.push(format!("text={:?}", t));
285    }
286    if !el.enabled {
287        bits.push("disabled".into());
288    }
289    bits.join(" ")
290}
291
292// -------------------- buildSuggestions ----------------------------------
293
294const SUGGESTION_THRESHOLD: f64 = 0.5;
295const SUGGESTION_TOP_N: usize = 3;
296
297/// Generate "Did you mean ...?" suggestions from the current visible
298/// element list. Contract: threshold > 0.5, top 3, score desc →
299/// field (name > text) → DFS index asc.
300///
301/// `target = None` → empty vec.
302#[must_use]
303pub fn build_suggestions(target: Option<&str>, visible: &[ElementSummary]) -> Vec<String> {
304    let Some(target) = target else {
305        return Vec::new();
306    };
307    let lower_target = target.to_lowercase();
308    let mut candidates: Vec<(f64, &'static str, String, usize)> = Vec::new();
309    for (i, el) in visible.iter().enumerate() {
310        let mut best: Option<(f64, &'static str, String)> = None;
311        if let Some(name) = &el.name
312            && !name.is_empty()
313        {
314            let s = similarity(&name.to_lowercase(), &lower_target);
315            if s > SUGGESTION_THRESHOLD {
316                best = Some((s, "name", name.clone()));
317            }
318        }
319        if let Some(id) = &el.id
320            && !id.is_empty()
321        {
322            let s = similarity(&id.to_lowercase(), &lower_target);
323            if s > SUGGESTION_THRESHOLD && best.as_ref().map(|(bs, _, _)| s > *bs).unwrap_or(true) {
324                best = Some((s, "id", id.clone()));
325            }
326        }
327        if let Some(text) = &el.text
328            && !text.is_empty()
329        {
330            let s = similarity(&text.to_lowercase(), &lower_target);
331            if s > SUGGESTION_THRESHOLD && best.as_ref().map(|(bs, _, _)| s > *bs).unwrap_or(true) {
332                best = Some((s, "text", text.clone()));
333            }
334        }
335        if let Some((score, field, value)) = best {
336            candidates.push((score, field, value, i));
337        }
338    }
339    // Sort: score desc → field name>text → index asc.
340    let field_rank = |f: &str| match f {
341        "name" => 0,
342        "id" => 1,
343        _ => 2, // text
344    };
345    candidates.sort_by(|a, b| {
346        b.0.partial_cmp(&a.0)
347            .unwrap_or(std::cmp::Ordering::Equal)
348            .then_with(|| field_rank(a.1).cmp(&field_rank(b.1)))
349            .then_with(|| a.3.cmp(&b.3))
350    });
351    candidates
352        .into_iter()
353        .take(SUGGESTION_TOP_N)
354        .map(|(score, field, value, _)| {
355            format!(
356                "Did you mean {:?}? (similarity {:.2}, field {})",
357                value, score, field
358            )
359        })
360        .collect()
361}
362
363/// Normalized `[0, 1]` string similarity. 1 = identical,
364/// 0 = completely different.
365#[must_use]
366pub fn similarity(a: &str, b: &str) -> f64 {
367    if a == b {
368        return 1.0;
369    }
370    let (longer, shorter) = if a.chars().count() >= b.chars().count() {
371        (a, b)
372    } else {
373        (b, a)
374    };
375    let llen = longer.chars().count();
376    if llen == 0 {
377        return 1.0;
378    }
379    let dist = edit_distance(longer, shorter);
380    (llen as f64 - dist as f64) / llen as f64
381}
382
383/// Levenshtein edit distance (Wagner-Fischer).
384#[must_use]
385pub fn edit_distance(a: &str, b: &str) -> usize {
386    let a_chars: Vec<char> = a.chars().collect();
387    let b_chars: Vec<char> = b.chars().collect();
388    let a_len = a_chars.len();
389    let b_len = b_chars.len();
390    let mut dp: Vec<usize> = (0..=b_len).collect();
391    for i in 1..=a_len {
392        let mut prev = dp[0];
393        dp[0] = i;
394        for j in 1..=b_len {
395            let tmp = dp[j];
396            dp[j] = if a_chars[i - 1] == b_chars[j - 1] {
397                prev
398            } else {
399                1 + dp[j].min(dp[j - 1]).min(prev)
400            };
401            prev = tmp;
402        }
403    }
404    dp[b_len]
405}
406
407impl FailureCode {
408    /// Every code, once.
409    ///
410    /// Exported because the alternative is a second hand-written copy,
411    /// and there was one: `tests/sdk_failure_code_parity.rs` kept its
412    /// own `all_variants()` list, and every assertion in that file —
413    /// the three SDK declarations and the errors guide — is derived
414    /// from it. Its docstring said adding a variant would stop the file
415    /// compiling. That stopped being true when the exhaustiveness guard
416    /// moved in here, because `#[non_exhaustive]` makes an outside
417    /// `match` accept anything; adding `CaptureBackpressure` in 7.1 left
418    /// all seven of those assertions green while no SDK declared it.
419    ///
420    /// [`Self::ALL`] is the one list. The exhaustive match in
421    /// `the_vocabulary_is_pinned` guards it from in here, where
422    /// `non_exhaustive` cannot weaken the match, and everything else
423    /// reads it rather than repeating it.
424    pub const ALL: &'static [FailureCode] = &[
425        FailureCode::ElementNotFound,
426        FailureCode::NotVisible,
427        FailureCode::NotEnabled,
428        FailureCode::Ambiguous,
429        FailureCode::Timeout,
430        FailureCode::AssertionFailed,
431        FailureCode::AppNotRunning,
432        FailureCode::SimulatorNotBooted,
433        FailureCode::TapMissed,
434        FailureCode::CoordinateSpaceMismatch,
435        FailureCode::DriverError,
436        FailureCode::CaptureBackpressure,
437    ];
438}
439
440#[cfg(test)]
441mod vocabulary {
442    use super::*;
443
444    /// A new `FailureCode` must not compile until it has been thought
445    /// about everywhere.
446    ///
447    /// This match is exhaustive on purpose and lives inside the crate on
448    /// purpose: `#[non_exhaustive]` makes an outside `match` accept
449    /// anything, so the guard that used to sit in
450    /// `tests/sdk_failure_code_parity.rs` would have started passing for
451    /// every future variant. Adding a code should break this line, then
452    /// the wire-string arm below it, then the three SDK declarations the
453    /// parity test reads, then the errors guide.
454    #[test]
455    fn the_vocabulary_is_pinned() {
456        let every = FailureCode::ALL;
457        for &code in every {
458            match code {
459                FailureCode::ElementNotFound
460                | FailureCode::NotVisible
461                | FailureCode::NotEnabled
462                | FailureCode::Ambiguous
463                | FailureCode::Timeout
464                | FailureCode::AssertionFailed
465                | FailureCode::AppNotRunning
466                | FailureCode::SimulatorNotBooted
467                | FailureCode::TapMissed
468                | FailureCode::CoordinateSpaceMismatch
469                | FailureCode::DriverError
470                | FailureCode::CaptureBackpressure => {}
471            }
472            // Every code renders as a wire string, and a code whose
473            // string nobody wrote would reach a consumer as whatever
474            // the formatter defaults to.
475            assert!(!format_code(code).is_empty(), "{code:?} has no wire string");
476        }
477        assert_eq!(
478            every.len(),
479            12,
480            "counted off the list above, not remembered"
481        );
482    }
483}