mobile-agent-android 0.1.0-alpha.1

mobile-agent's Android driver: the adb client, the agent's deploy and session, and the emulator's gRPC controller
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
//! Integration tests for the agent session behind the mirror (task 5.3).
//!
//! They run only when `MOBILE_AGENT_ANDROID_SERIAL` names a device with the
//! Compose fixture installed (`fixtures/compose`), one at a time, and need
//! the agent jar. Each starts the fixture, attaches, and stops its agent at
//! the end (or kills it by pid when it fails first); the controller test
//! also needs an emulator started with `-grpc <port> -grpc-use-token`. The
//! device may be shared: a test that another user disturbs (its agent takes
//! UI automation, or it moves the fixture) runs again once the device is
//! quiet.

mod common;

use std::time::{Duration, Instant};

use android::adb::{AdbServer, Device};
use android::agent::{Attached, DeployOptions, Deployer, Records};
use android::emulator::{self, Options};
use android::session::{ControllerLink, Session, SessionOptions};
use common::{
    COMPOSE, Disturbed, Fixture, Leftovers, agent_alive, agent_jar, compose_in_front, device_lock,
    disturbed_by, launch_compose, retry_when_disturbed, serial_or_skip,
};
use mirror::backend::{ReadReason, ReadRequest, StreamItem};
use mirror::{
    Action, Condition, Degradation, Mirror, MirrorConfig, Selector, SnapshotOptions, Target,
};

fn device(serial: &str) -> Device {
    AdbServer::from_env().device(serial)
}

fn ms(d: Duration) -> f64 {
    d.as_secs_f64() * 1e3
}

fn attach(device: &Device, leftovers: &mut Leftovers) -> Result<Attached, Disturbed> {
    let attached = Deployer::new(device.clone(), agent_jar(), Records::in_memory())
        .attach(&DeployOptions {
            idle_exit: Duration::from_secs(10),
            ..DeployOptions::default()
        })
        .map_err(|e| disturbed_by(device, e))?;
    leftovers.track(attached.agent.pid, &attached.agent.socket);
    Ok(attached)
}

/// Nodes in the mirror's replica: the indented lines of its dump.
fn replica_nodes(mirror: &Mirror) -> usize {
    mirror
        .dump()
        .lines()
        .filter(|line| line.starts_with("  "))
        .count()
}

/// The bounds of the node whose resource id is `id`.
fn find_bounds(
    snapshot: &protocol::snapshot::Snapshot,
    id: &str,
) -> Option<protocol::snapshot::Bounds> {
    fn walk(node: &protocol::snapshot::Node, id: &str) -> Option<protocol::snapshot::Bounds> {
        if node.res_id.as_deref() == Some(id) {
            return Some(node.bounds);
        }
        node.children.iter().find_map(|child| walk(child, id))
    }
    snapshot
        .windows
        .iter()
        .filter_map(|w| w.root.as_ref())
        .find_map(|root| walk(root, id))
}

/// The full-stack test of task 5.3: a mirror built on the session serves
/// the Compose Big screen with the node count the agent reported, a tap
/// through the input sink changes the tree, and a killed agent is reported
/// disconnected within 5 s (android-driver "Agent lifecycle", device-protocol
/// "Liveness detection", ui-mirror "Replica maintained from device events").
#[test]
fn the_mirror_serves_compose_big_follows_a_tap_and_reports_a_killed_agent() {
    let test = "the_mirror_serves_compose_big_follows_a_tap_and_reports_a_killed_agent";
    let Some(serial) = serial_or_skip(test) else {
        return;
    };
    let _device = device_lock();
    let device = device(&serial);
    retry_when_disturbed(test, &device, || full_stack(&device));
}

