smix-runner-client 1.0.24

smix-runner-client — HTTP IPC client to swift-bridge/SmixRunnerCore.
Documentation
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
//! v3.1 c8 — wiremock-based wire-level integration tests for HttpRunnerClient.
//!
//! Verifies URL shape + query params + request body + response parsing
//! 1:1 with the TS runner-client. Not real-sim — real-sim binding lives
//! in c-final capstone alongside swift-bridge build verification.

use smix_input::{KeyName, SwipeDirection};
use smix_runner_client::{HttpRunnerClient, IncludeScope, RunnerScrollSelector, TapMode};
use smix_screen::{A11yNode, Rect};
use smix_selector::{Modifiers, Pattern, Selector};
use wiremock::matchers::{body_json, method, path, query_param};
use wiremock::{Mock, MockServer, ResponseTemplate};

fn text_sel(t: &str) -> Selector {
    Selector::Text {
        text: Pattern::text(t),
        modifiers: Modifiers::default(),
    }
}

fn minimal_tree() -> A11yNode {
    A11yNode {
        raw_type: "application".into(),
        element_type_raw: 1,
        role: None,
        identifier: None,
        label: None,
        title: None,
        placeholder_value: None,
        value: None,
        text: None,
        bounds: Rect {
            x: 0.0,
            y: 0.0,
            w: 390.0,
            h: 844.0,
        },
        enabled: true,
        selected: false,
        has_focus: false,
        visible: true,
        children: vec![],
    }
}

// ---- health / ensure_reachable -----------------------------------------

#[tokio::test]
async fn health_returns_true_on_200() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/health"))
        .respond_with(ResponseTemplate::new(200))
        .mount(&server)
        .await;
    let client = HttpRunnerClient::with_base(server.uri());
    assert!(client.health().await);
}

#[tokio::test]
async fn ensure_reachable_memoizes_after_first_success() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/health"))
        .respond_with(ResponseTemplate::new(200))
        .expect(1) // only ONE probe — memoized after success.
        .mount(&server)
        .await;
    let client = HttpRunnerClient::with_base(server.uri());
    client.ensure_reachable().await.expect("first probe");
    client.ensure_reachable().await.expect("memoized no-op");
    client.ensure_reachable().await.expect("memoized no-op");
    // wiremock verifies .expect(1) on drop — implicit assertion.
}

#[tokio::test]
async fn ensure_reachable_fails_when_health_500() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/health"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&server)
        .await;
    let client = HttpRunnerClient::with_base(server.uri());
    let err = client.ensure_reachable().await.unwrap_err();
    let msg = format!("{err:?}");
    assert!(msg.contains("Unreachable"), "got: {msg}");
}

// ---- get_tree -----------------------------------------------------------

#[tokio::test]
async fn get_tree_no_include_no_query_param() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/tree"))
        .respond_with(ResponseTemplate::new(200).set_body_json(minimal_tree()))
        .mount(&server)
        .await;
    let client = HttpRunnerClient::with_base(server.uri());
    let tree = client.get_tree(None).await.expect("tree");
    assert_eq!(tree.bounds.w, 390.0);
}

#[tokio::test]
async fn get_tree_with_include_threads_query_param() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/tree"))
        .and(query_param("include", "all-windows"))
        .respond_with(ResponseTemplate::new(200).set_body_json(minimal_tree()))
        .mount(&server)
        .await;
    let client = HttpRunnerClient::with_base(server.uri());
    let _ = client
        .get_tree(Some(IncludeScope::AllWindows))
        .await
        .expect("tree with scope");
}

// ---- find ---------------------------------------------------------------

#[tokio::test]
async fn find_exists_true_serializes_selector_text() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/find"))
        .and(body_json(serde_json::json!({
            "selector": {"text": "Login"}
        })))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "exists": true
        })))
        .mount(&server)
        .await;
    let client = HttpRunnerClient::with_base(server.uri());
    assert!(client.find(&text_sel("Login"), None).await.unwrap());
}

