smix-cli 2.1.0

smix — AI-native iOS Simulator automation CLI.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
//! `smix tap` / `smix find` / `smix wait-for` CLI subcommands.
//!
//! Shell-out act/sense surface on top of a running runner (see
//! `smix capsule up` / `smix runner up`). The CLI plumbs through to
//! `smix-runner-client` via HTTP at `localhost:<port>`. Port defaults to
//! 22087 (single-sim) and reads `SMIX_RUNNER_PORT` env when set
//! (used to bind multiple concurrent runners to distinct ports).
//!
//! Selector shorthand (parsed once at CLI parse-time):
//!   - `id:btn-take-photo` → Selector::Id { id: "btn-take-photo", ... }
//!   - `text:Welcome to smix` → Selector::Text { text: Pattern::Text(..), ... }
//!   - `label:Settings` → Selector::Label { label: "Settings", ... }
//!   - `role:button` → Selector::Role { role: Role::Button, ... }
//!
//! Examples:
//!   $ smix capsule up ios-17 --soft --no-capture
//!   $ smix find 'id:home-tab'
//!   exists=true
//!   $ smix tap 'id:home-tab'
//!   tapped id=home-tab
//!   $ smix wait-for 'id:home-counter-label' --timeout 5
//!   visible id=home-counter-label (waited 12ms)

use smix_driver::SimctlDriver;
use smix_input::{KeyName, SwipeDirection};
use smix_runner_client::HttpRunnerClient;
use smix_screen::role_from_raw_type;
use smix_selector::{Modifiers, Pattern, Selector};
use std::time::Duration;

/// The port the runner binds when nobody says otherwise.
///
/// The bottom rung of the ladder, and the only place it is spelled:
/// `run_port` reads it from here so the two paths cannot drift.
pub const DEFAULT_RUNNER_PORT: u16 = 22087;

/// Read SMIX_RUNNER_PORT env, or nothing.
///
/// Deliberately not `-> u16`. It used to be, substituting 22087 for an
/// unset variable, and that answer arrived before the registry was ever
/// asked: the documented ladder is flag → env → registry → default, and
/// a function that applies the default in the middle of it removes the
/// third rung. In a workspace with a sim registered on 22088 the
/// single-shot verbs dialled 22087 while `smix run` dialled 22088. The
/// default now lives in one place, at the bottom of the ladder.
pub fn runner_port_from_env_opt() -> Option<u16> {
    std::env::var("SMIX_RUNNER_PORT")
        .ok()
        .and_then(|s| s.parse::<u16>().ok())
}

/// Parse `<kind>:<value>` selector shorthand. Returns None on unknown kind
/// / missing colon so the CLI can surface a clear "selector parse error".
pub fn parse_selector(s: &str) -> Option<Selector> {
    let (kind, value) = s.split_once(':')?;
    let modifiers = Modifiers::default();
    match kind {
        "id" => Some(Selector::Id {
            id: value.to_string(),
            modifiers,
        }),
        "text" => Some(Selector::Text {
            text: Pattern::text(value),
            modifiers,
        }),
        "label" => Some(Selector::Label {
            label: value.to_string(),
            modifiers,
        }),
        "role" => {
            let role = role_from_raw_type(value)?;
            Some(Selector::Role {
                role,
                name: None,
                modifiers,
            })
        }
        _ => None,
    }
}

#[derive(Debug, thiserror::Error)]
pub enum ActError {
    #[error("invalid selector `{0}` — expected one of `id:` / `text:` / `label:` / `role:`")]
    BadSelector(String),
    #[error("runner transport: {0}")]
    Transport(String),
    #[error("wait_for timeout after {timeout_ms}ms: {selector}")]
    Timeout { selector: String, timeout_ms: u64 },
}

fn driver(port: u16) -> SimctlDriver {
    SimctlDriver::new(HttpRunnerClient::new(port))
}

/// Parse a KeyName shorthand mirroring the wire camelCase form
/// `smix_input::KeyName::as_str` produces. Accepts a couple of common
/// shell-friendly aliases (`enter` → return, `backspace` → delete).
pub fn parse_key_name(s: &str) -> Option<KeyName> {
    match s {
        "return" | "enter" => Some(KeyName::Return),
        "delete" | "backspace" => Some(KeyName::Delete),
        "tab" => Some(KeyName::Tab),
        "space" => Some(KeyName::Space),
        "escape" | "esc" => Some(KeyName::Escape),
        "arrowUp" | "up" => Some(KeyName::ArrowUp),
        "arrowDown" | "down" => Some(KeyName::ArrowDown),
        "arrowLeft" | "left" => Some(KeyName::ArrowLeft),
        "arrowRight" | "right" => Some(KeyName::ArrowRight),
        "home" => Some(KeyName::Home),
        "lock" => Some(KeyName::Lock),
        "volumeUp" | "volume-up" => Some(KeyName::VolumeUp),
        "volumeDown" | "volume-down" => Some(KeyName::VolumeDown),
        _ => None,
    }
}

