allwright-surface-mobile 0.0.59

Shared mobile surface abstractions for allwright plugins.
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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
use allwright_plugin_sdk::SurfaceFamily;
use allwright_plugin_sdk::SurfacePluginDescriptor;
use serde::{Deserialize, Serialize};
use tokio::time::{Duration, sleep};

pub const SURFACE_ID: &str = "mobile";

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MobileAutomationBackend {
    UiAutomator2,
    Espresso,
    WebViewBridge,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MobileAppKind {
    Native,
    Hybrid,
    BrowserWrapped,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RuntimeMaturity {
    Planned,
    Scaffolding,
    RuntimeReady,
    Installable,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MobileCapabilitySet {
    pub supports_native_views: bool,
    pub supports_webviews: bool,
    pub supports_deep_links: bool,
    pub supports_shell_commands: bool,
    pub supports_device_logs: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MobileSurfaceProfile {
    pub plugin_id: &'static str,
    pub display_name: &'static str,
    pub family: SurfaceFamily,
    pub backends: &'static [MobileAutomationBackend],
    pub default_backend: MobileAutomationBackend,
    pub supported_app_kinds: &'static [MobileAppKind],
    pub capabilities: MobileCapabilitySet,
    pub bootstrap_hint: &'static str,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MobileRuntimeReadiness {
    pub maturity: RuntimeMaturity,
    pub missing_runtime_artifacts: &'static [&'static str],
    pub next_milestones: &'static [&'static str],
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum MobilePlatform {
    Android,
    Ios,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum DeviceConnectionKind {
    Usb,
    Emulator,
    RemoteAdb,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DeviceTarget {
    pub platform: MobilePlatform,
    pub device_id: String,
    pub connection_kind: DeviceConnectionKind,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ConnectOptions {
    pub platform: MobilePlatform,
    pub device: Option<String>,
    pub adb_endpoint: Option<String>,
    pub preserve_app_state: bool,
    pub timeout_ms: Option<u32>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct LaunchOptions {
    pub apk_path: Option<String>,
    pub app_id: Option<String>,
    pub launch_activity: Option<String>,
    pub stop_before_launch: bool,
    pub timeout_ms: Option<u32>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct MobileAutomationSessionInfo {
    pub backend: String,
    pub session_id: String,
    pub note: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct MobileBrowserSessionHandle {
    pub platform: MobilePlatform,
    pub automation: MobileAutomationSessionInfo,
    pub device: DeviceTarget,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct MobilePageSessionHandle {
    pub page_id: String,
    pub package_name: Option<String>,
    pub activity_name: Option<String>,
    pub webview_context: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct MobilePageInfo {
    pub note: String,
    pub page_session: MobilePageSessionHandle,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct MobileConnectInfo {
    pub browser: String,
    pub note: String,
    pub browser_session: MobileBrowserSessionHandle,
    pub initial_page: MobilePageInfo,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum SelectorFlavor {
    Css,
    XPath,
    UiAutomator,
}

impl SelectorFlavor {
    fn as_str(self) -> &'static str {
        match self {
            Self::Css => "css",
            Self::XPath => "xpath",
            Self::UiAutomator => "uia",
        }
    }
}

const UIAUTOMATOR_SELECTOR_KEYS: &[&str] = &[
    "text",
    "textcontains",
    "textmatches",
    "textstartswith",
    "classname",
    "classnamematches",
    "description",
    "desc",
    "descriptioncontains",
    "desccontains",
    "descriptionmatches",
    "descmatches",
    "descriptionstartswith",
    "descstartswith",
    "checkable",
    "checked",
    "clickable",
    "longclickable",
    "scrollable",
    "enabled",
    "focusable",
    "focused",
    "selected",
    "packagename",
    "package",
    "packagenamematches",
    "resourceid",
    "resourceidmatches",
    "index",
    "instance",
];

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct MobileLocator {
    pub selector: String,
}

impl MobileLocator {
    pub fn normalize(selector: &str) -> Self {
        Self {
            selector: normalize_selector_for_transport(selector),
        }
    }

    pub fn chain(&self, child_selector: &str) -> Self {
        Self {
            selector: chain_selector_for_transport(&self.selector, child_selector),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct MobileClickInfo {
    pub selector: String,
    pub note: String,
    pub session_id: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct MobileElementCountInfo {
    pub selector: String,
    pub count: u32,
    pub note: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct MobileFillInfo {
    pub selector: String,
    pub value: String,
    pub note: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct MobileElementInfo {
    pub selector: String,
    pub note: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct MobilePressInfo {
    pub selector: String,
    pub key: String,
    pub note: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct MobileTextInfo {
    pub selector: String,
    pub text: String,
    pub note: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct MobileWaitForSelectorInfo {
    pub selector: String,
    pub visible: bool,
    pub note: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct MobileScreenshotInfo {
    pub png_data: Vec<u8>,
    pub note: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "command", rename_all = "snake_case")]
pub enum MobileCommand {
    Connect(ConnectOptions),
    LaunchApp {
        browser_session: MobileBrowserSessionHandle,
        options: LaunchOptions,
    },
    OpenPage {
        browser_session: MobileBrowserSessionHandle,
    },
    ClosePage {
        browser_session: MobileBrowserSessionHandle,
        page_session: MobilePageSessionHandle,
    },
    ClickElement {
        browser_session: MobileBrowserSessionHandle,
        page_session: MobilePageSessionHandle,
        selector: String,
        timeout_ms: Option<u32>,
    },
    CountElements {
        browser_session: MobileBrowserSessionHandle,
        page_session: MobilePageSessionHandle,
        selector: String,
        timeout_ms: Option<u32>,
    },
    FocusElement {
        browser_session: MobileBrowserSessionHandle,
        page_session: MobilePageSessionHandle,
        selector: String,
        timeout_ms: Option<u32>,
    },
    FillElement {
        browser_session: MobileBrowserSessionHandle,
        page_session: MobilePageSessionHandle,
        selector: String,
        value: String,
        timeout_ms: Option<u32>,
    },
    PressKey {
        browser_session: MobileBrowserSessionHandle,
        page_session: MobilePageSessionHandle,
        selector: String,
        key: String,
        text: Option<String>,
        timeout_ms: Option<u32>,
    },
    GetText {
        browser_session: MobileBrowserSessionHandle,
        page_session: MobilePageSessionHandle,
        selector: String,
        timeout_ms: Option<u32>,
    },
    GetInnerText {
        browser_session: MobileBrowserSessionHandle,
        page_session: MobilePageSessionHandle,
        selector: String,
        timeout_ms: Option<u32>,
    },
    WaitForSelector {
        browser_session: MobileBrowserSessionHandle,
        page_session: MobilePageSessionHandle,
        selector: String,
        visible: bool,
        timeout_ms: Option<u32>,
    },
    Screenshot {
        browser_session: MobileBrowserSessionHandle,
        page_session: MobilePageSessionHandle,
        timeout_ms: Option<u32>,
        full_page: bool,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "result", rename_all = "snake_case")]
pub enum MobileCommandResult {
    Connect(MobileConnectInfo),
    LaunchApp(MobilePageInfo),
    OpenPage(MobilePageInfo),
    ClosePage,
    ClickElement(MobileClickInfo),
    CountElements(MobileElementCountInfo),
    FocusElement(MobileElementInfo),
    FillElement(MobileFillInfo),
    PressKey(MobilePressInfo),
    GetText(MobileTextInfo),
    GetInnerText(MobileTextInfo),
    WaitForSelector(MobileWaitForSelectorInfo),
    Screenshot(MobileScreenshotInfo),
}

pub fn shared_descriptor() -> SurfacePluginDescriptor {
    SurfacePluginDescriptor {
        id: SURFACE_ID,
        family: SurfaceFamily::Mobile,
        version: env!("CARGO_PKG_VERSION"),
        description: "Shared mobile surface abstractions for Android and iOS plugins.",
    }
}

pub async fn boot_surface(label: &str, delay_ms: u64) -> String {
    sleep(Duration::from_millis(delay_ms)).await;
    format!("{label} ready")
}

pub async fn boot() -> String {
    boot_surface("mobile", 25).await
}

fn parse_explicit_selector_prefix(selector: &str) -> Option<(SelectorFlavor, usize)> {
    let lowered = selector.to_ascii_lowercase();
    if lowered.starts_with("xpath=") || lowered.starts_with("xpath:") {
        return Some((SelectorFlavor::XPath, 6));
    }
    if lowered.starts_with("uia=") || lowered.starts_with("uia:") {
        return Some((SelectorFlavor::UiAutomator, 4));
    }
    if let Some(prefix_len) = uiautomator_selector_prefix_len(&lowered) {
        return Some((SelectorFlavor::UiAutomator, prefix_len));
    }
    if lowered.starts_with("text=") || lowered.starts_with("text:") {
        return Some((SelectorFlavor::UiAutomator, 5));
    }
    if lowered.starts_with("id=") || lowered.starts_with("id:") {
        return Some((SelectorFlavor::Css, 3));
    }
    if lowered.starts_with("css=") || lowered.starts_with("css:") {
        return Some((SelectorFlavor::Css, 4));
    }
    None
}

fn uiautomator_selector_prefix_len(lowered: &str) -> Option<usize> {
    UIAUTOMATOR_SELECTOR_KEYS.iter().find_map(|key| {
        if lowered.starts_with(key) {
            let separator = lowered.as_bytes().get(key.len()).copied()?;
            if separator == b'=' || separator == b':' {
                return Some(key.len() + 1);
            }
        }
        None
    })
}

fn find_json_string_end(value: &str) -> Option<usize> {
    let bytes = value.as_bytes();
    if bytes.first().copied()? != b'"' {
        return None;
    }

    let mut index = 1usize;
    let mut escaped = false;
    while index < bytes.len() {
        let byte = bytes[index];
        if escaped {
            escaped = false;
            index += 1;
            continue;
        }
        match byte {
            b'\\' => escaped = true,
            b'"' => return Some(index + 1),
            _ => {}
        }
        index += 1;
    }
    None
}

fn is_normalized_transport_selector(selector: &str) -> bool {
    let trimmed = selector.trim();
    if trimmed.is_empty() {
        return false;
    }

    let mut index = 0usize;
    while index < trimmed.len() {
        let Some((_, prefix_len)) = parse_explicit_selector_prefix(&trimmed[index..]) else {
            return false;
        };

        index += prefix_len;
        let remainder = &trimmed[index..];
        if !remainder.starts_with('"') {
            return false;
        }

        let Some(json_end) = find_json_string_end(remainder) else {
            return false;
        };
        index += json_end;

        if index == trimmed.len() {
            return true;
        }

        let whitespace_len = trimmed[index..]
            .chars()
            .take_while(|char| char.is_ascii_whitespace())
            .count();
        if whitespace_len == 0 {
            return false;
        }
        index += whitespace_len;

        if parse_explicit_selector_prefix(&trimmed[index..]).is_none() {
            return false;
        }
    }

    true
}

fn decode_selector_body(body: &str) -> String {
    let candidate = body.trim();
    if candidate.len() >= 2 && candidate.starts_with('"') && candidate.ends_with('"') {
        if let Ok(decoded) = serde_json::from_str::<String>(candidate) {
            return unescape_shell_escaped_selector(&decoded);
        }
    }
    unescape_shell_escaped_selector(candidate)
}

fn unescape_shell_escaped_selector(value: &str) -> String {
    let mut result = String::with_capacity(value.len());
    let mut chars = value.chars().peekable();
    while let Some(ch) = chars.next() {
        if ch == '\\' {
            match chars.peek().copied() {
                Some('_' | ' ' | '#' | ':' | '[' | ']' | '(' | ')' | '"' | '\'') => {
                    result.push(chars.next().expect("peeked char should exist"));
                    continue;
                }
                _ => {}
            }
        }
        result.push(ch);
    }
    result
}

pub fn parse_selector_for_transport(selector: &str) -> (SelectorFlavor, String) {
    let trimmed = selector.trim();
    let lowered = trimmed.to_ascii_lowercase();
    if lowered.starts_with("xpath=") || lowered.starts_with("xpath:") {
        return (SelectorFlavor::XPath, decode_selector_body(&trimmed[6..]));
    }
    if lowered.starts_with("uia=") || lowered.starts_with("uia:") {
        return (
            SelectorFlavor::UiAutomator,
            decode_selector_body(&trimmed[4..]),
        );
    }
    if let Some(prefix_len) = uiautomator_selector_prefix_len(&lowered) {
        return (
            SelectorFlavor::UiAutomator,
            trimmed[..prefix_len - 1].to_string()
                + "="
                + &decode_selector_body(&trimmed[prefix_len..]),
        );
    }
    if lowered.starts_with("text=") || lowered.starts_with("text:") {
        let body = decode_selector_body(&trimmed[5..]);
        return (SelectorFlavor::UiAutomator, format!("text={body}"));
    }
    if lowered.starts_with("id=") || lowered.starts_with("id:") {
        let body = decode_selector_body(&trimmed[3..]);
        let normalized = if body.starts_with('#') {
            body
        } else {
            format!("#{body}")
        };
        return (SelectorFlavor::Css, normalized);
    }
    if lowered.starts_with("css=") || lowered.starts_with("css:") {
        return (SelectorFlavor::Css, decode_selector_body(&trimmed[4..]));
    }
    if trimmed.starts_with("//")
        || trimmed.starts_with(".//")
        || trimmed.starts_with("../")
        || trimmed.starts_with('/')
        || trimmed.starts_with('(')
    {
        return (SelectorFlavor::XPath, trimmed.to_string());
    }
    (SelectorFlavor::Css, trimmed.to_string())
}

pub fn normalize_selector_for_transport(selector: &str) -> String {
    let trimmed = selector.trim();
    if trimmed.is_empty() {
        return String::new();
    }
    if is_normalized_transport_selector(trimmed) {
        return trimmed.to_string();
    }
    let (flavor, body) = parse_selector_for_transport(selector);
    format!(
        "{}={}",
        flavor.as_str(),
        serde_json::to_string(&body).unwrap_or_else(|_| format!("{body:?}"))
    )
}

pub fn chain_selector_for_transport(parent: &str, child: &str) -> String {
    let parent_selector = if parent.trim().is_empty() {
        String::new()
    } else {
        normalize_selector_for_transport(parent)
    };
    let child_selector = if child.trim().is_empty() {
        String::new()
    } else {
        normalize_selector_for_transport(child)
    };
    if parent_selector.is_empty() {
        return child_selector;
    }
    if child_selector.is_empty() {
        return parent_selector;
    }
    format!("{parent_selector} {child_selector}")
}

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

    #[tokio::test]
    async fn boots_mobile_runtime() {
        assert_eq!(boot().await, "mobile ready");
    }

    #[tokio::test]
    async fn boots_named_mobile_surface() {
        assert_eq!(boot_surface("android", 1).await, "android ready");
    }

    #[test]
    fn normalizes_xpath_and_css_like_web_clients() {
        assert_eq!(
            normalize_selector_for_transport("xpath=//android.widget.TextView"),
            "xpath=\"//android.widget.TextView\""
        );
        assert_eq!(normalize_selector_for_transport("#login"), "css=\"#login\"");
        assert_eq!(
            normalize_selector_for_transport("Id=bottom_nav_account"),
            "css=\"#bottom_nav_account\""
        );
        assert_eq!(
            normalize_selector_for_transport(r"Id=bottom\_nav\_account"),
            "css=\"#bottom_nav_account\""
        );
        assert_eq!(
            normalize_selector_for_transport("text=Account"),
            "uia=\"text=Account\""
        );
        assert_eq!(
            normalize_selector_for_transport("textContains=Account"),
            "uia=\"textContains=Account\""
        );
        assert_eq!(
            normalize_selector_for_transport("resourceId=com.example:id/login"),
            "uia=\"resourceId=com.example:id/login\""
        );
        assert_eq!(
            normalize_selector_for_transport("descriptionContains=Account"),
            "uia=\"descriptionContains=Account\""
        );
        assert_eq!(
            normalize_selector_for_transport("selected=true"),
            "uia=\"selected=true\""
        );
        assert_eq!(
            normalize_selector_for_transport("classNameMatches=android\\.widget\\..*"),
            "uia=\"classNameMatches=android\\\\.widget\\\\..*\""
        );
    }

    #[test]
    fn chains_mobile_locators_like_web_locators() {
        let parent = MobileLocator::normalize("xpath=//android.view.ViewGroup");
        let child = parent.chain("css=.cta");
        assert_eq!(
            child.selector,
            "xpath=\"//android.view.ViewGroup\" css=\".cta\""
        );
    }

    #[test]
    fn mobile_connect_command_returns_web_like_session_shape() {
        let command = MobileCommand::Connect(ConnectOptions {
            platform: MobilePlatform::Android,
            device: Some("emulator-5554".to_string()),
            adb_endpoint: None,
            preserve_app_state: true,
            timeout_ms: Some(5_000),
        });

        match command {
            MobileCommand::Connect(options) => {
                assert_eq!(options.platform, MobilePlatform::Android);
                assert_eq!(options.device.as_deref(), Some("emulator-5554"));
            }
            _ => panic!("expected connect command"),
        }
    }

    #[test]
    fn mobile_launch_command_keeps_launch_shape_separate() {
        let browser_session = MobileBrowserSessionHandle {
            platform: MobilePlatform::Android,
            automation: MobileAutomationSessionInfo {
                backend: "uiautomator2".to_string(),
                session_id: "uiautomator2:emulator-5554".to_string(),
                note: "ready".to_string(),
            },
            device: DeviceTarget {
                platform: MobilePlatform::Android,
                device_id: "emulator-5554".to_string(),
                connection_kind: DeviceConnectionKind::Emulator,
            },
        };

        let command = MobileCommand::LaunchApp {
            browser_session,
            options: LaunchOptions {
                apk_path: Some("/tmp/app.apk".to_string()),
                app_id: Some("dev.allwright.sample".to_string()),
                launch_activity: Some(".MainActivity".to_string()),
                stop_before_launch: true,
                timeout_ms: Some(15_000),
            },
        };

        match command {
            MobileCommand::LaunchApp { options, .. } => {
                assert_eq!(options.apk_path.as_deref(), Some("/tmp/app.apk"));
                assert!(options.stop_before_launch);
            }
            _ => panic!("expected launch command"),
        }
    }
}