// ---- tap_at_norm_coord --------------------------------------------------

#[tokio::test]
async fn tap_at_norm_coord_posts_nx_ny() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/tap-at-norm-coord"))
        .and(body_json(serde_json::json!({"nx": 0.5, "ny": 0.25})))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "ok": true
        })))
        .mount(&server)
        .await;
    let client = HttpRunnerClient::with_base(server.uri());
    client.tap_at_norm_coord(0.5, 0.25).await.unwrap();
}

// ---- tap (selector + mode) ---------------------------------------------

#[tokio::test]
async fn tap_posts_selector_and_mode_resolve_camel_case() {
    let server = MockServer::start().await;
    // mode serializes as camelCase "resolve" / "resolveAndTap".
    Mock::given(method("POST"))
        .and(path("/tap"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "stages": null, "frame": null, "appFrame": null
        })))
        .mount(&server)
        .await;
    let client = HttpRunnerClient::with_base(server.uri());
    let _ = client
        .tap(&text_sel("OK"), TapMode::Resolve, None)
        .await
        .expect("tap ok");
}

// ---- press_key ----------------------------------------------------------

#[tokio::test]
async fn press_key_serializes_camel_case_name() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/press-key"))
        .and(body_json(serde_json::json!({"key": "arrowUp"})))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "tree": null, "stages": null
        })))
        .mount(&server)
        .await;
    let client = HttpRunnerClient::with_base(server.uri());
    let _ = client.press_key(KeyName::ArrowUp).await.expect("press_key");
}

// ---- swipe_once ---------------------------------------------------------

#[tokio::test]
async fn swipe_once_posts_direction_camel_case() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/swipe-once"))
        .and(body_json(serde_json::json!({"direction": "down"})))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "ok": true
        })))
        .mount(&server)
        .await;
    let client = HttpRunnerClient::with_base(server.uri());
    client.swipe_once(SwipeDirection::Down).await.unwrap();
}

// ---- scroll ------------------------------------------------------------

#[tokio::test]
async fn scroll_matched_returns_swipe_count() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/scroll"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "matched": true,
            "swipes": 3
        })))
        .mount(&server)
        .await;
    let client = HttpRunnerClient::with_base(server.uri());
    let s = RunnerScrollSelector::Text {
        text: "Log out".into(),
    };
    let swipes = client
        .scroll(&s, SwipeDirection::Down, None)
        .await
        .expect("matched");
    assert_eq!(swipes, 3);
}

#[tokio::test]
async fn scroll_not_matched_returns_malformed_body_with_swipe_count_detail() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/scroll"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "matched": false,
            "swipes": 30
        })))
        .mount(&server)
        .await;
    let client = HttpRunnerClient::with_base(server.uri());
    let s = RunnerScrollSelector::Text {
        text: "Hidden".into(),
    };
    let err = client
        .scroll(&s, SwipeDirection::Down, None)
        .await
        .unwrap_err();
    let msg = format!("{err}");
    assert!(msg.contains("30 swipes"), "got: {msg}");
}

// ---- system_popups envelope --------------------------------------------

#[tokio::test]
async fn system_popups_unwraps_envelope() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/system-popups"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "popups": [
                {
                    "id": "p1",
                    "type": "alert",
                    "source": "com.apple.springboard",
                    "title": "Allow notifications?",
                    "body": "",
                    "buttons": []
                }
            ]
        })))
        .mount(&server)
        .await;
    let client = HttpRunnerClient::with_base(server.uri());
    let popups = client.system_popups(None).await.expect("popups");
    assert_eq!(popups.len(), 1);
    assert_eq!(popups[0].id, "p1");
}

// ---- record cycle -------------------------------------------------------