/// Parse swipe / scroll direction.
pub fn parse_direction(s: &str) -> Option<SwipeDirection> {
    match s {
        "up" => Some(SwipeDirection::Up),
        "down" => Some(SwipeDirection::Down),
        "left" => Some(SwipeDirection::Left),
        "right" => Some(SwipeDirection::Right),
        _ => None,
    }
}

/// `smix tap <selector>` — host-resolve + tap_at_norm_coord on the running
/// runner. Routes through `SimctlDriver::tap` so id/label/role selectors
/// resolve via the /tree path (swift /tap only supports text selectors).
pub async fn cmd_tap(selector_str: String, port: u16) -> Result<(), ActError> {
    let selector =
        parse_selector(&selector_str).ok_or_else(|| ActError::BadSelector(selector_str.clone()))?;
    let d = driver(port);
    let outcome = d
        .tap(&selector, None)
        .await
        .map_err(|e| ActError::Transport(format!("{e}")))?;
    // Say what the touch landed on, not just that one was sent.
    //
    // A consumer hit "the step is green and the app did nothing" three
    // times in one effort, and all three times the touch HAD arrived —
    // the fault was downstream, in a counter, a no-op navigate, and an
    // inter-tap window. Each time the green step was read as "smix did
    // not deliver it" and sent them upstream first, ~13 rounds in
    // total. A pass that shows its evidence points the other way.
    println!("tapped {selector_str}");
    if !outcome.observed.is_empty() {
        let inside: Vec<String> = outcome
            .observed
            .iter()
            .map(|e| {
                if !e.identifier.is_empty() {
                    e.identifier.clone()
                } else if !e.label.is_empty() {
                    format!("{:?}", e.label)
                } else {
                    "<unnamed>".to_string()
                }
            })
            .collect();
        println!("  landed inside: {}", inside.join(" < "));
    }
    if let smix_driver::ActVerdict::Unconfirmable(why) = &outcome.verdict {
        println!("  not verified: {why}");
    }
    Ok(())
}

/// `smix find <selector>` — boolean existence probe. Same routing path as
/// `smix tap`: text → swift /find shortcut, anything else → /tree resolve.
pub async fn cmd_find(selector_str: String, port: u16) -> Result<(), ActError> {
    let selector =
        parse_selector(&selector_str).ok_or_else(|| ActError::BadSelector(selector_str.clone()))?;
    let d = driver(port);
    let exists = d
        .find(&selector, None)
        .await
        .map_err(|e| ActError::Transport(format!("{e}")))?;
    println!("exists={exists}");
    Ok(())
}

/// `smix fill <selector> --text <text>` — type `text` into the matched field.
/// Mirrors maestro `inputText:`.
pub async fn cmd_fill(selector_str: String, text: String, port: u16) -> Result<(), ActError> {
    let selector =
        parse_selector(&selector_str).ok_or_else(|| ActError::BadSelector(selector_str.clone()))?;
    let d = driver(port);
    d.fill(&selector, &text, None)
        .await
        .map_err(|e| ActError::Transport(format!("{e}")))?;
    println!("filled {selector_str} with `{text}`");
    Ok(())
}

/// `smix press-key <key-name>` — issue a hardware / IME key press. Key
/// shorthand: `return` (alias `enter`), `delete` (alias `backspace`),
/// `tab`, `space`, `escape` / `esc`, `arrowUp` / `up`, `arrowDown` /
/// `down`, `arrowLeft` / `left`, `arrowRight` / `right`, `home`, `lock`,
/// `volumeUp` / `volume-up`, `volumeDown` / `volume-down`.
pub async fn cmd_press_key(key_str: String, port: u16) -> Result<(), ActError> {
    let key =
        parse_key_name(&key_str).ok_or_else(|| ActError::BadSelector(format!("key:{key_str}")))?;
    let d = driver(port);
    d.press_key(key)
        .await
        .map_err(|e| ActError::Transport(format!("{e}")))?;
    println!("pressed key:{key_str}");
    Ok(())
}

/// `smix scroll <selector> --direction <up|down|left|right>` — scroll
/// until selector becomes visible.
pub async fn cmd_scroll(
    selector_str: String,
    direction_str: String,
    port: u16,
) -> Result<(), ActError> {
    let selector =
        parse_selector(&selector_str).ok_or_else(|| ActError::BadSelector(selector_str.clone()))?;
    let direction = parse_direction(&direction_str)
        .ok_or_else(|| ActError::BadSelector(format!("direction:{direction_str}")))?;
    let d = driver(port);
    d.scroll(&selector, direction)
        .await
        .map_err(|e| ActError::Transport(format!("{e}")))?;
    println!("scrolled {direction_str} to {selector_str}");
    Ok(())
}

