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}` → 200/`{ok}`
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 /scroll` `{selector, direction}` → `{matched, swipes}`
34//! - `POST /swipe-once` `{direction}` → `{ok}`
35//! - `POST /foreground` `{bundleId}` → `{ok}`
36//! - `POST /hide-keyboard` → `{ok}`
37//! - `POST /back` → `{ok}`
38//! - `POST /record/start` → `{ok}`
39//! - `GET /record/poll` → `{events: [`[`RecordedEvent`]`]}`
40//! - `POST /record/stop` → `{events: [`[`RecordedEvent`]`]}`
41
42#![doc(html_root_url = "https://docs.smix.dev/smix-runner-wire")]
43
44use serde::{Deserialize, Serialize};
45use smix_selector::Selector;
46use thiserror::Error;
47
48// -------------------- Errors --------------------------------------------
49
50/// Transport-level failure variants exposed by the HTTP client. The
51/// concrete `reqwest::Error` source lives in `smix-runner-client`; the
52/// wire stone exposes only the discriminator + endpoint context so
53/// non-HTTP transports can reuse the variants.
54#[derive(Debug, Error)]
55pub enum RunnerTransportErrorKind {
56 /// Network / transport-layer fetch error (timeout, DNS, TLS, etc.).
57 #[error("runner {endpoint} fetch failed")]
58 FetchFailed {
59 /// Endpoint path that failed (e.g. `"/tap"`).
60 endpoint: String,
61 },
62 /// Runner returned non-2xx HTTP status.
63 #[error("runner {endpoint} returned status {status}: {body}")]
64 NonSuccessStatus {
65 /// Endpoint path that returned the error.
66 endpoint: String,
67 /// HTTP status code.
68 status: u16,
69 /// Raw response body (may be truncated).
70 body: String,
71 },
72 /// Runner returned a body that wasn't valid JSON.
73 #[error("runner {endpoint} returned non-JSON body")]
74 NonJsonBody {
75 /// Endpoint path that returned a non-JSON body.
76 endpoint: String,
77 },
78 /// Runner returned valid JSON but it didn't match the expected schema.
79 #[error("runner {endpoint} returned malformed body: {detail}")]
80 MalformedBody {
81 /// Endpoint path that returned the malformed body.
82 endpoint: String,
83 /// Schema-mismatch detail (serde error message).
84 detail: String,
85 },
86 /// Runner is unreachable (refused / closed / not listening).
87 #[error("runner {endpoint} unreachable: {message}")]
88 Unreachable {
89 /// Endpoint path attempted.
90 endpoint: String,
91 /// Reason (e.g. "connection refused").
92 message: String,
93 },
94}
95
96// -------------------- Common wire types ---------------------------------
97
98/// `include` scope query param shared by `/tree` / `/tap` / `/fill` /
99/// `/clear` / `/find` / `/scroll` / `/system-popups`. URL-only.
100#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
101#[serde(rename_all = "camelCase")]
102pub struct RunnerIncludeOpts {
103 /// Optional include scope (e.g. system-popups → `AllWindows`).
104 #[serde(default, skip_serializing_if = "Option::is_none")]
105 pub include: Option<IncludeScope>,
106}
107
108/// `include` scope literal — currently only `all-windows` (system popups
109/// pierce the app frame).
110#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
111#[serde(rename_all = "kebab-case")]
112pub enum IncludeScope {
113 /// Include all windows (system popups, alerts) above the app frame.
114 AllWindows,
115}
116
117impl IncludeScope {
118 /// kebab-case wire string used in the query parameter value.
119 pub fn query_value(self) -> &'static str {
120 match self {
121 IncludeScope::AllWindows => "all-windows",
122 }
123 }
124}
125
126// -------------------- /tap wire shape -----------------------------------
127
128/// `POST /tap` mode discriminator.
129#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
130#[serde(rename_all = "camelCase")]
131pub enum TapMode {
132 /// Runner returns only the matched frame; host normalizes + injects
133 /// via `/tap-at-norm-coord` (v1.6 c5 default).
134 Resolve,
135 /// Runner resolves AND taps (legacy v1.1 path A, host-HID-based).
136 ResolveAndTap,
137 /// Runner resolves selector then synthesizes the touch event via the
138 /// XCTRunnerDaemonSession daemonProxy (v4.0 c3 swift G8 fix —
139 /// bypasses the XCUIElement gesture recognizer chain so RN
140 /// Pressable `RCTTouchHandler` UIGestureRecognizer receives the
141 /// touch and fires the JS-thread `onPress` callback reliably).
142 DaemonProxySynthesize,
143}
144
145/// `POST /tap` per-stage timing in milliseconds.
146#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
147#[serde(rename_all = "camelCase")]
148pub struct TapStages {
149 /// Time spent resolving the selector against the a11y tree.
150 #[serde(rename = "resolveMs", default)]
151 pub resolve_ms: f64,
152 /// Time spent dispatching the tap event itself.
153 #[serde(rename = "tapCallMs", default)]
154 pub tap_call_ms: f64,
155 /// End-to-end wall-clock for the whole tap call.
156 #[serde(rename = "totalMs", default)]
157 pub total_ms: f64,
158 /// Time spent waiting for the element to exist (implicit wait).
159 #[serde(rename = "waitExistenceMs", default)]
160 pub wait_existence_ms: f64,
161 /// Time spent reading the matched element's frame.
162 #[serde(rename = "frameReadMs", default)]
163 pub frame_read_ms: f64,
164}
165
166/// `POST /tap` response body.
167#[derive(Clone, Debug, Default, Serialize, Deserialize)]
168#[serde(rename_all = "camelCase")]
169pub struct TapResult {
170 /// Per-stage timing breakdown.
171 #[serde(default)]
172 pub stages: Option<TapStages>,
173 /// Matched element's geometric frame, when resolve succeeded.
174 #[serde(default)]
175 pub frame: Option<smix_screen::Rect>,
176 /// Application window frame (for normalizing the matched frame).
177 #[serde(rename = "appFrame", default)]
178 pub app_frame: Option<smix_screen::Rect>,
179}
180
181/// `POST /tap` request body.
182#[derive(Clone, Debug, Serialize, Deserialize)]
183#[serde(rename_all = "camelCase")]
184pub struct TapRequest {
185 /// Selector picking the tap target.
186 pub selector: Selector,
187 /// Resolve-only vs resolve-and-tap discriminator.
188 pub mode: TapMode,
189}
190
191/// `POST /tap-at-norm-coord` request body.
192#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
193#[serde(rename_all = "camelCase")]
194pub struct TapAtNormCoordRequest {
195 /// Normalized x coordinate in `(0, 1)` (app-frame relative).
196 pub nx: f64,
197 /// Normalized y coordinate in `(0, 1)` (app-frame relative).
198 pub ny: f64,
199}
200
201// -------------------- /fill /clear /press-key wire shape ----------------
202
203/// Per-stage timing returned by `/fill` / `/clear` / `/press-key`.
204#[derive(Clone, Debug, Default, Serialize, Deserialize)]
205#[serde(rename_all = "camelCase")]
206pub struct KeyboardStages {
207 /// Selector resolve time.
208 #[serde(rename = "resolveMs", default)]
209 pub resolve_ms: f64,
210 /// Time waiting for keyboard appearance after the focus tap.
211 #[serde(rename = "keyboardWaitMs", default)]
212 pub keyboard_wait_ms: f64,
213 /// Time spent typing the characters.
214 #[serde(rename = "typingMs", default)]
215 pub typing_ms: f64,
216 /// End-to-end wall-clock for the whole keyboard operation.
217 #[serde(rename = "totalMs", default)]
218 pub total_ms: f64,
219}
220
221/// `POST /fill` / `POST /clear` / `POST /press-key` response body.
222#[derive(Clone, Debug, Default, Serialize, Deserialize)]
223#[serde(rename_all = "camelCase")]
224pub struct RunnerKeyboardResult {
225 /// Tree snapshot after the keyboard operation completed (optional).
226 #[serde(default)]
227 pub tree: Option<smix_screen::A11yNode>,
228 /// Per-stage timing breakdown (optional).
229 #[serde(default)]
230 pub stages: Option<KeyboardStages>,
231}
232
233// -------------------- /find wire shape -----------------------------------
234
235/// `POST /find` request body.
236#[derive(Clone, Debug, Serialize, Deserialize)]
237#[serde(rename_all = "camelCase")]
238pub struct FindRequest {
239 /// Selector to look up.
240 pub selector: Selector,
241}
242
243/// `POST /find` response body.
244#[derive(Clone, Debug, Default, Serialize, Deserialize)]
245#[serde(rename_all = "camelCase")]
246pub struct FindResponse {
247 /// Whether the selector matched any element.
248 #[serde(default)]
249 pub exists: bool,
250 /// Whether the resolve subsystem itself succeeded.
251 #[serde(default)]
252 pub ok: bool,
253}
254
255// -------------------- /scroll wire shape --------------------------------
256
257/// Reduced selector shape used by `/scroll` (text-or-id only; complex
258/// selectors are host-side-resolved before reaching the runner).
259#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
260#[serde(untagged)]
261pub enum RunnerScrollSelector {
262 /// Match by text content.
263 Text {
264 /// Text to match against.
265 text: String,
266 },
267 /// Match by accessibility identifier.
268 Id {
269 /// Identifier to match against.
270 id: String,
271 },
272}
273
274/// `POST /scroll` response body.
275#[derive(Clone, Debug, Default, Serialize, Deserialize)]
276#[serde(rename_all = "camelCase")]
277pub struct ScrollResponse {
278 /// Whether the selector matched after scrolling (None when unknown).
279 #[serde(default)]
280 pub matched: Option<bool>,
281 /// Number of swipe iterations performed.
282 #[serde(default)]
283 pub swipes: Option<u32>,
284}
285
286// -------------------- /system-popups wire shape -------------------------
287
288/// One system-popup discovered on the screen (alert / sheet / banner).
289#[derive(Clone, Debug, Serialize, Deserialize)]
290#[serde(rename_all = "camelCase")]
291pub struct SystemPopup {
292 /// Stable identifier for matching across polls.
293 pub id: String,
294 /// Discriminator (e.g. `"alert"` / `"sheet"` / `"banner"`).
295 #[serde(rename = "type")]
296 pub kind: String,
297 /// Originator (e.g. bundle id, system framework name).
298 pub source: String,
299 /// Popup title text.
300 #[serde(default)]
301 pub title: String,
302 /// Popup body text.
303 #[serde(default)]
304 pub body: String,
305 /// Buttons available on the popup.
306 #[serde(default)]
307 pub buttons: Vec<SystemPopupButton>,
308}
309
310/// One button on a [`SystemPopup`].
311#[derive(Clone, Debug, Serialize, Deserialize)]
312#[serde(rename_all = "camelCase")]
313pub struct SystemPopupButton {
314 /// Stable identifier for the button.
315 pub id: String,
316 /// Visible button label.
317 pub label: String,
318 /// Semantic role (`"cancel"` / `"destructive"` / `"default"`).
319 pub role: String,
320 /// Whether tapping this button performs a destructive action.
321 #[serde(default)]
322 pub dangerous: bool,
323 /// Optional outcome hint (e.g. `"grants location permission"`).
324 #[serde(rename = "outcomeHint", default)]
325 pub outcome_hint: Option<String>,
326}
327
328/// `POST /system-popup-action` request body (v4.2 c2 — G9 act side).
329///
330/// `popupId` and `buttonId` round-trip from a prior `GET /system-popups`
331/// enumerate (`Popup.id` / `PopupButton.id` fields). The runner walks the
332/// same scan order on the act path, so callers do not need to maintain an
333/// out-of-band id map.
334#[derive(Clone, Debug, Serialize, Deserialize)]
335#[serde(rename_all = "camelCase")]
336pub struct SystemPopupActionRequest {
337 /// Popup id from a prior `Popup.id` enumerate.
338 pub popup_id: String,
339 /// Button id from a prior `PopupButton.id` enumerate.
340 pub button_id: String,
341}
342
343/// `POST /system-popup-action` response body.
344///
345/// `ok=true` ⇒ the runner found the popup + button and dispatched a
346/// daemonProxy touch; `ok=false` ⇒ neither side matched (either popup id
347/// missed, button id missed, or synthesize raised inside the runner).
348#[derive(Clone, Debug, Default, Serialize, Deserialize)]
349#[serde(rename_all = "camelCase")]
350pub struct SystemPopupActionResponse {
351 /// Whether the popup-button match + tap dispatch succeeded.
352 #[serde(default)]
353 pub ok: bool,
354 /// Wire-layer error discriminator ("not_found" / "bad_request" / etc.)
355 /// emitted by the runner on the non-2xx path. Absent on success.
356 #[serde(default, skip_serializing_if = "Option::is_none")]
357 pub error: Option<String>,
358}
359
360/// `GET /system-popups` response body.
361#[derive(Clone, Debug, Default, Serialize, Deserialize)]
362#[serde(rename_all = "camelCase")]
363pub struct SystemPopupsResponse {
364 /// All popups currently on screen (empty when none).
365 #[serde(default)]
366 pub popups: Vec<SystemPopup>,
367}
368
369// -------------------- /record/* wire shape ------------------------------
370
371/// One recorder event captured by `/record/start` → `/record/poll` flow.
372///
373/// v5.1 c3 S2 校正:swift `EventRecorder` 端实际 emit 的是 `rawCode` field
374/// (kAXNotification raw int — 1018 = focus change / 1028 = HID / 4002 = userTesting / ...),
375/// 不是 `code`。c2 capstone 初版 jq 用 `.code` 查 events.json 全返 null,
376/// 误判 "0 个 1018",修正后真实有 3 × 1018。SDK 端 deserialize 之前同样
377/// silent → `code` 字段永远 0。本 struct 字段名按 swift 真实 schema 对齐
378/// (`raw_code` + serde camelCase → `rawCode`),并加 `extra` flatten 兜底
379/// 把 swift 在 RecordedEvent 顶层平铺的 enrich 字段(`kind` / `frame` /
380/// `payloadDescription` / `elementType` / 等)宽松接收。
381#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
382#[serde(rename_all = "camelCase")]
383pub struct RecordedEvent {
384 /// Numeric event-type discriminator(swift `RecordedEvent.rawCode`)。
385 /// 典型值:1018 (kAXFirstResponderChangedNotification) / 1028
386 /// (kAXHIDEventReceivedNotification) / 4002 (kAXUserTestingNotification)
387 /// / 1006 (kAXAlertNotification) / 1021 (kAXPidStatusChangedNotification)。
388 #[serde(default)]
389 pub raw_code: i32,
390 /// Capture-time timestamp in milliseconds.
391 #[serde(default)]
392 pub timestamp_ms: f64,
393 /// Free-form per-event 顶层 enrich 字段(swift 端平铺 `kind` / `frame` /
394 /// `payloadDescription` / `elementType` / `appBundleId` / `payloadClassName`
395 /// 等)。reconcile 只读 `raw_code` + `timestamp_ms`,不依赖此字段;
396 /// 上层 SDK 想看明细时按需取(类型 = `serde_json::Map`)。
397 #[serde(flatten, default)]
398 pub extra: serde_json::Map<String, serde_json::Value>,
399}
400
401/// `GET /record/poll` / `POST /record/stop` response body.
402#[derive(Clone, Debug, Default, Serialize, Deserialize)]
403#[serde(rename_all = "camelCase")]
404pub struct RecordEventsResponse {
405 /// Events captured since the last poll (chronological).
406 #[serde(default)]
407 pub events: Vec<RecordedEvent>,
408}
409
410// -------------------- /session/* wire shape (v1.0.2) --------------------
411//
412// Session lifecycle addresses the "activation storm" root cause: pre-v1.0.2
413// runners re-bind + `.activate()` an `XCUIApplication` on every request
414// whose `App-Activate: true` header is set. Long-running gates (visual /
415// perf regression) accumulate thousands of activate calls, exhausting
416// XCTest process arbitration on iOS 26.5+ and crashing `test_runForever()`
417// mid-run. Sessions replace that with a one-shot lifecycle: open once,
418// runner caches the binding + activates at most on transition or via
419// explicit renew, close when the client is done.
420//
421// Wire compat: absent `Session-Id: <id>` header on any request falls
422// through to the legacy per-request `resolveApp()` path, now itself
423// rate-limited to at most one `.activate()` per 5 s per bundle-id (which
424// is enough to keep the recovery-from-drift semantic of the original
425// design without producing the storm).
426
427/// `POST /session/open` request body.
428#[derive(Clone, Debug, Serialize, Deserialize)]
429#[serde(rename_all = "camelCase")]
430pub struct SessionOpenRequest {
431 /// Bundle id (iOS) / package name (Android) the session is bound to.
432 /// Empty string means "use the runner's boot-time default", which is
433 /// almost always `com.apple.Preferences` — usable for testing but
434 /// probably not what the client wants.
435 #[serde(default)]
436 pub bundle_id: String,
437 /// If true, the runner calls `.activate()` once as part of the open,
438 /// synchronously, before returning. Idiomatic for gates that want
439 /// the target app foregrounded before the first `/tap` fires.
440 #[serde(default)]
441 pub activate: bool,
442}
443
444/// `POST /session/open` response body.
445///
446/// The returned `session_id` becomes the value of the `Session-Id`
447/// request header on every subsequent request that should share this
448/// session's cached app binding.
449#[derive(Clone, Debug, Serialize, Deserialize)]
450#[serde(rename_all = "camelCase")]
451pub struct SessionOpenResponse {
452 /// Opaque token; treat as a stable string identifier. UUID today.
453 pub session_id: String,
454 /// Whether the runner issued an initial `.activate()` on open.
455 /// Mirrors the request's `activate` field unless the runner
456 /// rate-limited it (e.g. same bundle-id was activated within the
457 /// last 5 s from a prior session).
458 #[serde(default)]
459 pub activated_once: bool,
460 /// Server-side epoch millis at open. Consumers pair this with
461 /// downstream `sessionUptimeMs` sidecar fields to reconstruct
462 /// session timelines.
463 #[serde(default)]
464 pub server_time_ms: u64,
465}
466
467/// `POST /session/close` request body.
468#[derive(Clone, Debug, Serialize, Deserialize)]
469#[serde(rename_all = "camelCase")]
470pub struct SessionCloseRequest {
471 /// Session to close. Absent / unknown / already-closed sessions
472 /// return 200 with `ok=true` — idempotent.
473 pub session_id: String,
474}
475
476/// `POST /session/close` response body.
477#[derive(Clone, Debug, Default, Serialize, Deserialize)]
478#[serde(rename_all = "camelCase")]
479pub struct SessionCloseResponse {
480 /// True unless the runner failed to remove the session cache entry.
481 /// Not a "session was known" flag — closing an unknown session is
482 /// idempotent success.
483 pub ok: bool,
484}
485
486/// `POST /session/renew-activation` request body.
487///
488/// Client-side escape hatch when the client detects target-app drift
489/// (e.g. `/tree` returned `snapshot_unavailable`, or a foreground steal
490/// by SpringBoard). The runner re-issues `.activate()` on the cached
491/// binding subject to the same 5 s / bundle-id rate limit.
492#[derive(Clone, Debug, Serialize, Deserialize)]
493#[serde(rename_all = "camelCase")]
494pub struct SessionRenewActivationRequest {
495 /// Session to renew. Unknown session → 404.
496 pub session_id: String,
497}
498
499/// `POST /session/renew-activation` response body.
500#[derive(Clone, Debug, Default, Serialize, Deserialize)]
501#[serde(rename_all = "camelCase")]
502pub struct SessionRenewActivationResponse {
503 /// True on success (session known + not-rate-limited).
504 pub ok: bool,
505 /// Whether the runner actually issued `.activate()` this call, or
506 /// suppressed it because the previous activation was within the
507 /// rate-limit window. `ok=true, activated=false` is a valid outcome
508 /// meaning "session is fresh enough, no-op".
509 #[serde(default)]
510 pub activated: bool,
511}
512
513/// Extended `GET /health` response body (v1.0.2 additive).
514///
515/// Prior to v1.0.2 the endpoint returned a bare 200 with no body.
516/// Consumers that ignore the body get identical behavior; consumers
517/// that parse the JSON gain liveness observability.
518#[derive(Clone, Debug, Default, Serialize, Deserialize)]
519#[serde(rename_all = "camelCase")]
520pub struct HealthResponse {
521 /// Runner alive.
522 pub ok: bool,
523 /// Runner semver (matches the smix-cli that shipped it).
524 #[serde(default)]
525 pub runner_version: String,
526 /// Runner uptime in milliseconds.
527 #[serde(default)]
528 pub uptime_ms: u64,
529 /// Epoch millis of the runner's most recent processed request
530 /// (any route). 0 if the runner has served no requests yet.
531 #[serde(default)]
532 pub last_request_at_ms: u64,
533 /// Currently-open session count.
534 #[serde(default)]
535 pub sessions_open: u32,
536 /// Total `.activate()` calls issued since runner boot.
537 #[serde(default)]
538 pub activations_total: u64,
539 /// v1.0.4 — SimRenderServer pid + alive flag observed by the
540 /// runner's sim-health sensor. `alive = false` after
541 /// `com.apple.display.captureservice` internal assertion trips.
542 #[serde(default)]
543 pub sim_render_server: HealthProcessInfo,
544 /// v1.0.4 — xcodebuild test-host pid + alive flag + total restart
545 /// count (S7 auto-restart on `** TEST INTERRUPTED **`).
546 #[serde(default)]
547 pub xcodebuild_test_host: HealthTestHostInfo,
548}
549
550/// v1.0.4 — pid + alive flag for a watched process. Additive to
551/// [`HealthResponse`].
552#[derive(Clone, Debug, Default, Serialize, Deserialize)]
553#[serde(rename_all = "camelCase")]
554pub struct HealthProcessInfo {
555 /// True when the runner last observed the process alive.
556 #[serde(default)]
557 pub alive: bool,
558 /// Last-known pid (0 if never observed).
559 #[serde(default)]
560 pub pid: u32,
561}
562
563/// v1.0.4 — xcodebuild test-host health with restart accounting.
564#[derive(Clone, Debug, Default, Serialize, Deserialize)]
565#[serde(rename_all = "camelCase")]
566pub struct HealthTestHostInfo {
567 /// True when the runner-side supervisor last saw xcodebuild alive.
568 #[serde(default)]
569 pub alive: bool,
570 /// Last-known pid (0 if unrecorded).
571 #[serde(default)]
572 pub pid: u32,
573 /// Number of times the supervisor has restarted the test-host
574 /// (RFC 1.0.4 §D6).
575 #[serde(default)]
576 pub restart_count: u32,
577}
578
579// ---- v1.0.4 D5 / D6 / D7 / D14 additive wire ----------------------------
580
581/// `POST /session/close-all` — v1.0.4 §D5 support for `smix runner
582/// cycle`. Runner-side clears every open session and returns the
583/// count that was cleared.
584#[derive(Clone, Debug, Default, Serialize, Deserialize)]
585#[serde(rename_all = "camelCase")]
586pub struct SessionCloseAllResponse {
587 /// True on success (idempotent — closing an empty session table
588 /// is not an error).
589 pub ok: bool,
590 /// Number of sessions closed.
591 #[serde(default)]
592 pub closed: u32,
593}
594
595/// `POST /session/relaunch-app` request body (v1.0.4 §D14).
596///
597/// Instructs the runner to `terminate()` + `launch()` the session's
598/// cached `XCUIApplication` binding IN PLACE — same test-host process,
599/// same session id, same XCUITest binding. Used to recover from a
600/// downstream app crash without cycling the entire runner.
601#[derive(Clone, Debug, Serialize, Deserialize)]
602#[serde(rename_all = "camelCase")]
603pub struct SessionRelaunchAppRequest {
604 /// Session whose cached binding will be relaunched.
605 pub session_id: String,
606}
607
608/// `POST /session/relaunch-app` response body.
609#[derive(Clone, Debug, Default, Serialize, Deserialize)]
610#[serde(rename_all = "camelCase")]
611pub struct SessionRelaunchAppResponse {
612 /// True on success (session known + relaunch cycle completed).
613 pub ok: bool,
614 /// Wall-clock milliseconds the terminate+launch cycle took.
615 #[serde(default)]
616 pub wall_ms: u64,
617}
618
619/// v1.0.8 §D1 — request body shared by `POST /session/terminate-app`
620/// and `POST /session/launch-app`. Both endpoints take just the
621/// session id.
622#[derive(Clone, Debug, Serialize, Deserialize)]
623#[serde(rename_all = "camelCase")]
624pub struct SessionAppLifecycleRequest {
625 /// Session whose cached `XCUIApplication` binding will be acted on.
626 pub session_id: String,
627}
628
629/// v1.0.8 §D1 — response for `POST /session/terminate-app` and
630/// `POST /session/launch-app`. Runner reports wall time for
631/// observability; the whole point of splitting terminate + launch
632/// from `/session/relaunch-app` is to let the SDK insert a
633/// host-side `SimctlClient::clear_app_sandbox` call between them,
634/// eliminating the "Insight quit unexpectedly" ReportCrash dialog
635/// that even v1.0.4 §D12's in-place `simctl` wipe still tripped.
636#[derive(Clone, Debug, Default, Serialize, Deserialize)]
637#[serde(rename_all = "camelCase")]
638pub struct SessionAppLifecycleResponse {
639 /// True on success.
640 pub ok: bool,
641 /// Wall-clock milliseconds the terminate or launch took.
642 #[serde(default)]
643 pub wall_ms: u64,
644}
645
646/// v1.0.5 §D1 — one entry in `POST /session/list` response.
647#[derive(Clone, Debug, Serialize, Deserialize)]
648#[serde(rename_all = "camelCase")]
649pub struct SessionSummary {
650 /// Session id.
651 pub session_id: String,
652 /// Bundle id the session's XCUIApplication is bound to.
653 pub bundle_id: String,
654 /// Epoch millis of open time.
655 #[serde(default)]
656 pub opened_at_ms: u64,
657 /// Epoch millis of last `.activate()` on this session (renew or
658 /// open). Distinct from the runner-internal `lastAccessedAt` used
659 /// by the idle-close sweep.
660 #[serde(default)]
661 pub last_activated_at_ms: u64,
662}
663
664/// `POST /session/list` response body (v1.0.5 §D1).
665#[derive(Clone, Debug, Default, Serialize, Deserialize)]
666#[serde(rename_all = "camelCase")]
667pub struct SessionListResponse {
668 /// Every session currently known to the runner.
669 #[serde(default)]
670 pub sessions: Vec<SessionSummary>,
671}
672
673/// v1.0.7 §D3 — one entry in the subprocess ring buffer.
674#[derive(Clone, Debug, Serialize, Deserialize)]
675#[serde(rename_all = "camelCase")]
676pub struct SubprocessRecord {
677 /// argv passed to the invoked binary.
678 pub argv: Vec<String>,
679 /// Exit code; `None` when the process failed to spawn.
680 #[serde(default)]
681 pub exit_code: Option<i32>,
682 /// Wall-clock milliseconds.
683 #[serde(default)]
684 pub wall_ms: u64,
685 /// First 256 bytes of stderr.
686 #[serde(default)]
687 pub stderr_head: String,
688 /// Epoch millis when the invocation completed.
689 #[serde(default)]
690 pub timestamp_ms: u64,
691}
692
693/// `POST /diagnostic/dump` response body (v1.0.7 §D5).
694///
695/// Snapshot of the runner's runtime state: recent subprocess
696/// invocations, currently-open sessions, sim health state, supervisor
697/// pid. Consumers dump this after a failed flow to get post-mortem
698/// visibility without needing a new patch for each failure mode.
699#[derive(Clone, Debug, Default, Serialize, Deserialize)]
700#[serde(rename_all = "camelCase")]
701pub struct DiagnosticDumpResponse {
702 /// Recent `xcrun simctl` invocations recorded by the runner's
703 /// subprocess ring buffer. Ordered oldest → newest, capped at 128.
704 #[serde(default)]
705 pub recent_subprocesses: Vec<SubprocessRecord>,
706 /// Every session currently known to the runner (mirrors
707 /// `/session/list`; embedded here for one-shot dump).
708 #[serde(default)]
709 pub sessions: Vec<SessionSummary>,
710 /// Coarse sim-health classification at dump time.
711 #[serde(default)]
712 pub sim_health: String,
713 /// Pid of the supervisor sidecar, when spawned via
714 /// `smix runner up --supervise` (v1.0.6 §D1).
715 #[serde(default)]
716 pub supervisor_pid: Option<u32>,
717 /// Runner wall-clock uptime in milliseconds.
718 #[serde(default)]
719 pub uptime_ms: u64,
720}
721
722/// v1.0.4 §D7 — Session state exposed to SDK consumers via the
723/// `X-Sim-Health` response header on every runner response.
724///
725/// Additive to v1.0.3 sessions — consumers that ignore the header get
726/// v1.0.3 behavior; consumers that read it get `Degraded` / `Dead` /
727/// `Cycling` transitions without polling.
728#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
729#[non_exhaustive]
730pub enum SimHealthWireState {
731 /// All watched signals inside envelope.
732 #[serde(rename = "healthy")]
733 Healthy,
734 /// At least one signal degraded (screenshot p95 slow, /health
735 /// stale, etc.).
736 #[serde(rename = "degraded")]
737 Degraded,
738 /// Runner is mid-cycle (supervisor auto-restart in progress).
739 /// Callers should back off until the next `Healthy` transition.
740 #[serde(rename = "cycling")]
741 Cycling,
742 /// Runner or a watched subprocess (SimRenderServer / xcodebuild)
743 /// is gone. Callers should bail.
744 #[serde(rename = "dead")]
745 Dead,
746}
747
748impl SimHealthWireState {
749 /// Parse a case-insensitive wire string; returns `None` on
750 /// unknown values so unrecognized future states don't panic.
751 pub fn from_header(value: &str) -> Option<Self> {
752 match value.trim().to_ascii_lowercase().as_str() {
753 "healthy" => Some(Self::Healthy),
754 "degraded" => Some(Self::Degraded),
755 "cycling" => Some(Self::Cycling),
756 "dead" => Some(Self::Dead),
757 _ => None,
758 }
759 }
760
761 /// Header string emitted on the runner side.
762 pub fn as_header(&self) -> &'static str {
763 match self {
764 Self::Healthy => "healthy",
765 Self::Degraded => "degraded",
766 Self::Cycling => "cycling",
767 Self::Dead => "dead",
768 }
769 }
770}