#[tokio::test]
async fn record_start_stop_polls_drain_events() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/record/start"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "ok": true
        })))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/record/poll"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "events": []
        })))
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(path("/record/stop"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "events": [
                {"rawCode": 1021, "timestampMs": 100.0}
            ]
        })))
        .mount(&server)
        .await;
    let client = HttpRunnerClient::with_base(server.uri());
    client.start_record().await.unwrap();
    let polled = client.poll_record().await.unwrap();
    assert!(polled.is_empty());
    let final_events = client.stop_record().await.unwrap();
    assert_eq!(final_events.len(), 1);
    // v5.1 c3 S2 — 字段名校正 `code` → `raw_code`(serde camelCase → `rawCode`)
    // 对齐 swift `EventRecorder` 真实 emit 的 schema。
    assert_eq!(final_events[0].raw_code, 1021);
}

// ---- error path: non-2xx ----------------------------------------------

#[tokio::test]
async fn non_2xx_returns_non_success_status_error() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/find"))
        .respond_with(ResponseTemplate::new(503).set_body_string("upstream down"))
        .mount(&server)
        .await;
    let client = HttpRunnerClient::with_base(server.uri());
    let err = client.find(&text_sel("X"), None).await.unwrap_err();
    let msg = format!("{err:?}");
    assert!(msg.contains("503"), "got: {msg}");
}

// -------------------- v1.0.3 session lifecycle -------------------------

use smix_runner_client::{SessionCloseRequest, SessionOpenRequest, SessionRenewActivationRequest};
use wiremock::matchers::header;

#[tokio::test]
async fn open_session_sends_bundle_id_and_returns_session_id() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/session/open"))
        .and(body_json(serde_json::json!({
            "bundleId": "com.example.app",
            "activate": true,
        })))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "sessionId": "sess-abc-123",
            "activatedOnce": true,
            "serverTimeMs": 1_720_500_000_000u64,
        })))
        .mount(&server)
        .await;
    let client = HttpRunnerClient::with_base(server.uri());
    let req = SessionOpenRequest {
        bundle_id: "com.example.app".into(),
        activate: true,
    };
    let resp = client.open_session(&req).await.expect("session open");
    assert_eq!(resp.session_id, "sess-abc-123");
    assert!(resp.activated_once);
    assert_eq!(resp.server_time_ms, 1_720_500_000_000u64);
}

#[tokio::test]
async fn client_with_session_id_sends_session_header_on_every_request() {
    let server = MockServer::start().await;
    // Any /find request MUST carry Session-Id: sess-xyz.
    Mock::given(method("POST"))
        .and(path("/find"))
        .and(header("session-id", "sess-xyz"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "exists": true,
        })))
        .mount(&server)
        .await;
    let mut client = HttpRunnerClient::with_base(server.uri());
    client.set_session_id("sess-xyz");
    let ok = client
        .find(&text_sel("X"), None)
        .await
        .expect("find with session header");
    assert!(ok);
}

#[tokio::test]
async fn client_clear_session_id_stops_sending_header() {
    let server = MockServer::start().await;
    // Request must NOT carry Session-Id after clear.
    Mock::given(method("POST"))
        .and(path("/find"))
        .and(header("app-bundle-id", "com.example.app"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "exists": false,
        })))
        .mount(&server)
        .await;
    let mut client =
        HttpRunnerClient::with_base(server.uri()).with_target_bundle_id("com.example.app");
    client.set_session_id("sess-xyz");
    client.clear_session_id();
    // If the mock rejects the request (session-id present when we don't
    // expect it), this errors. Passing means no session-id was sent.
    let _ = client.find(&text_sel("X"), None).await;
}

#[tokio::test]
async fn close_session_hits_close_route() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/session/close"))
        .and(body_json(serde_json::json!({ "sessionId": "sess-abc" })))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "ok": true,
        })))
        .mount(&server)
        .await;
    let client = HttpRunnerClient::with_base(server.uri());
    let resp = client
        .close_session(&SessionCloseRequest {
            session_id: "sess-abc".into(),
        })
        .await
        .expect("session close");
    assert!(resp.ok);
}

