Skip to main content

smix_runner_wire/
lib.rs

1#![doc = include_str!("../README.md")]
2#![deny(missing_docs)]
3#![deny(rustdoc::broken_intra_doc_links)]
4
5//! smix-runner-wire — pure wire types for the SmixRunnerCore HTTP IPC.
6//!
7//! Stone, zero project coupling beyond the smix-screen / smix-selector
8//! upstream types it embeds (those are themselves stones).
9//!
10//! Pairs with [`smix-runner-client`](https://docs.rs/smix-runner-client)
11//! which provides the reqwest+tokio HTTP client; this crate is just the
12//! types so a consumer can:
13//!
14//! - Drive their own HTTP client (sync or async, custom transport)
15//! - Hand-roll a server side serving the same wire contract
16//! - Pin the wire-shape contract independently of the client implementation
17//!
18//! # Route surface
19//!
20//! 18 wire endpoints (see the `smix-runner-client` crate for the
21//! corresponding method names):
22//!
23//! - `GET /health` — bare 200/non-200
24//! - `GET /tree?include=…` → [`smix_screen::A11yNode`]
25//! - `GET /system-popups?include=…` → `Vec<`[`SystemPopup`]`>`
26//! - `POST /system-popup-action` `{popupId, buttonId}` → [`SystemPopupActionResponse`]
27//! - `POST /tap` → [`TapResult`]
28//! - `POST /tap-at-norm-coord` `{nx, ny}` → [`TapAtCoordResult`]
29//! - `POST /find` `{selector}` → `{exists}` or `{ok}`
30//! - `POST /fill` `{selector, text}` → [`RunnerKeyboardResult`]
31//! - `POST /clear` `{selector}` → [`RunnerKeyboardResult`]
32//! - `POST /press-key` `{key}` → [`RunnerKeyboardResult`]
33//! - `POST /swipe-once` `{direction}` → `{ok}`
34//! - `POST /pinch-at-norm-coord` `{cx, cy, fromSpan, toSpan, durationMs, panDx?, panDy?, panMs?, runUp?}` → `{ok, fingers}`
35//! - `POST /drag-at-norm-coord` `{fromNx, fromNy, toNx, toNy, holdMs, durationMs, releaseMs}` → `{ok}`
36//! - `POST /mouse-at-norm-coord` `{kind, nx?, ny?, toNx?, toNy?, dxDp?, dyDp?, wheel?, ctrl?}` → `{ok, kind, injected}` (Android)
37//! - `POST /window-size` `{package?, widthDp, heightDp}` → `{ok, widthDp, heightDp, package}` (Android)
38//! - `POST /press-key-combo` `{key, ctrl?, shift?, alt?, meta?}` → `{ok, key, keyCode}` (Android)
39//! - `POST /window-bounds` `{package?}` → `{ok, package, left, top, right, bottom, displayWidth, displayHeight}` (Android)
40//! - `POST /foreground` `{bundleId}` → `{ok}`
41//! - `POST /hide-keyboard` → `{ok}`
42//! - `POST /back` → `{ok}`
43//! - `POST /record/start` → `{ok}`
44//! - `GET /record/poll` → `{events: [`[`RecordedEvent`]`]}`
45//! - `POST /record/stop` → `{events: [`[`RecordedEvent`]`]}`
46
47#![doc(html_root_url = "https://docs.smix.dev/smix-runner-wire")]
48
49use serde::{Deserialize, Serialize};
50use smix_selector::Selector;
51use thiserror::Error;
52
53mod tap;
54pub use tap::{HitChainEntry, PressResult, TapAtCoordResult, TreeReader};
55
56// -------------------- Errors --------------------------------------------
57
58/// Transport-level failure variants exposed by the HTTP client. The
59/// concrete `reqwest::Error` source lives in `smix-runner-client`; the
60/// wire stone exposes only the discriminator + endpoint context so
61/// non-HTTP transports can reuse the variants.
62#[derive(Debug, Error)]
63pub enum RunnerTransportErrorKind {
64    /// Network / transport-layer fetch error (timeout, DNS, TLS, etc.).
65    #[error("runner {endpoint} fetch failed")]
66    FetchFailed {
67        /// Endpoint path that failed (e.g. `"/tap"`).
68        endpoint: String,
69    },
70    /// Runner returned non-2xx HTTP status.
71    #[error("runner {endpoint} returned status {status}: {body}")]
72    NonSuccessStatus {
73        /// Endpoint path that returned the error.
74        endpoint: String,
75        /// HTTP status code.
76        status: u16,
77        /// Raw response body (may be truncated).
78        body: String,
79    },
80    /// Runner returned a body that wasn't valid JSON.
81    #[error("runner {endpoint} returned non-JSON body")]
82    NonJsonBody {
83        /// Endpoint path that returned a non-JSON body.
84        endpoint: String,
85    },
86    /// Runner returned valid JSON but it didn't match the expected schema.
87    #[error("runner {endpoint} returned malformed body: {detail}")]
88    MalformedBody {
89        /// Endpoint path that returned the malformed body.
90        endpoint: String,
91        /// Schema-mismatch detail (serde error message).
92        detail: String,
93    },
94    /// Runner is unreachable (refused / closed / not listening).
95    #[error("runner {endpoint} unreachable: {message}")]
96    Unreachable {
97        /// Endpoint path attempted.
98        endpoint: String,
99        /// Reason (e.g. "connection refused").
100        message: String,
101    },
102}
103
104// -------------------- Common wire types ---------------------------------
105
106/// `include` scope query param shared by `/tree` / `/tap` / `/fill` /
107/// `/clear` / `/find` / `/scroll` / `/system-popups`. URL-only.
108#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
109#[serde(rename_all = "camelCase")]
110pub struct RunnerIncludeOpts {
111    /// Optional include scope (e.g. system-popups → `AllWindows`).
112    #[serde(default, skip_serializing_if = "Option::is_none")]
113    pub include: Option<IncludeScope>,
114}
115
116/// `include` scope literal — currently only `all-windows` (system popups
117/// pierce the app frame).
118#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
119#[serde(rename_all = "kebab-case")]
120pub enum IncludeScope {
121    /// Include all windows (system popups, alerts) above the app frame.
122    AllWindows,
123}
124
125impl IncludeScope {
126    /// kebab-case wire string used in the query parameter value.
127    pub fn query_value(self) -> &'static str {
128        match self {
129            IncludeScope::AllWindows => "all-windows",
130        }
131    }
132}
133
134// -------------------- /tap wire shape -----------------------------------
135
136/// `POST /tap` mode discriminator.
137#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
138#[serde(rename_all = "camelCase")]
139pub enum TapMode {
140    /// Runner returns only the matched frame; host normalizes + injects
141    /// via `/tap-at-norm-coord`. This is the default.
142    Resolve,
143    /// Runner resolves AND taps (legacy host-HID-based path).
144    ResolveAndTap,
145    /// Runner resolves selector then synthesizes the touch event via the
146    /// XCTRunnerDaemonSession daemonProxy. This bypasses the XCUIElement
147    /// gesture recognizer chain so RN Pressable `RCTTouchHandler`
148    /// UIGestureRecognizer receives the touch and fires the JS-thread
149    /// `onPress` callback reliably.
150    DaemonProxySynthesize,
151}
152
153/// `POST /tap` per-stage timing in milliseconds.
154#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
155#[serde(rename_all = "camelCase")]
156pub struct TapStages {
157    /// Time spent resolving the selector against the a11y tree.
158    #[serde(rename = "resolveMs", default)]
159    pub resolve_ms: f64,
160    /// Time spent dispatching the tap event itself.
161    #[serde(rename = "tapCallMs", default)]
162    pub tap_call_ms: f64,
163    /// End-to-end wall-clock for the whole tap call.
164    #[serde(rename = "totalMs", default)]
165    pub total_ms: f64,
166    /// Time spent waiting for the element to exist (implicit wait).
167    #[serde(rename = "waitExistenceMs", default)]
168    pub wait_existence_ms: f64,
169    /// Time spent reading the matched element's frame.
170    #[serde(rename = "frameReadMs", default)]
171    pub frame_read_ms: f64,
172}
173
174/// `POST /tap` response body.
175///
176/// This struct is the wire contract; the Swift emitter
177/// (`TapRoute.success`) is gated against it by
178/// `tests/it/tap_route_shape.rs`, which failed to exist long enough for the
179/// runner to ship a nested-`matched` + snake_case body that this struct
180/// silently deserialized to all-`None`/zero.
181#[derive(Clone, Debug, Default, Serialize, Deserialize)]
182#[serde(rename_all = "camelCase")]
183pub struct TapResult {
184    /// Matched element's accessibility label (selector text echoed when
185    /// the label is empty).
186    #[serde(rename = "matchedLabel", default)]
187    pub matched_label: Option<String>,
188    /// Per-stage timing breakdown.
189    #[serde(default)]
190    pub stages: Option<TapStages>,
191    /// Matched element's geometric frame, when resolve succeeded.
192    #[serde(default)]
193    pub frame: Option<smix_screen::Rect>,
194    /// Application window frame (for normalizing the matched frame).
195    #[serde(rename = "appFrame", default)]
196    pub app_frame: Option<smix_screen::Rect>,
197}
198
199/// `POST /tap` request body.
200#[derive(Clone, Debug, Serialize, Deserialize)]
201#[serde(rename_all = "camelCase")]
202pub struct TapRequest {
203    /// Selector picking the tap target.
204    pub selector: Selector,
205    /// Resolve-only vs resolve-and-tap discriminator.
206    pub mode: TapMode,
207}
208
209/// `POST /tap-at-norm-coord` request body.
210#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
211#[serde(rename_all = "camelCase")]
212pub struct TapAtNormCoordRequest {
213    /// Normalized x coordinate in `(0, 1)` (app-frame relative).
214    pub nx: f64,
215    /// Normalized y coordinate in `(0, 1)` (app-frame relative).
216    pub ny: f64,
217}
218
219// -------------------- /fill /clear /press-key wire shape ----------------
220
221/// Per-stage timing returned by `/fill` / `/clear` / `/press-key`.
222#[derive(Clone, Debug, Default, Serialize, Deserialize)]
223#[serde(rename_all = "camelCase")]
224pub struct KeyboardStages {
225    /// Selector resolve time.
226    #[serde(rename = "resolveMs", default)]
227    pub resolve_ms: f64,
228    /// Time waiting for keyboard appearance after the focus tap.
229    #[serde(rename = "keyboardWaitMs", default)]
230    pub keyboard_wait_ms: f64,
231    /// Time spent typing the characters.
232    #[serde(rename = "typingMs", default)]
233    pub typing_ms: f64,
234    /// End-to-end wall-clock for the whole keyboard operation.
235    #[serde(rename = "totalMs", default)]
236    pub total_ms: f64,
237}
238
239/// `POST /fill` / `POST /clear` / `POST /press-key` response body.
240#[derive(Clone, Debug, Default, Serialize, Deserialize)]
241#[serde(rename_all = "camelCase")]
242pub struct RunnerKeyboardResult {
243    /// Tree snapshot after the keyboard operation completed (optional).
244    #[serde(default)]
245    pub tree: Option<smix_screen::A11yNode>,
246    /// Per-stage timing breakdown (optional).
247    #[serde(default)]
248    pub stages: Option<KeyboardStages>,
249}
250
251// -------------------- /find wire shape -----------------------------------
252
253/// `POST /find` request body.
254#[derive(Clone, Debug, Serialize, Deserialize)]
255#[serde(rename_all = "camelCase")]
256pub struct FindRequest {
257    /// Selector to look up.
258    pub selector: Selector,
259}
260
261/// `POST /find` response body.
262#[derive(Clone, Debug, Default, Serialize, Deserialize)]
263#[serde(rename_all = "camelCase")]
264pub struct FindResponse {
265    /// Whether the selector matched any element.
266    #[serde(default)]
267    pub exists: bool,
268    /// Whether the resolve subsystem itself succeeded.
269    #[serde(default)]
270    pub ok: bool,
271}
272
273// -------------------- /system-popups wire shape -------------------------
274
275/// One system-popup discovered on the screen (alert / sheet / banner).
276#[derive(Clone, Debug, Serialize, Deserialize)]
277#[serde(rename_all = "camelCase")]
278pub struct SystemPopup {
279    /// Stable identifier for matching across polls.
280    pub id: String,
281    /// Discriminator (e.g. `"alert"` / `"sheet"` / `"banner"`).
282    #[serde(rename = "type")]
283    pub kind: String,
284    /// Originator (e.g. bundle id, system framework name).
285    pub source: String,
286    /// Popup title text.
287    #[serde(default)]
288    pub title: String,
289    /// Popup body text.
290    #[serde(default)]
291    pub body: String,
292    /// Buttons available on the popup.
293    #[serde(default)]
294    pub buttons: Vec<SystemPopupButton>,
295}
296
297/// One button on a [`SystemPopup`].
298#[derive(Clone, Debug, Serialize, Deserialize)]
299#[serde(rename_all = "camelCase")]
300pub struct SystemPopupButton {
301    /// Stable identifier for the button.
302    pub id: String,
303    /// Visible button label.
304    pub label: String,
305    /// Semantic role (`"cancel"` / `"destructive"` / `"default"`).
306    pub role: String,
307    /// Whether tapping this button performs a destructive action.
308    #[serde(default)]
309    pub dangerous: bool,
310    /// Optional outcome hint (e.g. `"grants location permission"`).
311    #[serde(rename = "outcomeHint", default)]
312    pub outcome_hint: Option<String>,
313}
314
315/// `POST /system-popup-action` request body.
316///
317/// `popupId` and `buttonId` round-trip from a prior `GET /system-popups`
318/// enumerate (`Popup.id` / `PopupButton.id` fields). The runner walks the
319/// same scan order on the act path, so callers do not need to maintain an
320/// out-of-band id map.
321#[derive(Clone, Debug, Serialize, Deserialize)]
322#[serde(rename_all = "camelCase")]
323pub struct SystemPopupActionRequest {
324    /// Popup id from a prior `Popup.id` enumerate.
325    pub popup_id: String,
326    /// Button id from a prior `PopupButton.id` enumerate.
327    pub button_id: String,
328}
329
330/// `POST /system-popup-action` response body.
331///
332/// `ok=true` ⇒ the runner found the popup + button and dispatched a
333/// daemonProxy touch; `ok=false` ⇒ neither side matched (either popup id
334/// missed, button id missed, or synthesize raised inside the runner).
335#[derive(Clone, Debug, Default, Serialize, Deserialize)]
336#[serde(rename_all = "camelCase")]
337pub struct SystemPopupActionResponse {
338    /// Whether the popup-button match + tap dispatch succeeded.
339    #[serde(default)]
340    pub ok: bool,
341    /// Wire-layer error discriminator ("not_found" / "bad_request" / etc.)
342    /// emitted by the runner on the non-2xx path. Absent on success.
343    #[serde(default, skip_serializing_if = "Option::is_none")]
344    pub error: Option<String>,
345}
346
347/// `GET /system-popups` response body.
348#[derive(Clone, Debug, Default, Serialize, Deserialize)]
349#[serde(rename_all = "camelCase")]
350pub struct SystemPopupsResponse {
351    /// All popups currently on screen (empty when none).
352    #[serde(default)]
353    pub popups: Vec<SystemPopup>,
354}
355
356// -------------------- /record/* wire shape ------------------------------
357
358/// One recorder event captured by `/record/start` → `/record/poll` flow.
359///
360/// The Swift `EventRecorder` emits the notification discriminator as
361/// `rawCode`, not `code`. Field names here mirror that schema exactly
362/// (`raw_code` + serde camelCase → `rawCode`); a mismatch deserializes
363/// silently to `0` rather than erroring, so the naming is load-bearing.
364///
365/// `extra` is a flatten catch-all for the enrich fields Swift splats onto
366/// the top level of `RecordedEvent` (`kind` / `frame` /
367/// `payloadDescription` / `elementType` / …), so new ones are accepted
368/// without a wire break.
369#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
370#[serde(rename_all = "camelCase")]
371pub struct RecordedEvent {
372    /// Numeric event-type discriminator (Swift `RecordedEvent.rawCode`),
373    /// carrying the raw kAXNotification int. Typical values: 1018
374    /// (kAXFirstResponderChangedNotification) / 1028
375    /// (kAXHIDEventReceivedNotification) / 4002 (kAXUserTestingNotification)
376    /// / 1006 (kAXAlertNotification) / 1021 (kAXPidStatusChangedNotification).
377    #[serde(default)]
378    pub raw_code: i32,
379    /// Capture-time timestamp in milliseconds.
380    #[serde(default)]
381    pub timestamp_ms: f64,
382    /// Free-form per-event enrich fields that the Swift side splats onto
383    /// the top level (`kind` / `frame` / `payloadDescription` /
384    /// `elementType` / `appBundleId` / `payloadClassName` / …).
385    /// Reconciliation reads only `raw_code` + `timestamp_ms` and never
386    /// depends on this; consumers wanting detail can read it on demand.
387    #[serde(flatten, default)]
388    pub extra: serde_json::Map<String, serde_json::Value>,
389}
390
391/// `GET /record/poll` / `POST /record/stop` response body.
392#[derive(Clone, Debug, Default, Serialize, Deserialize)]
393#[serde(rename_all = "camelCase")]
394pub struct RecordEventsResponse {
395    /// Events captured since the last poll (chronological).
396    #[serde(default)]
397    pub events: Vec<RecordedEvent>,
398}
399
400// -------------------- /session/* wire shape ------------------------------
401//
402// Session lifecycle addresses the "activation storm" root cause: without a
403// session the runner re-binds + `.activate()`s an `XCUIApplication` on every
404// request whose `App-Activate: true` header is set. Long-running gates (visual /
405// perf regression) accumulate thousands of activate calls, exhausting
406// XCTest process arbitration on iOS 26.5+ and crashing `test_runForever()`
407// mid-run. Sessions replace that with a one-shot lifecycle: open once,
408// runner caches the binding + activates at most on transition or via
409// explicit renew, close when the client is done.
410//
411// Wire compat: absent `Session-Id: <id>` header on any request falls
412// through to the legacy per-request `resolveApp()` path, now itself
413// rate-limited to at most one `.activate()` per 5 s per bundle-id (which
414// is enough to keep the recovery-from-drift semantic of the original
415// design without producing the storm).
416
417/// `POST /session/open` request body.
418#[derive(Clone, Debug, Serialize, Deserialize)]
419#[serde(rename_all = "camelCase")]
420pub struct SessionOpenRequest {
421    /// Bundle id (iOS) / package name (Android) the session is bound to.
422    /// Empty string means "use the runner's boot-time default", which is
423    /// almost always `com.apple.Preferences` — usable for testing but
424    /// probably not what the client wants.
425    #[serde(default)]
426    pub bundle_id: String,
427    /// If true, the runner calls `.activate()` once as part of the open,
428    /// synchronously, before returning. Idiomatic for gates that want
429    /// the target app foregrounded before the first `/tap` fires.
430    #[serde(default)]
431    pub activate: bool,
432}
433
434/// `POST /session/open` response body.
435///
436/// The returned `session_id` becomes the value of the `Session-Id`
437/// request header on every subsequent request that should share this
438/// session's cached app binding.
439#[derive(Clone, Debug, Serialize, Deserialize)]
440#[serde(rename_all = "camelCase")]
441pub struct SessionOpenResponse {
442    /// Opaque token; treat as a stable string identifier. UUID today.
443    pub session_id: String,
444    /// Whether the runner issued an initial `.activate()` on open.
445    /// Mirrors the request's `activate` field unless the runner
446    /// rate-limited it (e.g. same bundle-id was activated within the
447    /// last 5 s from a prior session).
448    #[serde(default)]
449    pub activated_once: bool,
450    /// Server-side epoch millis at open. Consumers pair this with
451    /// downstream `sessionUptimeMs` sidecar fields to reconstruct
452    /// session timelines.
453    #[serde(default)]
454    pub server_time_ms: u64,
455}
456
457/// `POST /session/close` request body.
458#[derive(Clone, Debug, Serialize, Deserialize)]
459#[serde(rename_all = "camelCase")]
460pub struct SessionCloseRequest {
461    /// Session to close. Absent / unknown / already-closed sessions
462    /// return 200 with `ok=true` — idempotent.
463    pub session_id: String,
464}
465
466/// `POST /session/close` response body.
467#[derive(Clone, Debug, Default, Serialize, Deserialize)]
468#[serde(rename_all = "camelCase")]
469pub struct SessionCloseResponse {
470    /// True unless the runner failed to remove the session cache entry.
471    /// Not a "session was known" flag — closing an unknown session is
472    /// idempotent success.
473    pub ok: bool,
474}
475
476/// `POST /session/renew-activation` request body.
477///
478/// Client-side escape hatch when the client detects target-app drift
479/// (e.g. `/tree` returned `snapshot_unavailable`, or a foreground steal
480/// by SpringBoard). The runner re-issues `.activate()` on the cached
481/// binding subject to the same 5 s / bundle-id rate limit.
482#[derive(Clone, Debug, Serialize, Deserialize)]
483#[serde(rename_all = "camelCase")]
484pub struct SessionRenewActivationRequest {
485    /// Session to renew. Unknown session → 404.
486    pub session_id: String,
487}
488
489/// `POST /session/renew-activation` response body.
490#[derive(Clone, Debug, Default, Serialize, Deserialize)]
491#[serde(rename_all = "camelCase")]
492pub struct SessionRenewActivationResponse {
493    /// True on success (session known + not-rate-limited).
494    pub ok: bool,
495    /// Whether the runner actually issued `.activate()` this call, or
496    /// suppressed it because the previous activation was within the
497    /// rate-limit window. `ok=true, activated=false` is a valid outcome
498    /// meaning "session is fresh enough, no-op".
499    #[serde(default)]
500    pub activated: bool,
501}
502
503/// Extended `GET /health` response body.
504///
505/// The body is purely additive over the legacy bare-200 response.
506/// Wire schema versions this build speaks.
507///
508/// The schema is versioned apart from the runner, because they are not the
509/// same thing. A runner that has been up since before a CLI upgrade, and an
510/// SDK released on its own cadence, both talk to a wire whose shape may not
511/// have moved at all. Tying them to the runner's semver made every version
512/// difference an error, including the ones that did not matter.
513///
514/// Add a version here when the shape changes, and keep the old one for as
515/// long as it is still spoken.
516pub const WIRE_SCHEMA_SUPPORTED: &[u32] = &[1, 2];
517
518/// The newest schema both ends speak, or `None` when they share none.
519///
520/// Highest-common rather than exact-match: two builds that both know schema
521/// 2 agree on schema 2, whatever their versions say.
522#[must_use]
523pub fn negotiate_wire_schema(ours: &[u32], theirs: &[u32]) -> Option<u32> {
524    ours.iter().filter(|v| theirs.contains(v)).copied().max()
525}
526
527/// What a runner says about the wire it speaks.
528#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
529#[serde(rename_all = "camelCase")]
530pub struct WireSchemaInfo {
531    /// Every schema the runner speaks.
532    #[serde(default)]
533    pub supports: Vec<u32>,
534    /// The one it settled on with the client that asked, when the client
535    /// said what it speaks. Absent from a runner too old to have been asked.
536    #[serde(default)]
537    pub negotiated: Option<u32>,
538}
539
540/// Consumers that ignore the body get identical behavior; consumers
541/// that parse the JSON gain liveness observability.
542#[derive(Clone, Debug, Default, Serialize, Deserialize)]
543#[serde(rename_all = "camelCase")]
544pub struct HealthResponse {
545    /// Runner alive.
546    pub ok: bool,
547    /// Runner semver (matches the smix-cli that shipped it).
548    #[serde(default)]
549    pub runner_version: String,
550    /// Runner uptime in milliseconds.
551    #[serde(default)]
552    pub uptime_ms: u64,
553    /// Epoch millis of the runner's most recent processed request
554    /// (any route). 0 if the runner has served no requests yet.
555    #[serde(default)]
556    pub last_request_at_ms: u64,
557    /// Currently-open session count.
558    #[serde(default)]
559    pub sessions_open: u32,
560    /// Total `.activate()` calls issued since runner boot.
561    #[serde(default)]
562    pub activations_total: u64,
563    /// SimRenderServer pid + alive flag observed by the runner's
564    /// sim-health sensor. `alive = false` after
565    /// `com.apple.display.captureservice` internal assertion trips.
566    #[serde(default)]
567    pub sim_render_server: HealthProcessInfo,
568    /// xcodebuild test-host pid + alive flag + total restart count
569    /// (auto-restart on `** TEST INTERRUPTED **`).
570    #[serde(default)]
571    pub xcodebuild_test_host: HealthTestHostInfo,
572    /// The wire this runner speaks. Empty from a runner that predates the
573    /// question — which means "unknown", not "none".
574    #[serde(default)]
575    pub wire_schema: WireSchemaInfo,
576}
577
578/// Pid + alive flag for a watched process. Additive to
579/// [`HealthResponse`].
580#[derive(Clone, Debug, Default, Serialize, Deserialize)]
581#[serde(rename_all = "camelCase")]
582pub struct HealthProcessInfo {
583    /// True when the runner last observed the process alive.
584    #[serde(default)]
585    pub alive: bool,
586    /// Last-known pid (0 if never observed).
587    #[serde(default)]
588    pub pid: u32,
589}
590
591/// xcodebuild test-host health with restart accounting.
592#[derive(Clone, Debug, Default, Serialize, Deserialize)]
593#[serde(rename_all = "camelCase")]
594pub struct HealthTestHostInfo {
595    /// True when the runner-side supervisor last saw xcodebuild alive.
596    #[serde(default)]
597    pub alive: bool,
598    /// Last-known pid (0 if unrecorded).
599    #[serde(default)]
600    pub pid: u32,
601    /// Number of times the supervisor has restarted the test-host.
602    #[serde(default)]
603    pub restart_count: u32,
604}
605
606/// `POST /session/close-all` — backs `smix runner cycle`. Runner-side
607/// clears every open session and returns the count that was cleared.
608#[derive(Clone, Debug, Default, Serialize, Deserialize)]
609#[serde(rename_all = "camelCase")]
610pub struct SessionCloseAllResponse {
611    /// True on success (idempotent — closing an empty session table
612    /// is not an error).
613    pub ok: bool,
614    /// Number of sessions closed.
615    #[serde(default)]
616    pub closed: u32,
617}
618
619/// `POST /session/relaunch-app` request body.
620///
621/// Instructs the runner to `terminate()` + `launch()` the session's
622/// cached `XCUIApplication` binding IN PLACE — same test-host process,
623/// same session id, same XCUITest binding. Used to recover from a
624/// downstream app crash without cycling the entire runner.
625#[derive(Clone, Debug, Serialize, Deserialize)]
626#[serde(rename_all = "camelCase")]
627pub struct SessionRelaunchAppRequest {
628    /// Session whose cached binding will be relaunched.
629    pub session_id: String,
630}
631
632/// `POST /session/relaunch-app` response body.
633#[derive(Clone, Debug, Default, Serialize, Deserialize)]
634#[serde(rename_all = "camelCase")]
635pub struct SessionRelaunchAppResponse {
636    /// True on success (session known + relaunch cycle completed).
637    pub ok: bool,
638    /// Wall-clock milliseconds the terminate+launch cycle took.
639    #[serde(default)]
640    pub wall_ms: u64,
641}
642
643/// Request body shared by `POST /session/terminate-app` and
644/// `POST /session/launch-app`.
645///
646/// Carries launch-argument / launch-environment injection so consumers
647/// can bypass scaffolding like Expo dev-launcher server pickers that
648/// vanish on clearAppData (SDK 57 stops auto-navigating on URL scheme).
649// Not `#[non_exhaustive]` — consumers construct these directly. Wire
650// evolution is handled by `#[serde(default)]` on each field, so
651// adding a field is source-compatible for anyone using
652// `..Default::default()` in their struct literal (idiomatic pattern
653// in the SDK). The response variant DOES carry `#[non_exhaustive]`
654// because consumers only READ it, not construct.
655#[derive(Clone, Debug, Default, Serialize, Deserialize)]
656#[serde(rename_all = "camelCase")]
657pub struct SessionAppLifecycleRequest {
658    /// Session whose cached `XCUIApplication` binding will be acted on.
659    pub session_id: String,
660    /// launchArguments passed to `XCUIApplication.launch()`. Empty vec
661    /// leaves whatever the runner already had cached on
662    /// `entry.app.launchArguments` (empty by default).
663    /// Ignored by `/session/terminate-app`.
664    #[serde(default)]
665    pub args: Vec<String>,
666    /// launchEnvironment passed to `XCUIApplication.launch()`. Empty map
667    /// leaves the runner's cached environment untouched. Ignored by
668    /// `/session/terminate-app`.
669    #[serde(default)]
670    pub env: std::collections::BTreeMap<String, String>,
671    /// After `.launch()` dispatches, poll `XCUIApplication.state` at
672    /// 250 ms cadence until `.runningForeground` (or timeout). Prevents
673    /// callers from firing a subsequent terminateApp before the process
674    /// has signalled launchd ready — the root cause of
675    /// `bug_type: 309 exec_terminated_before_ready` `.ips` writes.
676    /// `None` = fire-and-return semantics; `Some(0)` = wait one
677    /// iteration then return terminal state (useful for tests).
678    /// Default: `Some(15000)` at the SDK layer.
679    #[serde(default)]
680    pub wait_for_foreground_ms: Option<u64>,
681    /// After `.runningForeground` is observed (or immediately when
682    /// `wait_for_foreground_ms == None`), poll the a11y tree at 500 ms
683    /// cadence looking for ≥ `minIdentifierCount` descendants with a
684    /// non-empty `accessibilityIdentifier` NOT in the interactive-probe
685    /// ignore list. Fires `launchAppReachedInteractive` when found; on
686    /// timeout fires `launchAppTimedOutBeforeInteractive`. Both counters
687    /// live on [`SessionLifecycleCounters`].
688    ///
689    /// `None` = fire-and-return (no interactive polling). Consumer config
690    /// `.smix/config.yaml interactiveProbe: { minIdentifierCount, ignore: [...] }`
691    /// forwards to the runner via `TEST_RUNNER_SMIX_INTERACTIVE_PROBE_JSON`
692    /// at boot; defaults are `minIdentifierCount: 3` and
693    /// `ignore: ["SplashScreenLogo"]`.
694    #[serde(default)]
695    pub wait_for_interactive_ms: Option<u64>,
696}
697
698/// Response for `POST /session/terminate-app` and
699/// `POST /session/launch-app`.
700#[derive(Clone, Debug, Default, Serialize, Deserialize)]
701#[serde(rename_all = "camelCase")]
702#[non_exhaustive]
703pub struct SessionAppLifecycleResponse {
704    /// True on success.
705    pub ok: bool,
706    /// Wall-clock milliseconds the terminate or launch took.
707    #[serde(default)]
708    pub wall_ms: u64,
709    /// Wall-clock milliseconds spent inside the wait-for-foreground
710    /// loop. Zero when the caller passed `wait_for_foreground_ms: 0`
711    /// or when the runner does not implement the wait.
712    #[serde(default)]
713    pub waited_ms: u64,
714    /// Final observed `XCUIApplication.state` at the moment the runner
715    /// returned. Wire-encoded as the raw `Int` value XCTest uses:
716    /// `0` unknown, `1` notRunning, `2` runningBackgroundSuspended,
717    /// `3` runningBackground, `4` runningForeground. Zero when the
718    /// caller opted out or the runner does not implement the wait.
719    #[serde(default)]
720    pub terminal_state: u8,
721    /// Set when the runner observed cooperative
722    /// termination (`XCUIApplication.terminate()` observed
723    /// `.notRunning` before timeout). `false` on `terminate-app` when
724    /// the runner had to fall back to a hard signal.
725    /// Only meaningful on `terminate-app` responses; `false` on
726    /// `launch-app`.
727    #[serde(default)]
728    pub terminated_cooperatively: bool,
729    /// Set on `launch-app` responses when the
730    /// interactive-probe (≥ `minIdentifierCount` non-empty ax-ids
731    /// outside the ignore list) fired inside `wait_for_interactive_ms`.
732    /// `false` when the caller didn't set `wait_for_interactive_ms`
733    /// OR when polling timed out without observing the interactive
734    /// fingerprint.
735    #[serde(default)]
736    pub reached_interactive: bool,
737    /// Sample of up to 8 `accessibilityIdentifier`
738    /// values observed at the moment `reached_interactive` fired.
739    /// Non-normative; useful for consumers debugging "did my
740    /// interactive probe fire on the right screen". Empty when
741    /// `reached_interactive == false` or the caller didn't set
742    /// `wait_for_interactive_ms`.
743    #[serde(default)]
744    pub interactive_named_ids: Vec<String>,
745}
746
747/// One entry in `POST /session/list` response.
748#[derive(Clone, Debug, Serialize, Deserialize)]
749#[serde(rename_all = "camelCase")]
750pub struct SessionSummary {
751    /// Session id.
752    pub session_id: String,
753    /// Bundle id the session's XCUIApplication is bound to.
754    pub bundle_id: String,
755    /// Epoch millis of open time.
756    #[serde(default)]
757    pub opened_at_ms: u64,
758    /// Epoch millis of last `.activate()` on this session (renew or
759    /// open). Distinct from the runner-internal `lastAccessedAt` used
760    /// by the idle-close sweep.
761    #[serde(default)]
762    pub last_activated_at_ms: u64,
763    /// Last non-empty interactive-probe sample of named accessibility
764    /// ids seen for this session's app. The runner sent this on every
765    /// list/diagnostic entry (and this crate's own docs referenced it)
766    /// while the struct lacked the field, so serde silently dropped it.
767    #[serde(default)]
768    pub interactive_named_ids: Vec<String>,
769}
770
771/// `POST /session/list` response body.
772#[derive(Clone, Debug, Default, Serialize, Deserialize)]
773#[serde(rename_all = "camelCase")]
774pub struct SessionListResponse {
775    /// Every session currently known to the runner.
776    #[serde(default)]
777    pub sessions: Vec<SessionSummary>,
778}
779
780/// One entry in the subprocess ring buffer.
781#[derive(Clone, Debug, Serialize, Deserialize)]
782#[serde(rename_all = "camelCase")]
783pub struct SubprocessRecord {
784    /// argv passed to the invoked binary.
785    pub argv: Vec<String>,
786    /// Exit code; `None` when the process failed to spawn.
787    #[serde(default)]
788    pub exit_code: Option<i32>,
789    /// Wall-clock milliseconds.
790    #[serde(default)]
791    pub wall_ms: u64,
792    /// First 256 bytes of stderr.
793    #[serde(default)]
794    pub stderr_head: String,
795    /// Epoch millis when the invocation completed.
796    #[serde(default)]
797    pub timestamp_ms: u64,
798}
799
800/// App-alive cache observability counters.
801/// Always emitted (even when the runner was booted without an
802/// `appAliveCache` — `wired: false` sentinel + all-zero counters).
803/// Consumers use `wired` to distinguish "workload never fired the
804/// re-probe path" from "runner version predates this observability".
805#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize)]
806#[serde(rename_all = "camelCase")]
807#[non_exhaustive]
808pub struct AliveCacheCounters {
809    /// `false` sentinel — either the runner omits the field entirely
810    /// or it was booted without a cache. When `true`, the field values
811    /// reflect an actual live cache.
812    #[serde(default)]
813    pub wired: bool,
814    /// Total calls to `AppAliveCache::markDead`.
815    #[serde(default)]
816    pub mark_dead_total: u64,
817    /// Total calls to `AppAliveCache::markAlive` (explicit + re-probe-success).
818    #[serde(default)]
819    pub mark_alive_total: u64,
820    /// `isSuppressed` returned true — a call was short-circuited.
821    #[serde(default)]
822    pub suppress_hit_total: u64,
823    /// `isSuppressed` returned false — a call was allowed through.
824    #[serde(default)]
825    pub suppress_miss_total: u64,
826    /// Re-probe Task spawned.
827    #[serde(default)]
828    pub reprobe_attempted_total: u64,
829    /// Re-probe observed target return to running.
830    #[serde(default)]
831    pub reprobe_succeeded_total: u64,
832    /// Re-probe was invalidated mid-flight by external markAlive.
833    #[serde(default)]
834    pub reprobe_invalidated_early: u64,
835    /// Re-probe ran all 6 iterations without recovery.
836    #[serde(default)]
837    pub reprobe_exhausted_window: u64,
838}
839
840/// Cumulative session lifecycle counters.
841///
842/// Unlike the instantaneous `sessions: Vec<SessionSummary>` view,
843/// these are advanced on every mutation and survive `close`. The split
844/// `terminate_app_via_xcuiapplication` / `terminate_app_via_fallback`
845/// counters answer "did clearAppData actually use the cooperative
846/// pathway or fall back to SIGKILL".
847#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize)]
848#[serde(rename_all = "camelCase")]
849#[non_exhaustive]
850pub struct SessionLifecycleCounters {
851    /// Total `POST /session/open` outcomes.
852    #[serde(default)]
853    pub opened_total: u64,
854    /// Total `POST /session/close` outcomes (idempotent — includes closes
855    /// of unknown sessions).
856    #[serde(default)]
857    pub closed_total: u64,
858    /// Total `POST /session/relaunch-app` outcomes.
859    #[serde(default)]
860    pub relaunch_app_total: u64,
861    /// Total `POST /session/terminate-app` outcomes.
862    #[serde(default)]
863    pub terminate_app_total: u64,
864    /// Terminate calls that observed the target `.notRunning` before
865    /// the XCUIApplication timeout — cooperative pathway succeeded.
866    #[serde(default)]
867    pub terminate_app_via_xcuiapplication: u64,
868    /// Terminate calls where XCUIApplication timed out and the runner
869    /// fell back to a hard-kill pathway. `> 0` is the smoking gun for
870    /// a non-cooperative teardown.
871    #[serde(default)]
872    pub terminate_app_via_fallback: u64,
873    /// Total `POST /session/launch-app` outcomes.
874    #[serde(default)]
875    pub launch_app_total: u64,
876    /// Launch calls that observed `.runningForeground` inside the
877    /// requested `wait_for_foreground_ms` window.
878    #[serde(default)]
879    pub launch_app_reached_foreground: u64,
880    /// Launch calls that timed out waiting for foreground.
881    #[serde(default)]
882    pub launch_app_timed_out_before_foreground: u64,
883    /// Total `resetAppData` verbs dispatched (URL-scheme JS-wipe
884    /// pattern, separate from `clearAppData`'s container-wipe pathway).
885    #[serde(default)]
886    pub reset_app_data_total: u64,
887    /// resetAppData calls where the completion
888    /// signal (log-line pattern match on the metro log tail) never
889    /// arrived inside the timeout window. `> 0` = the URL fired but
890    /// the app didn't emit the expected `[dev] reset-complete` line.
891    #[serde(default)]
892    pub reset_app_data_timed_out: u64,
893    /// Launch calls that observed the
894    /// interactive fingerprint (`≥ minIdentifierCount` non-ignored
895    /// ax-ids in the a11y tree) inside `wait_for_interactive_ms`.
896    /// Distinct from `launch_app_reached_foreground` which only
897    /// tracks process state, not tree probeability.
898    #[serde(default)]
899    pub launch_app_reached_interactive: u64,
900    /// Launch calls that timed out waiting for the interactive
901    /// fingerprint. Non-zero = "process foreground but tree unusable"
902    /// — typically a splash screen whose descendants are all unnamed.
903    #[serde(default)]
904    pub launch_app_timed_out_before_interactive: u64,
905}
906
907/// Per-flow attempt attribution. Populated by
908/// `smix run --retry <N>` (default 1) as each flow completes; carries
909/// through `/diagnostic/dump` so consumers can attribute a `.ips` to
910/// a specific retry rather than a whole batch.
911#[derive(Clone, Debug, Default, Serialize, Deserialize)]
912#[serde(rename_all = "camelCase")]
913#[non_exhaustive]
914pub struct FlowAttemptRecord {
915    /// Flow name (yaml basename or explicit id).
916    #[serde(default)]
917    pub flow_name: String,
918    /// Ordered attempts. Retry #0 is the first try; retry #1 is
919    /// second; etc.
920    #[serde(default)]
921    pub attempts: Vec<FlowAttempt>,
922}
923
924/// One attempt within a flow (see [`FlowAttemptRecord`]).
925#[derive(Clone, Debug, Default, Serialize, Deserialize)]
926#[serde(rename_all = "camelCase")]
927#[non_exhaustive]
928pub struct FlowAttempt {
929    /// Zero-based retry index. `0` = first try.
930    #[serde(default)]
931    pub attempt_index: u32,
932    /// Overall outcome: "ok" / "timeout" / "error" / "crashed".
933    #[serde(default)]
934    pub status: String,
935    /// Free-form error class code when non-ok (e.g., "TIMEOUT",
936    /// "DRIVER_ERROR", "APP_UNAVAILABLE"). Empty on success.
937    #[serde(default)]
938    pub error_class: Option<String>,
939    /// If a `.ips` file appeared under `~/Library/Logs/DiagnosticReports/`
940    /// during this attempt's window, its filename. Consumers grep for
941    /// this to tie a crash-report to a specific retry.
942    #[serde(default)]
943    pub ips_generated: Option<String>,
944    /// Wall-clock milliseconds this attempt ran.
945    #[serde(default)]
946    pub wall_ms: u64,
947}
948
949/// `POST /diagnostic/dump` response body.
950///
951/// Snapshot of the runner's runtime state: recent subprocess
952/// invocations, currently-open sessions, sim health state, supervisor
953/// pid, plus the always-emitted app-alive cache + cumulative session
954/// lifecycle counters that answer "is the observability instrumented?"
955/// as a numeric question, not a grep for a log line that may or may
956/// not survive a supervisor cycle.
957#[derive(Clone, Debug, Default, Serialize, Deserialize)]
958#[serde(rename_all = "camelCase")]
959#[non_exhaustive]
960pub struct DiagnosticDumpResponse {
961    /// Recent `xcrun simctl` invocations recorded by the runner's
962    /// subprocess ring buffer. Ordered oldest → newest, capped at 128.
963    #[serde(default)]
964    pub recent_subprocesses: Vec<SubprocessRecord>,
965    /// Every session currently known to the runner (mirrors
966    /// `/session/list`; embedded here for one-shot dump).
967    #[serde(default)]
968    pub sessions: Vec<SessionSummary>,
969    /// Coarse sim-health classification at dump time.
970    #[serde(default)]
971    pub sim_health: String,
972    /// Pid of the supervisor sidecar, when spawned via
973    /// `smix runner up --supervise`.
974    #[serde(default)]
975    pub supervisor_pid: Option<u32>,
976    /// Runner wall-clock uptime in milliseconds.
977    #[serde(default)]
978    pub uptime_ms: u64,
979    /// Always-present. `wired=false` when the runner didn't have an
980    /// `AppAliveCache` wired at boot (opt-out) or doesn't implement
981    /// this observability. When `wired=true`, the counter
982    /// fields reflect an actual live cache — even all-zero is
983    /// meaningful ("workload didn't fire the re-probe path").
984    #[serde(default)]
985    pub alive_cache: AliveCacheCounters,
986    /// Cumulative session lifecycle counters. Advance on every
987    /// mutation, survive close, and are persisted alongside the
988    /// session-persistence file so `smix runner cycle` doesn't wipe
989    /// them.
990    #[serde(default)]
991    pub session_counters: SessionLifecycleCounters,
992    /// Trailing N lines from the external
993    /// metro log the CLI was told to tail (via `--metro-log <path>`
994    /// on `smix run` or `smix diagnostic dump`). Empty when the CLI
995    /// was not given a log path OR when the file was unreadable at
996    /// dump time. Default N is 200 lines; consumer overrides with
997    /// `--metro-log-tail-lines <N>`. Purely additive — a consumer
998    /// ignoring this field sees no behavior change.
999    #[serde(default)]
1000    pub metro_log_tail: Vec<String>,
1001    /// Retry-attribution roll-up. Populated by
1002    /// `smix run` when it has driven at least one flow. Each entry
1003    /// carries per-attempt status + errorClass + any `.ips` generated
1004    /// so consumers can tell "flow X passed on retry 2 after retry 1
1005    /// crashed" from "flow X passed on the first try". Empty when no
1006    /// flow context available at dump time.
1007    #[serde(default)]
1008    pub recent_flows: Vec<FlowAttemptRecord>,
1009    /// Most-recent `interactiveNamedIds` sample observed
1010    /// across all `launchApp` completions since runner boot. Survives
1011    /// session teardown so post-batch triage can see WHICH ax-ids
1012    /// triggered `reachedInteractive` on the last observed launch,
1013    /// not just the count. Empty when no launch this run.
1014    ///
1015    /// Per-session values remain on `sessions[n].interactiveNamedIds`
1016    /// but go with the session at teardown. This top-level field is
1017    /// the last-values-standing for post-mortem observation.
1018    #[serde(default)]
1019    pub last_interactive_named_ids: Vec<String>,
1020}
1021
1022/// Session state exposed to SDK consumers via the `X-Sim-Health`
1023/// response header on every runner response.
1024///
1025/// Purely additive — consumers that ignore the header are unaffected;
1026/// consumers that read it get `Degraded` / `Dead` / `Cycling`
1027/// transitions without polling.
1028#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1029#[non_exhaustive]
1030pub enum SimHealthWireState {
1031    /// All watched signals inside envelope.
1032    #[serde(rename = "healthy")]
1033    Healthy,
1034    /// At least one signal degraded (screenshot p95 slow, /health
1035    /// stale, etc.).
1036    #[serde(rename = "degraded")]
1037    Degraded,
1038    /// Runner is mid-cycle (supervisor auto-restart in progress).
1039    /// Callers should back off until the next `Healthy` transition.
1040    #[serde(rename = "cycling")]
1041    Cycling,
1042    /// Runner or a watched subprocess (SimRenderServer / xcodebuild)
1043    /// is gone. Callers should bail.
1044    #[serde(rename = "dead")]
1045    Dead,
1046}
1047
1048impl SimHealthWireState {
1049    /// Parse a case-insensitive wire string; returns `None` on
1050    /// unknown values so unrecognized future states don't panic.
1051    pub fn from_header(value: &str) -> Option<Self> {
1052        match value.trim().to_ascii_lowercase().as_str() {
1053            "healthy" => Some(Self::Healthy),
1054            "degraded" => Some(Self::Degraded),
1055            "cycling" => Some(Self::Cycling),
1056            "dead" => Some(Self::Dead),
1057            _ => None,
1058        }
1059    }
1060
1061    /// Header string emitted on the runner side.
1062    pub fn as_header(&self) -> &'static str {
1063        match self {
1064            Self::Healthy => "healthy",
1065            Self::Degraded => "degraded",
1066            Self::Cycling => "cycling",
1067            Self::Dead => "dead",
1068        }
1069    }
1070}
1071
1072/// A rectangle as the runner reports it.
1073#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
1074pub struct Rect {
1075    /// Left edge, in the space whose rectangle this is.
1076    pub x: f64,
1077    /// Top edge, same space.
1078    pub y: f64,
1079    /// Width. Compared against the other rectangle's, which is how a
1080    /// landscape screen described by a portrait frame shows up.
1081    pub w: f64,
1082    /// Height.
1083    pub h: f64,
1084}
1085
1086/// The two coordinate spaces a tap passes through, and the orientation
1087/// the synthesised event is stamped with.
1088///
1089/// `GET /coordinate-space`. Reported together because separately they
1090/// are three unremarkable numbers: the defect they exist to expose is
1091/// the relationship between them — a point computed against the app's
1092/// frame and then read in whatever space the event is stamped with.
1093#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1094#[serde(rename_all = "camelCase")]
1095pub struct CoordinateSpace {
1096    /// What a normalised offset is multiplied by to get a point.
1097    pub app_frame: Rect,
1098    /// What `/tree` describes the screen as.
1099    pub snapshot_root_frame: Rect,
1100    /// What the device says it is rotated to. A simulator that has
1101    /// never been rotated answers `unknown`, and an app can be laid out
1102    /// landscape while this stays `portrait` — so it is reported, not
1103    /// used as the verdict.
1104    pub device_orientation: String,
1105    /// The orientation stamped on the synthesised event, which decides
1106    /// which space the point above is read in.
1107    pub event_record_orientation: String,
1108    /// The runner's own verdict on whether the point will be read in
1109    /// the space it was computed in.
1110    pub spaces_agree: bool,
1111}