fn full_stack(device: &Device) -> Result<(), Disturbed> {
    let mut leftovers = Leftovers::new(device);
    launch_compose(device, "big")?;
    let _fixture = Fixture(device.clone());
    let attached = attach(device, &mut leftovers)?;
    let session =
        Session::start(attached, SessionOptions::default(), None).unwrap_or_else(|e| panic!("{e}"));
    assert_eq!(
        session.scale(),
        2.625,
        "the API 36 emulator runs at 420 dpi"
    );
    let mut mirror = Mirror::new(session.backend(), MirrorConfig::default());

    let started = Instant::now();
    let big = mirror.snapshot(&SnapshotOptions::interactive()).unwrap();
    let cold = started.elapsed();
    compose_in_front(device, "the first snapshot")?;
    if !big.text.contains("cell-500") {
        return Err(Disturbed(format!(
            "the first snapshot shows another tab: {}",
            big.text.lines().take(3).collect::<Vec<_>>().join(" | ")
        )));
    }
    let read = session.last_read().expect("a tree read");
    assert_eq!(read.serialized, read.node_count, "the read was cut short");
    assert_eq!(replica_nodes(&mirror), read.node_count as usize);
    assert!(read.node_count >= 500, "{} nodes", read.node_count);
    for i in 1..=500 {
        let id = format!("cell-{i}");
        let cell = big
            .elements
            .iter()
            .find(|e| e.identifier.as_deref() == Some(id.as_str()))
            .unwrap_or_else(|| panic!("no {id} in the snapshot"));
        assert!(cell.reference.is_some(), "{id} has no ref");
    }
    assert!(!big.verdict.degraded, "{:?}", big.verdict);

    // Warm snapshots come from the replica without a device read. The
    // Compose window, which sends no events, is read again every second
    // (the mirror's poll); that read is let pass first, so that none falls
    // due while the snapshots are timed.
    if let Some(due) = mirror.next_wakeup() {
        mirror.run_until(due + Duration::from_millis(50)).unwrap();
    }
    let reads = session.reads();
    let quiet_until = mirror.next_wakeup();
    let mut warm = Vec::new();
    for _ in 0..20 {
        let t = Instant::now();
        mirror.snapshot(&SnapshotOptions::interactive()).unwrap();
        warm.push(ms(t.elapsed()));
    }
    if quiet_until.is_none_or(|due| Instant::now() < due) {
        assert_eq!(session.reads(), reads, "a warm snapshot read the device");
    } else {
        eprintln!("the warm snapshots outlasted the poll interval; reads not compared");
    }

    // A tap on the Login tab, through the sink, changes the tree.
    let tab = big
        .elements
        .iter()
        .find(|e| e.identifier.as_deref() == Some("tab-login"))
        .and_then(|e| e.reference)
        .expect("a ref for tab-login");
    let tapped = Instant::now();
    let outcome = mirror
        .act(&Action::Tap {
            target: Target::Ref(tab),
            hold: None,
        })
        .unwrap();
    let acknowledged = tapped.elapsed();
    assert!(outcome.accepted);
    let login = mirror.snapshot(&SnapshotOptions::interactive()).unwrap();
    let changed = tapped.elapsed();
    compose_in_front(device, "the tap")?;
    assert!(login.text.contains("login-username"), "{}", login.text);
    assert!(!login.text.contains("cell-1"), "{}", login.text);

    // Killing the agent is reported within 5 s. A read already due can fail
    // with `disconnected` before the mirror takes the stream's report;
    // either is the disconnection reported.
    let (pid, socket) = (session.agent().pid, session.agent().socket.clone());
    let killed = Instant::now();
    device
        .shell(&format!(
            "grep -qF {socket} /proc/{pid}/cmdline && kill -9 {pid}"
        ))
        .unwrap();
    let reported = |result: Result<(), mirror::MirrorError>| match result {
        Err(e) if e.code() == protocol::code::DISCONNECTED => true,
        Err(e) => panic!("{e}"),
        Ok(()) => false,
    };
    let detected = loop {
        let pumped = mirror.run_until(Instant::now() + Duration::from_millis(20));
        let snapshot = mirror.snapshot(&SnapshotOptions::interactive());
        let in_verdict = snapshot.as_ref().is_ok_and(|s| {
            s.verdict
                .reasons
                .iter()
                .any(|r| matches!(r, Degradation::Disconnected(_)))
        });
        if in_verdict || reported(pumped) || reported(snapshot.map(|_| ())) {
            break killed.elapsed();
        }
        assert!(
            killed.elapsed() < Duration::from_secs(5),
            "no disconnection reported 5 s after the kill"
        );
    };
    let last = mirror.snapshot(&SnapshotOptions::interactive()).unwrap();
    assert!(
        last.verdict
            .reasons
            .iter()
            .any(|r| matches!(r, Degradation::Disconnected(_))),
        "{:?}",
        last.verdict
    );
    assert!(!agent_alive(device, pid, &socket));
    let refused = mirror.act(&Action::Tap {
        target: Target::Ref(tab),
        hold: None,
    });
    assert!(refused.is_err(), "an action on a disconnected target");

    eprintln!(
        "Compose Big through the mirror: {} nodes, first snapshot {:.1} ms (agent read {:.1} ms); \
         warm snapshot p50 {:.2} ms, p95 {:.2} ms; tap acknowledged {:.1} ms, tree changed \
         {:.1} ms after the tap; killed agent reported disconnected after {:.1} ms",
        read.node_count,
        ms(cold),
        ms(read.took),
        common::percentile(&mut warm.clone(), 50.0),
        common::percentile(&mut warm, 95.0),
        ms(acknowledged),
        ms(changed),
        ms(detected),
    );
    Ok(())
}