#[tokio::test]
async fn renew_session_activation_returns_activated_flag() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/session/renew-activation"))
        .and(body_json(serde_json::json!({ "sessionId": "sess-abc" })))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "ok": true,
            "activated": false,
        })))
        .mount(&server)
        .await;
    let client = HttpRunnerClient::with_base(server.uri());
    let resp = client
        .renew_session_activation(&SessionRenewActivationRequest {
            session_id: "sess-abc".into(),
        })
        .await
        .expect("renew activation");
    assert!(resp.ok);
    assert!(!resp.activated);
}

#[tokio::test]
async fn health_detail_parses_extended_body() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/health"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "ok": true,
            "runnerVersion": "1.0.3",
            "uptimeMs": 42_000u64,
            "lastRequestAtMs": 1_720_500_000_000u64,
            "sessionsOpen": 2u32,
            "activationsTotal": 5u64,
        })))
        .mount(&server)
        .await;
    let client = HttpRunnerClient::with_base(server.uri());
    let resp = client.health_detail().await.expect("health detail");
    assert!(resp.ok);
    assert_eq!(resp.runner_version, "1.0.3");
    assert_eq!(resp.uptime_ms, 42_000);
    assert_eq!(resp.sessions_open, 2);
    assert_eq!(resp.activations_total, 5);
}

#[tokio::test]
async fn health_detail_tolerates_legacy_empty_body() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/health"))
        .respond_with(ResponseTemplate::new(200).set_body_string(""))
        .mount(&server)
        .await;
    let client = HttpRunnerClient::with_base(server.uri());
    let resp = client
        .health_detail()
        .await
        .expect("legacy health empty body tolerated");
    assert!(resp.ok);
    assert_eq!(resp.runner_version, "");
}

// ---- v1.0.4 sim-health feed -------------------------------------------

#[tokio::test]
async fn sim_health_receives_health_ok_from_bare_probe() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/health"))
        .respond_with(ResponseTemplate::new(200))
        .mount(&server)
        .await;
    let monitor =
        smix_sim_health::SimHealthMonitor::new(smix_sim_health::SimHealthConfig::default());
    let client = HttpRunnerClient::with_base(server.uri()).with_sim_health(monitor.clone());
    // Force a Degraded starting point via a failed process observation
    // so we can detect the recovery signal fed by the /health call.
    monitor.record_process("SimRenderServer", false);
    assert_eq!(monitor.state(), smix_sim_health::SimHealthState::Dead);
    monitor.record_process("SimRenderServer", true);
    // record_process alone recovers, so bare /health OK just keeps us Healthy.
    assert_eq!(monitor.state(), smix_sim_health::SimHealthState::Healthy);
    assert!(client.health().await);
    assert_eq!(monitor.state(), smix_sim_health::SimHealthState::Healthy);
}

#[tokio::test]
async fn sim_health_receives_health_fail_from_detail_5xx() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/health"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&server)
        .await;
    let monitor =
        smix_sim_health::SimHealthMonitor::new(smix_sim_health::SimHealthConfig::default());
    let client = HttpRunnerClient::with_base(server.uri()).with_sim_health(monitor.clone());
    let _ = client.health_detail().await;
    // A single fail with health_stale not yet reached stays classified
    // as HealthNeverSeen (Degraded) — the important thing is the feed
    // reached the monitor without panicking and the sim_health accessor works.
    let m = client.sim_health().expect("sim_health should be set");
    let evt = m.subscribe();
    // Second /health call, still 500.
    let _ = client.health_detail().await;
    drop(evt);
    // Assertion: the monitor is not Healthy anymore after two failed probes with
    // no successful history — HealthNeverSeen keeps it out of Healthy.
    assert_ne!(monitor.state(), smix_sim_health::SimHealthState::Healthy);
}

#[tokio::test]
async fn sim_health_accessor_returns_none_by_default() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/health"))
        .respond_with(ResponseTemplate::new(200))
        .mount(&server)
        .await;
    let client = HttpRunnerClient::with_base(server.uri());
    assert!(client.sim_health().is_none());
    // Without a monitor, /health still works — no feed, no crash.
    assert!(client.health().await);
}