/// `smix tree [--json]` — print the runner's current accessibility tree.
/// `--json` emits the wire-format JSON (large — typically 100KB+ for a
/// typical app screen); default emits an indented text outline keyed by
/// id + label per node.
pub async fn cmd_tree(json: bool, port: u16) -> Result<(), ActError> {
    let d = driver(port);
    let tree = d
        .tree(None)
        .await
        .map_err(|e| ActError::Transport(format!("{e}")))?;
    if json {
        let s = serde_json::to_string_pretty(&tree)
            .map_err(|e| ActError::Transport(format!("serde: {e}")))?;
        println!("{s}");
    } else {
        print_tree_outline(&tree, 0);
    }
    Ok(())
}

/// Helper for authoring subcommand to fetch the a11y
/// tree as raw JSON (bypasses print_tree_outline).
pub async fn fetch_tree_json(port: u16) -> Result<serde_json::Value, ActError> {
    let d = driver(port);
    let tree = d
        .tree(None)
        .await
        .map_err(|e| ActError::Transport(format!("{e}")))?;
    serde_json::to_value(&tree).map_err(|e| ActError::Transport(format!("serialize tree: {e}")))
}

fn print_tree_outline(node: &smix_screen::A11yNode, depth: usize) {
    let indent = "  ".repeat(depth);
    let id = node.identifier.as_deref().unwrap_or("");
    let label = node.label.as_deref().unwrap_or("");
    let visible = if node.visible { "" } else { "·" };
    println!("{indent}{visible} id={id:?} label={label:?}");
    for child in &node.children {
        print_tree_outline(child, depth + 1);
    }
}

/// `smix describe [--json]` — print the runner's ScreenDescription: the
/// nameable visible elements, the bundle id the description was taken
/// from, and the capture timestamp. `--json` emits the wire JSON;
/// default emits a pretty-printed Debug summary.
///
/// It used to promise a title and a status bar. Neither exists anywhere
/// in the tree, and two of the three metadata fields were empty on top
/// of that — the help described a richer thing than the code produced.
pub async fn cmd_describe(json: bool, port: u16) -> Result<(), ActError> {
    let d = driver(port);
    let desc = d
        .describe()
        .await
        .map_err(|e| ActError::Transport(format!("{e}")))?;
    if json {
        let s = serde_json::to_string_pretty(&desc)
            .map_err(|e| ActError::Transport(format!("serde: {e}")))?;
        println!("{s}");
    } else {
        println!("{desc:#?}");
    }
    Ok(())
}

/// `smix system-popups [--json]` — print the runner's current SpringBoard
/// system-popup list (camera permission alerts, "Open in `<App>`?", etc.).
/// `--json` emits the wire JSON; default emits a pretty-printed Debug
/// summary keyed by popup id + buttons.
pub async fn cmd_system_popups(json: bool, port: u16) -> Result<(), ActError> {
    let d = driver(port);
    let popups = d
        .system_popups(None)
        .await
        .map_err(|e| ActError::Transport(format!("{e}")))?;
    if json {
        let s = serde_json::to_string_pretty(&popups)
            .map_err(|e| ActError::Transport(format!("serde: {e}")))?;
        println!("{s}");
    } else {
        if popups.is_empty() {
            println!("(no system popups in scope)");
        } else {
            println!("{popups:#?}");
        }
    }
    Ok(())
}

/// `smix system-popup-action` — press a named button on a SpringBoard
/// popup. Both ids come from `smix system-popups` output. Exit is an
/// error when the runner reports no such popup/button (404), so shell
/// callers can branch on it.
pub async fn cmd_system_popup_action(
    popup_id: &str,
    button_id: &str,
    port: u16,
) -> Result<(), ActError> {
    let d = driver(port);
    let pressed = d
        .system_popup_action(popup_id, button_id)
        .await
        .map_err(|e| ActError::Transport(format!("{e}")))?;
    if !pressed {
        return Err(ActError::Transport(format!(
            "no popup {popup_id:?} with button {button_id:?} — list current \
             popups via `smix system-popups`"
        )));
    }
    println!("pressed: {button_id} on {popup_id}");
    Ok(())
}

/// `smix hide-keyboard` — dismiss the soft keyboard if visible.
pub async fn cmd_hide_keyboard(port: u16) -> Result<(), ActError> {
    let d = driver(port);
    d.hide_keyboard()
        .await
        .map_err(|e| ActError::Transport(format!("{e}")))?;
    println!("keyboard hidden");
    Ok(())
}