/// Task 10.9, through the driver: the mirror's read after a tap that tears
/// the Compose Big screen down under the agent's own re-read of it is
/// answered within the session's deadline. An injected action brings the
/// agent's re-read of a Compose window forward to 200 ms after it (on its
/// 100 ms tick), and a cold read of the 500 cells takes about 350 ms, so
/// after a tap on the Big tab the agent starts walking the cells 200 to
/// 300 ms later and is still among them past 500 ms, and a tap on the Login
/// tab 350 ms after the first takes them away under that walk. In the 10.1
/// run the read after such a tap waited behind a walk that spent about
/// 57 ms on each cell that was gone, and failed with `deadline_exceeded`
/// after 10 s.
#[test]
fn a_snapshot_after_a_tap_that_tears_the_big_screen_down_under_the_agents_reread_is_answered_in_time()
 {
    let test = "a_snapshot_after_a_tap_that_tears_the_big_screen_down_under_the_agents_reread_is_answered_in_time";
    let Some(serial) = serial_or_skip(test) else {
        return;
    };
    let _device = device_lock();
    let device = device(&serial);
    retry_when_disturbed(test, &device, || teardown_under_the_reread(&device));
}

fn teardown_under_the_reread(device: &Device) -> Result<(), Disturbed> {
    let mut leftovers = Leftovers::new(device);
    launch_compose(device, "login")?;
    let _fixture = Fixture(device.clone());
    let attached = attach(device, &mut leftovers)?;
    let options = SessionOptions::default();
    let deadline = options.read.deadline;
    let session = Session::start(attached, options, None).unwrap_or_else(|e| panic!("{e}"));
    let mut mirror = Mirror::new(session.backend(), MirrorConfig::default());
    // Every element: the interactive listing leaves out the selected tab.
    let login = mirror.snapshot(&SnapshotOptions::full()).unwrap();
    compose_in_front(device, "the first snapshot")?;
    // Points rather than refs, since aiming at a ref reads the tree first.
    let tab = |id: &str| {
        login
            .elements
            .iter()
            .find(|e| e.identifier.as_deref() == Some(id))
            .map(|e| e.bounds.center())
            .unwrap_or_else(|| panic!("no {id} in {}", login.text))
    };
    let (big, back) = (tab("tab-big"), tab("tab-login"));
    let mut answered = Vec::new();
    for round in 1..=3 {
        mirror
            .act(&Action::Tap {
                target: Target::Point(big),
                hold: None,
            })
            .unwrap();
        std::thread::sleep(Duration::from_millis(350));
        mirror
            .act(&Action::Tap {
                target: Target::Point(back),
                hold: None,
            })
            .unwrap();
        let asked = Instant::now();
        let after = mirror.snapshot(&SnapshotOptions::interactive());
        let took = asked.elapsed();
        compose_in_front(device, "the taps")?;
        let after = after.unwrap_or_else(|e| {
            panic!(
                "round {round}: the read after the Login tap failed after {:.0} ms: {e}",
                ms(took)
            )
        });
        assert!(
            after.text.contains("login-username"),
            "round {round}: {}",
            after.text
        );
        assert!(
            !after.text.contains("cell-1"),
            "round {round}: {}",
            after.text
        );
        assert!(took < deadline, "round {round}: {:.0} ms", ms(took));
        answered.push(ms(took));
    }
    eprintln!(
        "read after a tap that took the Big screen away under the agent's re-read, answered after \
         {answered:.0?} ms (deadline {} ms)",
        deadline.as_millis()
    );
    session.stop(Duration::from_secs(3)).unwrap();
    Ok(())
}

/// Spec scenario "App restarted" (Agent lifecycle), through the driver: the
/// same agent and session serve the mirror after the app is force-stopped
/// and relaunched.
#[test]
fn the_same_agent_serves_the_mirror_after_the_app_is_force_stopped_and_relaunched() {
    let test = "the_same_agent_serves_the_mirror_after_the_app_is_force_stopped_and_relaunched";
    let Some(serial) = serial_or_skip(test) else {
        return;
    };
    let _device = device_lock();
    let device = device(&serial);
    retry_when_disturbed(test, &device, || app_restart(&device));
}