/// `smix wait-for <selector> --timeout <secs>` — re-uses `SimctlDriver::
/// wait_for` (same polling + transient-transport-retry semantics the SDK
/// path uses). Returns visible-elements snapshot on timeout.
pub async fn cmd_wait_for(
    selector_str: String,
    timeout_secs: u64,
    port: u16,
) -> Result<(), ActError> {
    let selector =
        parse_selector(&selector_str).ok_or_else(|| ActError::BadSelector(selector_str.clone()))?;
    let d = driver(port);
    let timeout = Duration::from_secs(timeout_secs);
    match d.wait_for(&selector, timeout, None).await {
        Ok(_) => {
            println!("visible {selector_str}");
            Ok(())
        }
        Err(_) => Err(ActError::Timeout {
            selector: selector_str,
            timeout_ms: timeout.as_millis() as u64,
        }),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Mutex;

    /// Serialize env-touching tests. SMIX_RUNNER_PORT is a
    /// process-global, so the two `runner_port_from_env_*` tests must
    /// not race when cargo runs the test binary multi-threaded (default).
    static ENV_LOCK: Mutex<()> = Mutex::new(());

    #[test]
    fn parse_selector_id() {
        let s = parse_selector("id:btn-take-photo").expect("parse id");
        assert!(matches!(s, Selector::Id { id, .. } if id == "btn-take-photo"));
    }

    #[test]
    fn parse_selector_text_plain() {
        let s = parse_selector("text:Welcome to smix").expect("parse text");
        match s {
            Selector::Text { text, .. } => {
                assert!(matches!(text, Pattern::Text(t) if t == "Welcome to smix"));
            }
            _ => panic!("expected Selector::Text"),
        }
    }

    #[test]
    fn parse_selector_label() {
        let s = parse_selector("label:Settings").expect("parse label");
        assert!(matches!(s, Selector::Label { label, .. } if label == "Settings"));
    }

    #[test]
    fn parse_selector_role_button() {
        let s = parse_selector("role:button").expect("parse role");
        assert!(matches!(
            s,
            Selector::Role {
                role: smix_screen::Role::Button,
                ..
            }
        ));
    }

    #[test]
    fn parse_selector_unknown_kind_returns_none() {
        assert!(parse_selector("xpath://*[1]").is_none());
        assert!(parse_selector("nope").is_none()); // no colon
    }

    /// An unset variable is `None`, not the default.
    ///
    /// The distinction is the whole point: `None` lets the registry
    /// answer next, and 22087 would not.
    #[test]
    fn runner_port_from_env_is_none_when_unset() {
        let _g = ENV_LOCK.lock().unwrap();
        // SAFETY: ENV_LOCK serializes env churn across the 2 tests in this
        // module that touch SMIX_RUNNER_PORT.
        unsafe { std::env::remove_var("SMIX_RUNNER_PORT") };
        assert_eq!(runner_port_from_env_opt(), None);
    }

    #[test]
    fn runner_port_from_env_reads_override() {
        let _g = ENV_LOCK.lock().unwrap();
        // SAFETY: as above.
        unsafe { std::env::set_var("SMIX_RUNNER_PORT", "22099") };
        assert_eq!(runner_port_from_env_opt(), Some(22099));
        unsafe { std::env::remove_var("SMIX_RUNNER_PORT") };
    }

    #[test]
    fn parse_key_name_canonical_and_aliases() {
        assert_eq!(parse_key_name("return"), Some(KeyName::Return));
        assert_eq!(parse_key_name("enter"), Some(KeyName::Return));
        assert_eq!(parse_key_name("delete"), Some(KeyName::Delete));
        assert_eq!(parse_key_name("backspace"), Some(KeyName::Delete));
        assert_eq!(parse_key_name("arrowUp"), Some(KeyName::ArrowUp));
        assert_eq!(parse_key_name("up"), Some(KeyName::ArrowUp));
        assert_eq!(parse_key_name("escape"), Some(KeyName::Escape));
        assert_eq!(parse_key_name("esc"), Some(KeyName::Escape));
        assert_eq!(parse_key_name("volumeUp"), Some(KeyName::VolumeUp));
        assert_eq!(parse_key_name("volume-up"), Some(KeyName::VolumeUp));
        assert_eq!(parse_key_name("nope"), None);
    }

    #[test]
    fn parse_direction_four_compass_dirs() {
        assert_eq!(parse_direction("up"), Some(SwipeDirection::Up));
        assert_eq!(parse_direction("down"), Some(SwipeDirection::Down));
        assert_eq!(parse_direction("left"), Some(SwipeDirection::Left));
        assert_eq!(parse_direction("right"), Some(SwipeDirection::Right));
        assert_eq!(parse_direction("nope"), None);
        assert_eq!(parse_direction("UP"), None); // case-sensitive
    }
}