fn app_restart(device: &Device) -> Result<(), Disturbed> {
    let mut leftovers = Leftovers::new(device);
    launch_compose(device, "big")?;
    let _fixture = Fixture(device.clone());
    let attached = attach(device, &mut leftovers)?;
    let session =
        Session::start(attached, SessionOptions::default(), None).unwrap_or_else(|e| panic!("{e}"));
    let mut mirror = Mirror::new(session.backend(), MirrorConfig::default());
    let big = mirror.snapshot(&SnapshotOptions::interactive()).unwrap();
    compose_in_front(device, "the first snapshot")?;
    if !big.text.contains("cell-1") {
        return Err(Disturbed("the first snapshot shows another tab".into()));
    }

    device.shell(&format!("am force-stop {COMPOSE}")).unwrap();
    launch_compose(device, "login")?;
    let found = mirror.wait(
        &Selector::identifier("login-username"),
        Condition::Appear,
        Duration::from_secs(10),
    );
    compose_in_front(device, "the relaunch")?;
    let found = found.unwrap_or_else(|e| panic!("{e}"));
    assert!(found.element.is_some());
    assert!(session.close_reason().is_none(), "the session was lost");
    let (pid, socket) = (session.agent().pid, session.agent().socket.clone());
    assert!(agent_alive(device, pid, &socket), "the agent was restarted");
    session.stop(Duration::from_secs(3)).unwrap();
    Ok(())
}

/// On an emulator with its controller, frames arrive on the session's
/// event stream with hashes that leave the status bar out: a tab switch
/// changes the hash, and the frames encode as JPEG.
#[test]
fn controller_frames_arrive_on_the_event_stream_with_status_bar_free_hashes() {
    let test = "controller_frames_arrive_on_the_event_stream_with_status_bar_free_hashes";
    let Some(serial) = serial_or_skip(test) else {
        return;
    };
    let _device = device_lock();
    let device = device(&serial);
    retry_when_disturbed(test, &device, || controller_frames(&serial, &device));
}

fn controller_frames(serial: &str, device: &Device) -> Result<(), Disturbed> {
    let mut leftovers = Leftovers::new(device);
    launch_compose(device, "login")?;
    let _fixture = Fixture(device.clone());
    let endpoint = emulator::resolve(serial).unwrap_or_else(|e| panic!("{e}"));
    let link =
        ControllerLink::connect(&endpoint, Options::default()).unwrap_or_else(|e| panic!("{e}"));
    let attached = attach(device, &mut leftovers)?;
    let session = Session::start(attached, SessionOptions::default(), Some(link))
        .unwrap_or_else(|e| panic!("{e}"));
    assert!(session.uses_controller());
    let mut backend = session.backend();

    // Tap the List tab, found in a tree read, so that the screen changes.
    let tree = backend
        .tree
        .read(&ReadRequest {
            windows: None,
            reason: ReadReason::Attach,
        })
        .unwrap();
    compose_in_front(device, "the tree read")?;
    let Some(bounds) = find_bounds(&tree.snapshot, "tab-list") else {
        return Err(Disturbed("no tab-list in the tree".into()));
    };
    let at = mirror::Point::new(
        f64::from(bounds.left + bounds.right) / 2.0 / tree.scale,
        f64::from(bounds.top + bounds.bottom) / 2.0 / tree.scale,
    );
    backend
        .input
        .perform(&mirror::backend::Input::Tap { at, hold: None })
        .unwrap();
    let mut frames = Vec::new();
    let until = Instant::now() + Duration::from_secs(3);
    while let Some(item) = backend.events.next(until) {
        if let StreamItem::Frame(meta) = item.item {
            frames.push(meta);
        }
    }
    compose_in_front(device, "the frames")?;
    assert!(
        frames.len() >= 2,
        "{} frames in 3 s after a tab switch",
        frames.len()
    );
    let (first, last) = (frames[0], frames[frames.len() - 1]);
    assert_ne!(
        first.hash, last.hash,
        "the tab switch left the hash unchanged"
    );
    assert!(frames.windows(2).all(|w| w[0].seq < w[1].seq));
    assert_eq!((last.width, last.height), (540, 1200));
    let source = backend.frames.as_mut().expect("a frame source");
    let latest = source.latest().expect("the latest frame");
    let jpeg = source
        .encode(&mirror::backend::EncodeRequest {
            seq: latest.seq,
            width: 450,
            height: 1000,
            quality: 80,
            rotation: latest.rotation,
        })
        .unwrap();
    assert_eq!(&jpeg[..2], [0xFF, 0xD8]);
    let mut hashes: Vec<u64> = frames.iter().map(|f| f.hash).collect();
    hashes.sort_unstable();
    hashes.dedup();
    eprintln!(
        "{} frames in the 3 s after a tab switch, {} distinct hashes; latest encoded to {} bytes",
        frames.len(),
        hashes.len(),
        jpeg.len()
    );
    session.stop(Duration::from_secs(3)).unwrap();
    Ok(())
}