-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathtest.ex
More file actions
1976 lines (1621 loc) · 80 KB
/
Copy pathtest.ex
File metadata and controls
1976 lines (1621 loc) · 80 KB
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
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
defmodule Mob.Test do
@moduledoc """
Remote inspection and interaction helpers for connected Mob apps.
All functions accept a `node` atom and operate on the running screen via
Erlang distribution. Connect first with `mix mob.connect`, then use these
from IEx or from an agent via `:rpc.call/4`.
## Quick reference
node = :"[email protected]"
# Inspection
Mob.Test.screen(node) #=> MyApp.HomeScreen
Mob.Test.assigns(node) #=> %{count: 3, ...}
Mob.Test.tree(node) #=> %{type: :column, ...}
Mob.Test.find(node, "Save") #=> [{[0, 2], %{...}}]
Mob.Test.inspect(node) #=> %{screen: ..., assigns: ..., tree: ...}
# Interaction
Mob.Test.tap(node, :increment) # tap a button by tag
Mob.Test.back(node) # system back gesture
Mob.Test.pop(node) # pop to previous screen (synchronous)
Mob.Test.navigate(node, MyApp.DetailScreen, %{id: 42})
Mob.Test.pop_to(node, MyApp.HomeScreen)
Mob.Test.pop_to_root(node)
# Lists
Mob.Test.select(node, :my_list, 0) # select first row
# Visual capture + scroll (in-process, over dist — no adb/xcrun)
{:ok, png} = Mob.Test.screenshot(node)
Mob.Test.scroll_info(node, "feed") # offset/content/viewport
Mob.Test.scroll_to(node, "feed", :bottom)
Mob.Test.screenshot_tour(node, "feed") # page top→bottom, capture each
# Element positions without a screenshot (elements need an :id)
Mob.Test.element_frames(node) # %{id => {x, y, w, h}}
Mob.Test.frame(node, "save") # {x, y, w, h}
Mob.Test.tap_id(node, "save") # drive by id at real coords
# What colour did the app actually draw? (samples pixels — the view tree can't)
Mob.Test.sample_color(node, "my-card") # %{average: 0xFF2196F3, ...}
# Device API simulation
Mob.Test.send_message(node, {:permission, :camera, :granted})
Mob.Test.send_message(node, {:camera, :photo, %{path: "/tmp/photo.jpg", width: 1920, height: 1080}})
Mob.Test.send_message(node, {:location, %{lat: 43.65, lon: -79.38, accuracy: 10.0, altitude: 80.0}})
Mob.Test.send_message(node, {:notification, %{id: "n1", title: "Hi", body: "Hey", data: %{}, source: :push}})
## Tap vs send_message
`tap/2` sends the same `{:tap, tag}` message a native tap produces, so it
arrives in the screen's `handle_info/2` exactly like a real button press.
`send_message/2` delivers any term to `handle_info/2`.
Use `send_message/2` to simulate async results from device APIs (camera, location,
notifications, etc.) without having to trigger the actual hardware.
## Synchronous vs fire-and-forget
Navigation functions (`pop`, `navigate`, `pop_to`, `pop_to_root`) are synchronous —
they block until the navigation and re-render complete. This makes them safe to
follow immediately with `screen/1` or `assigns/1` to verify the result.
`back/1`, `tap/2` and `send_message/2` are fire-and-forget (they send a message
to the screen process and return immediately). Use `settle/2` as a sync point
if you need to wait before reading state:
Mob.Test.send_message(node, {:permission, :camera, :granted})
Mob.Test.settle(node)
Mob.Test.assigns(node)
`:sys.get_state/1` on `:mob_screen` is no longer sufficient on its own: since
MOB-110 the tree is handed to `Mob.Sender` and committed asynchronously, and
since MOB-112 `:mob_screen` is the navigation owner rather than the screen
itself. That only matters for the
functions that read the *native* side — `view_tree/1`, `screenshot/2`,
`tap_id/2`, `element_frames/2`. `tree/1` and `assigns/1` re-render in-process
and are unaffected.
## Two layers of inspection: render tree vs native UI
`Mob.Test` exposes two complementary views of what the app is showing:
| API | Source | When to use |
|-------------------------------|-------------------------------------|-------------|
| `tree/1`, `find/2` | Mob render tree (logical components) | Mob apps you control. Fast, exact, has `on_tap` tags, no AX activation needed. |
| `view_tree/1`, `find_view/2` | Native view hierarchy via NIF | Native pixel frames **and painted colours**; works for any app on iOS UIKit; shallow on SwiftUI/Compose. |
| `ui_tree/1` | OS accessibility tree | What sighted users read; works on any app *if* AX is active (iOS: VoiceOver). Strict superset of `view_tree` for UIKit; the only path to semantics inside SwiftUI/Compose. |
Choose render tree first if your app is Mob-rendered. Reach for `view_tree`
when you want native frames or geometry. Reach for `ui_tree` when you need
to inspect non-Mob content (alerts, system overlays, third-party SDK UI),
or to verify the *rendered* state matches the logical render.
## Driving controls beyond plain taps
- **Buttons / nav items** — `tap/2` (by tag, fastest), or
`mob_nif:tap/1` (by accessibility label), or `tap_xy/3` (by coordinate).
- **Sliders, steppers, pickers** — `adjust_slider/4` and the underlying
`ax_action/3` / `ax_action_at_xy/4` use `accessibilityIncrement` /
`accessibilityDecrement`. Synthetic drag gestures don't fire SwiftUI's
`DragGesture` reliably; AX actions do.
- **Switches / toggles** — `toggle/2` finds the switch by nearby label and
activates it via the AX path (sends `accessibilityActivate`).
- **Modals / alerts / sheets** — `dismiss_alert/2` uses
`accessibilityActivate` on the named button; `ax_action/3` with
`:escape` sends `accessibilityPerformEscape`.
- **Scroll views** — `ax_action/3` with `:scroll_up`/`:scroll_down`/
`:scroll_left`/`:scroll_right` sends `accessibilityScroll:`.
- **System back** — `back/1` (Mob screens, framework-level) or — for
sidecar mode against arbitrary apps — synthetic edge-pan via `swipe/5`
from `x=0`, but iOS owns that gesture above the app process and the
synthetic pan won't fire. Use `back/1` for Mob, document the limitation
for sidecar.
## Platform support matrix
| Helper | iOS sim | iOS device | Android |
|------------------------------|---------------|---------------|-----------------|
| `screen/1`, `assigns/1` | ✅ | ✅ | ✅ |
| `tap/2` (by tag) | ✅ | ✅ | ✅ |
| `back/1`, `pop/1`, `navigate`| ✅ | ✅ | ✅ |
| `send_message/2` | ✅ | ✅ | ✅ |
| `screen_info/1` | ✅ | ✅ | ✅ |
| `view_tree/1` | ✅ (shallow†) | ✅ (shallow†) | ✅ (0.4.33+)‡ |
| `sample_color/2` | ✅ | ✅ | ❌ not_loaded° |
| `find_view/2` | ✅ | ✅ | ✅ (0.4.33+)‡ |
| `ui_tree/1` (legacy AX) | ⚠️ AX active§ | ⚠️ AX active§ | ❌ not_loaded |
| `ax_action/3` | ⚠️ AX active§ | ⚠️ AX active§ | ❌ not_supported |
| `ax_action_at_xy/4` | ⚠️ AX active§ | ⚠️ AX active§ | ❌ not_supported |
| `toggle/2` | ⚠️ AX active§ | ⚠️ AX active§ | ❌ ui_tree_unavailable |
| `dismiss_alert/2` | ⚠️ AX active§ | ⚠️ AX active§ | ❌ ui_tree_unavailable |
| `adjust_slider/4` | ⚠️ AX active§ | ⚠️ AX active§ | ❌ ui_tree_unavailable |
| `tap_xy/3` | ⚠️ AX-activatable only¶ | ❌ no_effect¶ | ✅ ⊕ |
| `long_press_xy/4` | ⚠️ acceptance only✱| ⚠️ acceptance only✱| ✅ ⊕ |
| `swipe/5` | ⚠️ scroll only| ⚠️ acceptance only✱| ✅ ⊕ |
| `type_text/2` | ⚠️ acceptance only✱| ⚠️ acceptance only✱| ✅ ASCII only⊕ |
| `delete_backward/1` | ⚠️ acceptance only✱| ⚠️ acceptance only✱| ✅ ⊕ |
| `clear_text/1` | ⚠️ acceptance only✱| ⚠️ acceptance only✱| ❌ not_loaded⊕ |
| `capabilities/1` | ✅ | ✅ | ✅ |
**This table is a snapshot, and snapshots drift.** Ask the running app
instead — `capabilities/1` reports what THIS build can actually serve. On
Android that is a per-*app* fact, since each harness NIF bails when its
cached `MobBridge` method is absent and the bridge is generated once and
never re-rendered; on iOS it is per-*configuration*, since the whole harness
is compiled out of release builds. Apps generated before `mob_new` 0.4.32
have no synthetic-input methods in their bridge at all and report `false` for
every one of them; regenerate with a new enough `mob_new` to pick them up.
- **†** SwiftUI doesn't expose its content as separate UIView instances —
`view_tree` reaches the SwiftUI hosting view's container and stops.
For semantic content on Mob screens use `tree/1` (render tree); for any
other SwiftUI-based content use `ui_tree/1`.
- **‡** Android's `ui_view_tree` NIF delegates to a `MobBridge.uiViewTree()`
Kotlin method that lives in the app's generated bridge. Apps generated by
`mob_new` 0.4.33 or newer have it (MOB-157): it walks the Mob node tree
and emits the same eight keys iOS does, with `frame` populated only for
nodes carrying an `:id` and `class` / `bg_color` / `text_color` `null`
for now. Apps generated earlier return `{:error, :not_loaded}` until
`MobBridge.kt` is regenerated; `capabilities/1` tells you which you have.
- **°** `sample_region/4` is implemented in `ios/mob_nif.m` only. Android
would need the same crop-in-the-render treatment against the activity
window; until then `sample_color/2` returns `{:error, {:badrpc, _}}` there.
- **§** "AX active" means an iOS accessibility client is asking for the
AX tree so SwiftUI materializes it. Today: VoiceOver toggle. Production:
`XCAXClient_iOS` activation, debug-only — see WireTap stretch goals in
`future_developments.md`.
- **¶** `tap_xy/3` now verifies that the tap actually produced an event
before returning `:ok`. On the simulator that limits it to elements SwiftUI
exposes an accessibility action for (`Button`, text fields) — a `Box` with
`on_tap:` returns `{:error, :no_effect}`. On a physical device the
IOHID-injected touch is accepted but never delivered, so **every**
coordinate returns `{:error, :no_effect}`. Drive taps with `tap/2` (by tag);
see `tap_xy/3` and
`decisions/2026-08-09-ios-device-tap-injection-has-no-effect.md`.
- **⊕** Android synthesises input in-process, dispatching `MotionEvent`s at
the activity's decor view and `KeyEvent`s at the activity. No `adb`, no
`INJECT_EVENTS` (a signature permission no app can hold).
**The ✅ is a property of the app, not of mob.** These call methods on the
app's own generated `MobBridge`, which ships in `mob_new` — they work in an
app generated by `mob_new` 0.4.32 or newer, and return
`{:error, :not_loaded}` in every app generated before that, however new the
`mob` it runs. `MobBridge.kt` is generated once and never re-rendered, so
an existing app needs regenerating. `capabilities/1` answers this for the
build in front of you; the table cannot.
Four more consequences worth knowing before you rely on it:
* **Gestures cost real wall-clock.** A long press or swipe has to hold
the pointer for its real duration, because Android's detectors wait on
posted callbacks and frame boundaries — synthesised timestamps are
ignored. `long_press_xy(node, x, y, 800)` blocks for 800ms. These NIFs
run on a dirty IO scheduler for that reason.
* **Only the activity's own window is reachable.** A `Dialog` or a
Material `ModalBottomSheet` renders in its own window, so a tap aimed
at one lands on the dimmed activity behind it.
* **`type_text/2` is ASCII-only.** The virtual keyboard has no key
sequence for emoji or accented Latin, and one unmappable character
rejects the whole string, so nothing is typed.
* **`clear_text/1` is absent, not broken.** Two implementations reported
success while clearing nothing (events coalesce faster than the field
recomposes), so the bridge ships without it and the call returns
`{:error, :not_loaded}`. Select-all-and-delete by hand, or rebuild the
field's state through your own event.
Verified on a physical device: tap navigates, long press fires
`on_long_press`, swipe scrolls a scroll view, typing and backspace change
the field. `on_long_press` fires on `column`, `row`, `text`, `icon` and
`box` — not `button`, matching iOS — so a long press on a `button` does
nothing by design.
- **✱** These report `:ok` when the OS *accepted* the input, not when the app
was observed to react — they have not been converted to the observation
model `tap_xy/3` uses. Treat their `:ok` as "sent", not "worked".
Two different reasons sit behind that, and they lead to different bugs.
`swipe/5` and `long_press_xy/4` ride the same IOHID injection path as
`tap_xy/3`, which on a physical device is accepted and never delivered —
so their `:ok` there is actively misleading. `type_text/2`,
`delete_backward/1` and `clear_text/1` do NOT touch that path; they
`dispatch_sync` and message the first responder directly, so they do
something real, and merely fail to confirm it.
Helpers that depend on AX return clear error tuples on Android instead of
raising. Callers should match on `{:error, :not_supported_on_android}` and
`{:error, :ui_tree_unavailable}` and either skip or fall back to
`send_message/2` for state mutations.
## Known limitations affecting AX automation
Even on iOS with AX active, three Mob component defects keep the natural
paths from working today. Workarounds in each helper's docstring:
- **Slider** — `accessibilityIncrement`/`Decrement` are no-ops because
Mob's iOS Slider doesn't attach `.accessibilityAdjustableAction`.
See `issues.md` #7.
- **Toggle** — the `label:` prop doesn't reach the AX tree; `toggle/2`
can't find the switch by label name. Use `ax_action_at_xy/4` with
coordinates for now. See `issues.md` #8.
- **Alert OK button** — `accessibilityActivate` on the AX-tree button
doesn't fire the underlying `UIAlertAction`. Use Mob `Alert` with
`action:` atoms and `send_message/2` to dismiss programmatically.
See `issues.md` #9.
System-level gestures iOS owns *above* the app process (edge-pan back,
swipe-up app switcher, pull-down notification center) are out of reach
for in-process synthetic touches on physical devices. Use `back/1` for
Mob screens; for sidecar mode against arbitrary apps, document the
limitation rather than promising the gesture.
"""
# ── Inspection ────────────────────────────────────────────────────────────────
@doc "Return the current screen module."
@spec screen(node()) :: module()
def screen(node), do: rpc(node, :get_current_module)
@doc """
Return the current screen's assigns map, or `nil` while that screen is being
restarted after a crash (MOB-112 — the socket lives in the screen's own
process, which is briefly absent).
"""
@spec assigns(node()) :: map() | nil
def assigns(node) do
case rpc(node, :get_socket) do
nil -> nil
socket -> socket.assigns
end
end
@doc """
Return a map with `:screen`, `:assigns`, `:nav_history`, and `:tree`
(the raw render tree from calling `render/1` on the current screen).
"""
@spec inspect(node()) :: map()
def inspect(node), do: rpc(node, :inspect)
@doc "Return the current rendered tree (calls render/1 on the live assigns)."
@spec tree(node()) :: map()
def tree(node), do: rpc(node, :inspect).tree
@doc """
Find all nodes in the current tree whose text contains `substring`.
Returns a list of `{path, node}` tuples where `path` is a list of
indices from the root.
Mob.Test.find(node, "Device APIs")
#=> [{[0, 1, 8], %{"type" => "button", "props" => %{"text" => "Device APIs →", ...}}}]
"""
@spec find(node(), String.t()) :: [{list(), map()}]
def find(node, substring) do
search(tree(node), substring, [])
end
# ── Tap ───────────────────────────────────────────────────────────────────────
@doc """
Send a tap event to the current screen by tag atom.
The tag comes from `on_tap: {self(), :tag_atom}` in the screen's `render/1`.
Check the screen's render function to find available tags.
Fire-and-forget — does not wait for the screen to finish processing. Follow
with `settle/2` before reading the native side.
Mob.Test.tap(node, :save)
Mob.Test.tap(node, :open_detail)
"""
@spec tap(node(), atom()) :: :ok
def tap(node, tag) do
:rpc.call(node, Process, :send, [:mob_screen, {:tap, tag}, []])
:ok
end
@doc """
Block until the app has finished processing and the current frame is on
screen.
Drains the navigation owner and the screen process (twice, since an event
that navigates hands off to a *different* screen), then waits for
`Mob.Sender` to commit. All three are needed: the owner forwards the event,
the screen builds the tree, and the sender commits it — so a drained owner
mailbox alone does not mean the frame has been rendered.
Use after any fire-and-forget call (`tap/2`, `back/1`, `send_message/2`)
before reading the native side with `view_tree/1`, `screenshot/2`, `tap_id/2`
or `element_frames/2`.
Mob.Test.tap(node, :save)
Mob.Test.settle(node)
Mob.Test.view_tree(node)
"""
@spec settle(node(), timeout()) :: :ok
def settle(node, timeout \\ 5000) do
# Since MOB-112 the process registered as :mob_screen is the navigation
# *owner*; it forwards events to the screen, which builds the tree, which
# the sender commits. Draining only the owner proves nothing about the rest.
#
# Twice, because an event that navigates moves through owner -> old screen
# -> owner -> NEW screen. Draining once settles the screen that is on its
# way out and returns before the incoming one has rendered, so a
# tap -> settle -> screenshot would read the stale frame.
drain_owner_and_screen(node)
drain_owner_and_screen(node)
:rpc.call(node, Mob.Sender, :sync, [timeout])
:ok
end
defp drain_owner_and_screen(node) do
:rpc.call(node, :sys, :get_state, [:mob_screen])
case :rpc.call(node, Mob.Screen, :get_screen_pid, [:mob_screen]) do
pid when is_pid(pid) -> :rpc.call(node, :sys, :get_state, [pid])
_ -> :ok
end
end
# ── System gestures ───────────────────────────────────────────────────────────
@doc """
Simulate the system back gesture (Android hardware back / iOS edge-pan).
Fire-and-forget — follow with `settle/2` before reading the native side. The
framework pops the navigation stack; if already at the root, it exits the app. Prefer `pop/1` when you need to know that navigation
has finished before reading state.
"""
@spec back(node()) :: :ok
def back(node) do
:rpc.call(node, Process, :send, [:mob_screen, {:mob, :back}, []])
:ok
end
# ── Navigation (synchronous) ──────────────────────────────────────────────────
@doc """
Pop the current screen and return to the previous one. Synchronous.
Returns `:ok` once the navigation and re-render are complete, so it is safe
to call `screen/1` or `assigns/1` immediately after.
No-op (returns `:ok`) if already at the root of the stack.
"""
@spec pop(node()) :: :ok
def pop(node), do: nav(node, {:pop})
@doc """
Push a new screen onto the navigation stack. Synchronous.
`dest` is a screen module or a registered name atom (from `navigation/1`).
`params` are passed to the new screen's `mount/3`.
Mob.Test.navigate(node, MyApp.DetailScreen, %{id: 42})
Mob.Test.navigate(node, :detail, %{id: 42})
Mob.Test.navigate(node, MyApp.SettingsScreen)
"""
@spec navigate(node(), module() | atom(), map()) :: :ok
def navigate(node, dest, params \\ %{}), do: nav(node, {:push, dest, params})
@doc """
Pop the stack until `dest` is at the top. Synchronous.
`dest` is a screen module or registered name atom. No-op if not in history.
"""
@spec pop_to(node(), module() | atom()) :: :ok
def pop_to(node, dest), do: nav(node, {:pop_to, dest})
@doc """
Pop all screens back to the root of the current stack. Synchronous.
"""
@spec pop_to_root(node()) :: :ok
def pop_to_root(node), do: nav(node, {:pop_to_root})
@doc """
Replace the current navigation stack with a new root screen. Synchronous.
Use this to simulate auth transitions (e.g. login → home with no back button).
Pass `transition: :push` or `transition: :pop` to drive a directional reset,
matching `Mob.Socket.reset_to/4`. Pass `scope: :all` to discard every parked
stack as well as the active one.
"""
@spec reset_to(node(), module() | atom(), map(), [
{:transition, atom()} | {:scope, :stack | :all}
]) :: :ok
def reset_to(node, dest, params \\ %{}, opts \\ []) do
transition = Keyword.get(opts, :transition)
case Keyword.get(opts, :scope, :stack) do
:stack when is_nil(transition) ->
nav(node, {:reset, dest, params})
:stack ->
nav(node, {:reset, dest, params, transition})
:all ->
nav(node, {:reset, dest, params, transition || :reset, :all})
other ->
raise ArgumentError,
"Mob.Test.reset_to/4: invalid scope #{Kernel.inspect(other)}. " <>
"Expected one of [:stack, :all]."
end
end
@doc """
What this node can actually be probed with, right now.
Every helper in this module is a thin `:rpc.call` into `:mob_nif`, and which
of those the app can serve is a runtime fact, not a property of the platform:
* On **Android** each harness NIF checks a cached `MobBridge` method and
returns `{:error, :not_loaded}` when it is absent. `MobBridge.kt` is
app-owned and generated once, so an app built from an older template
silently lacks methods a newer one has.
* On **iOS** the whole harness is compiled out of release builds, leaving
the Erlang stubs behind.
Without this an agent finds out by running the probe and reading an error
mid-investigation, having already committed to an approach.
iex> Mob.Test.capabilities(node)
%{
dist_rpc: true,
view_tree: false,
tap_xy: true,
ax_action: false,
element_frames: true,
screenshot: true,
...
}
`dist_rpc` is `true` whenever the node answered, since that is what answering
proves. When it is unreachable every capability is `false` — including
against an iOS **release** build, which drops `-name` entirely and so has no
distribution to answer over.
A node whose `load_nif` failed reports `dist_rpc: true` with every probe
`false`: it answered, and every NIF really is down.
Two side effects worth knowing. `:mob_nif` is `-on_load`, so calling this on
a node that has not loaded it triggers the code load and the NIF load — in a
booted Mob app it is always loaded already, so this is theory rather than
practice. And the device runs an interactive code server, so probing a module
it has not loaded causes it to load; that makes the answer reflect the code
path rather than the resident set.
An app built before `mob_nif:capabilities/0` existed cannot answer. Rather
than guess from a table that would drift the same way, those report
`:unknown` for each probe with `dist_rpc: true` — the honest answer, and one
a caller can branch on.
"""
@spec capabilities(node(), timeout()) :: %{atom() => boolean() | :unknown}
def capabilities(node, timeout \\ 5_000) do
node
|> :rpc.call(:mob_nif, :capabilities, [], timeout)
|> classify_capabilities()
end
@doc false
# Extracted so the classification is testable without a device — every branch
# below describes a real state an agent hits, and the interesting ones cannot
# be produced from a host test otherwise.
@spec classify_capabilities(term()) :: %{atom() => boolean() | :unknown}
def classify_capabilities(%{} = caps), do: Map.put(caps, :dist_rpc, true)
def classify_capabilities({:badrpc, {:EXIT, {:undef, _}}}),
# The app predates `mob_nif:capabilities/0`. It answered, so dist works;
# what it can serve is genuinely unknown, and guessing from a table is the
# drift this function exists to avoid.
do: Map.put(unknown_probes(), :dist_rpc, true)
def classify_capabilities({:badrpc, {:EXIT, {:not_loaded, _}}}),
# `load_nif` failed on the device, so EVERY NIF is down, not just this one.
# Reporting `:unknown` would send an agent off to try probes that cannot
# work; false is the truth here.
do: unreachable() |> Map.put(:dist_rpc, true)
def classify_capabilities(_unreachable_or_unrecognised), do: unreachable()
@probe_keys [
:view_tree,
:ui_tree,
:screen_info,
:tap_xy,
:tap_by_label,
:long_press_xy,
:swipe_xy,
:type_text,
:delete_backward,
:clear_text,
:ax_action,
:element_frames,
:scroll_info,
:scroll_to,
:sample_region,
:screenshot,
:native_stats
]
@doc false
@spec probe_keys() :: [atom()]
def probe_keys, do: @probe_keys
defp unknown_probes, do: Map.new(@probe_keys, &{&1, :unknown})
defp unreachable,
do: @probe_keys |> Map.new(&{&1, false}) |> Map.put(:dist_rpc, false)
@doc """
Switch to a named tab stack. Synchronous.
Pass `transition: :push`, `transition: :pop`, or `transition: :reset` to
exercise the same directional animation as `Mob.Socket.switch_tab/3`.
`mount_params: %{...}` is passed to a target root only on its first mount.
"""
@spec switch_tab(node(), atom(), [{:transition, atom()} | {:mount_params, map()}]) :: :ok
def switch_tab(node, tab, opts \\ []) do
transition =
case Keyword.fetch(opts, :transition) do
:error -> :none
{:ok, value} -> validate_tab_transition!(value)
end
case Keyword.fetch(opts, :mount_params) do
{:ok, mount_params} when is_map(mount_params) ->
nav(node, {:switch_tab, tab, transition, mount_params})
{:ok, mount_params} ->
raise ArgumentError,
"Mob.Test.switch_tab/3: invalid mount_params #{Kernel.inspect(mount_params)}. " <>
"Expected a map."
:error when transition == :none ->
nav(node, {:switch_tab, tab})
:error ->
nav(node, {:switch_tab, tab, transition})
end
end
defp validate_tab_transition!(transition) when transition in [:push, :pop, :reset],
do: transition
defp validate_tab_transition!(transition) do
raise ArgumentError,
"Mob.Test.switch_tab/3: invalid transition #{Kernel.inspect(transition)}. " <>
"Expected one of [:push, :pop, :reset]."
end
# ── Lists ─────────────────────────────────────────────────────────────────────
@doc """
Select a row in a `:list` component by index.
`list_id` must match the `:id` prop on the `type: :list` node. `index` is
zero-based. Delivers `{:select, list_id, index}` to `handle_info/2`.
Fire-and-forget.
Mob.Test.select(node, :my_list, 0) # first row
"""
@spec select(node(), atom(), non_neg_integer()) :: :ok
def select(node, list_id, index) when is_atom(list_id) and is_integer(index) do
:rpc.call(node, Process, :send, [:mob_screen, {:select, list_id, index}, []])
:ok
end
# ── send_message ──────────────────────────────────────────────────────────────
@doc """
Send an arbitrary message to the screen's `handle_info/2`. Fire-and-forget.
Use this to simulate results from device APIs without triggering real hardware:
# Permissions
Mob.Test.send_message(node, {:permission, :camera, :granted})
Mob.Test.send_message(node, {:permission, :notifications, :denied})
# Camera
Mob.Test.send_message(node, {:camera, :photo, %{path: "/tmp/photo.jpg", width: 1920, height: 1080}})
Mob.Test.send_message(node, {:camera, :cancelled})
# Location
Mob.Test.send_message(node, {:location, %{lat: 43.6532, lon: -79.3832, accuracy: 10.0, altitude: 80.0}})
Mob.Test.send_message(node, {:location, :error, :denied})
# Photos / Files
Mob.Test.send_message(node, {:photos, :picked, [%{path: "/tmp/photo.jpg", width: 800, height: 600}]})
Mob.Test.send_message(node, {:files, :picked, [%{path: "/tmp/doc.pdf", name: "doc.pdf", size: 4096}]})
# Audio / Motion / Scanner
Mob.Test.send_message(node, {:audio, :recorded, %{path: "/tmp/audio.aac", duration: 12}})
Mob.Test.send_message(node, {:motion, %{ax: 0.1, ay: 9.8, az: 0.0, gx: 0.0, gy: 0.0, gz: 0.0}})
Mob.Test.send_message(node, {:scan, :result, %{type: :qr, value: "https://example.com"}})
# Notifications
Mob.Test.send_message(node, {:notification, %{id: "n1", title: "Hi", body: "Hello", data: %{}, source: :push}})
Mob.Test.send_message(node, {:push_token, :ios, "abc123def456"})
# Biometric
Mob.Test.send_message(node, {:biometric, :success})
Mob.Test.send_message(node, {:biometric, :failure, :user_cancel})
# Custom
Mob.Test.send_message(node, {:my_event, %{key: "value"}})
"""
@spec send_message(node(), term()) :: :ok
def send_message(node, message) do
:rpc.call(node, Process, :send, [:mob_screen, message, []])
:ok
end
# ── Native UI — unmodified app test harness ─────────────────────────────────
#
# These functions drive the native UI of any app — not just Mob-rendered ones.
# They call mob_nif directly via RPC and do not require a mob screen process.
@doc """
Return the live accessibility tree from the running native app.
Each element is a tuple: `{type, label, value, {x, y, w, h}}`
Mob.Test.ui_tree(node)
#=> [{:button, "Increment", "", {164.0, 400.0, 54.0, 54.0}}, ...]
"""
@spec ui_tree(node()) :: list()
def ui_tree(node) do
:rpc.call(node, :mob_nif, :ui_tree, [])
end
@doc """
Return the live UI tree as a nested map, walking native views directly.
Unlike `ui_tree/1` (which uses the accessibility subsystem and requires
VoiceOver activation on iOS), this walks UIView/View hierarchies directly:
no AX activation needed.
## Coverage caveat
- **UIKit apps (sidecar mode)**: full UIView hierarchy with labels and frames.
- **SwiftUI apps (current Mob)**: shallow — SwiftUI doesn't expose its content
as separate UIView instances under the hosting view. You'll see containers
and scroll views but not individual buttons/text. For Mob apps, prefer
`Mob.Test.tree/1` (the logical render tree, which has all the semantic info)
or `Mob.Test.ui_tree/1` (AX walk, requires VoiceOver activation).
- **Android (planned)**: a registry populated via `onGloballyPositioned` in
Mob's Compose components — see `future_developments.md` "WireTap" section.
Returns a nested map:
%{
type: :root, class: nil, label: nil, value: nil,
frame: {0.0, 0.0, 393.0, 852.0},
bg_color: nil, text_color: nil,
children: [
%{type: :window, class: "UIWindow", ..., children: [
%{type: :scroll, ..., children: [
%{type: :button, class: "SwiftUI.CGDrawingView", label: "Roll Dice",
frame: {24.0, 416.0, 327.0, 53.5},
bg_color: 0xFF2196F3, text_color: 0xFFFFFFFF, children: []}
]}
]}
]
}
`:class` is the concrete native view class. On SwiftUI it is usually the only
thing that identifies a node — `:type` collapses anything it doesn't recognise
to `:view` — and it's what tells you which renderer drew a node when a colour
comes back `nil`.
## Colours
`:bg_color` and `:text_color` are the colours the view **actually painted**,
as `0xAARRGGBB` integers — the same representation component props use
(`guides/theming.md`). `nil` means nothing paintable was found, or the colour
has no single RGBA value (a multi-stop gradient, a pattern fill).
UIKit puts colour on the view (`UIView.backgroundColor`, `UILabel.textColor`).
**SwiftUI mostly does not** — `.background(Color, in: shape)` and
`.foregroundColor`, which is what Mob's renderer uses for every Box and Text,
go through SwiftUI's own renderer and land on a `CALayer` (typically a
`CAShapeLayer` fill) under a structural view whose own `backgroundColor` stays
`nil`. So each node also harvests from its own layer subtree, excluding layers
owned by its subviews so a container never claims a child's paint.
Sources consulted per node, first match wins:
| | Background | Text |
|---|---|---|
| view | `UIView.backgroundColor` | `UILabel`/`UITextField`/`UITextView`/`UIButton` |
| layer subtree | `CAShapeLayer.fillColor`, single-stop `CAGradientLayer`, `CALayer.backgroundColor` | `CATextLayer.foregroundColor` |
Fully-transparent colours are treated as no colour, so a `Color.clear`
placeholder doesn't read as "painted black at alpha 0".
Because these are read back off `UIView`/`CALayer` rather than echoed from the
render tree, they are the way to catch a styling regression where a theme or
modifier silently drops a colour Elixir sent. Compare against `tree/1` (what
Elixir asked for) to see the two diverge.
**If colours come back `nil` across the board**, don't guess at the reason —
call `paint_debug/1`, which reports which view/layer classes the renderer
produced and which colour properties they actually set. On iOS 26 SwiftUI that
is the expected outcome, and `sample_color/2` (real pixels) is the way to
verify a drawn colour.
On Android, the JSON returned by `mob_nif:ui_view_tree/0` is decoded here.
The `uiViewTree()` it calls lives in the app's generated `MobBridge.kt`:
apps generated by `mob_new` 0.4.33 or newer walk the Mob node tree and
return the same shape iOS does (frames only for nodes with an `:id`);
apps generated earlier return `{:error, :not_loaded}` until the bridge is
regenerated. `capabilities/1` says which you have.
"""
@spec view_tree(node()) :: map() | {:error, term()}
def view_tree(node) do
case :rpc.call(node, :mob_nif, :ui_view_tree, []) do
bin when is_binary(bin) -> bin |> :json.decode() |> normalize_view_tree()
%{} = m -> m
other -> other
end
end
@doc """
Normalize an Android-shaped (JSON-decoded, string-keyed) view tree into the
iOS map shape: atom keys, atom `:type`, `{x, y, w, h}` frame tuple.
`view_tree/1` applies this automatically. It's public so a captured tree can
be normalized without a device.
"""
@spec normalize_view_tree(map() | term()) :: map() | term()
def normalize_view_tree(%{"type" => _} = node) do
%{
type: normalize_atom(node["type"]),
class: denull(node["class"]),
label: denull(node["label"]),
value: denull(node["value"]),
frame:
case node["frame"] do
[x, y, w, h] -> {x * 1.0, y * 1.0, w * 1.0, h * 1.0}
other -> denull(other)
end,
bg_color: denull(node["bg_color"]),
text_color: denull(node["text_color"]),
children: Enum.map(denull(node["children"]) || [], &normalize_view_tree/1)
}
end
def normalize_view_tree(other), do: other
# `:json.decode/1` maps JSON null to the atom :null. Left as-is it leaks into
# every comparison against nil, and `:null || []` is truthy, so an absent
# children list would crash Enum.map.
defp denull(:null), do: nil
defp denull(other), do: other
defp normalize_atom(s) when is_binary(s), do: String.to_atom(s)
defp normalize_atom(a) when is_atom(a), do: a
@doc """
Census of where colour lives in the native view tree — the diagnostic to reach
for when `view_tree/1` reports `nil` colours and you need to know why.
Groups every native view by `(view class, layer class, sublayer classes)` and
reports, per group, how many views set each colour-bearing property:
Mob.Test.paint_debug(node)
#=> %{
# "total_views" => 443,
# "groups" => [
# %{"view" => "SwiftUI.CGDrawingView", "layer" => "SwiftUI.CGDrawingLayer",
# "sublayers" => ["CAShapeLayer"], "count" => 40,
# "view_bg" => 0, "layer_bg" => 0, "shape_fill" => 40,
# "gradient" => 0, "text_layer_fg" => 0, "uikit_text" => 0,
# "has_contents" => 40},
# ...
# ]
# }
Read a row as: for these 40 views the only colour set is
`CAShapeLayer.fillColor`, so that is the property the extractor has to read.
A group where every tally is 0 but `has_contents` is high is a view that drew
itself into a bitmap — its colour is not recoverable without pixel sampling.
iOS only, debug builds only. Android raises `:nif_error`.
"""
@spec paint_debug(node()) :: map() | {:error, term()}
def paint_debug(node) do
case :rpc.call(node, :mob_nif, :ui_paint_debug, []) do
bin when is_binary(bin) -> :json.decode(bin)
other -> other
end
end
@doc """
Tally of the distinct painted colours in a view tree — the cheap way to assert
a styling change actually reached the screen.
Pass a node to fetch the tree, or an already-fetched tree to work offline.
Returns `%{background: %{argb => count}, text: %{argb => count}}`, `nil`
colours excluded.
Mob.Test.color_census(node)
#=> %{background: %{0xFF2196F3 => 4, 0xFF1E1E1E => 1}, text: %{0xFFFFFFFF => 9}}
A theme regression that discards backgrounds shows up as an empty (or
collapsed) `:background` map, and two themes that should differ produce
different key sets.
"""
@spec color_census(node() | map()) :: %{background: map(), text: map()}
def color_census(node) when is_atom(node), do: color_census(view_tree(node))
def color_census(%{} = tree) do
tree
|> flatten_tree()
|> Enum.reduce(%{background: %{}, text: %{}}, fn {_path, n}, acc ->
acc
|> tally(:background, n[:bg_color])
|> tally(:text, n[:text_color])
end)
end
defp tally(acc, _key, nil), do: acc
defp tally(acc, key, color) do
Map.update!(acc, key, &Map.update(&1, color, 1, fn n -> n + 1 end))
end
@doc """
Return the view tree flattened to a list of `{path, node}` tuples.
`path` is the list of child indices from the root — e.g. `[0, 2, 1]` is
"the second child of the third child of the first child of the root."
Useful for filter/find — see `find_view/2`.
Mob.Test.view_tree_flat(node)
#=> [
# {[], %{type: :root, ...}},
# {[0], %{type: :window, ...}},
# {[0, 0], %{type: :scroll, ...}},
# ...
# ]
"""
@spec view_tree_flat(node()) :: [{[non_neg_integer()], map()}]
def view_tree_flat(node) when is_atom(node), do: flatten_tree(view_tree(node))
@doc """
Flatten an already-fetched view tree. Pure function — useful for tests
and for inspecting a captured tree without re-fetching.
tree = Mob.Test.view_tree(node)
flat = Mob.Test.flatten_tree(tree)
"""
@spec flatten_tree(map()) :: [{[non_neg_integer()], map()}]
def flatten_tree(%{} = tree), do: do_flatten(tree, []) |> Enum.reverse()
def flatten_tree(other), do: other
defp do_flatten(%{children: children} = node, path) do
self_entry = [{path, Map.delete(node, :children)}]
children
|> Enum.with_index()
|> Enum.reduce(self_entry, fn {child, i}, acc ->
do_flatten(child, path ++ [i]) ++ acc
end)
end
defp do_flatten(other, path), do: [{path, other}]
@doc """
Find nodes in the view tree whose label or value contains `text`.
Returns `[{path, node}]` for each match. Faster and more accurate than
`find_native/2` (no AX dependency, sees all views).
Mob.Test.find_view(node, "Roll Dice")
#=> [{[0, 0, 0, 4], %{type: :button, label: "Roll Dice", ...}}]
"""
@spec find_view(node(), String.t()) :: [{[non_neg_integer()], map()}]
def find_view(node, text) do
node
|> view_tree_flat()
|> Enum.filter(fn {_path, %{} = n} ->
String.contains?(to_string(n[:label] || ""), text) or
String.contains?(to_string(n[:value] || ""), text)
end)
end
@doc """
Invoke an accessibility action on the first AX element matching `match`.
## Platform support
- **iOS**: works once AX is active (today: VoiceOver on; future:
`XCAXClient_iOS` activation, see `future_developments.md`).
- **Android**: returns `{:error, :not_supported_on_android}`. The Compose
semantics walker is queued under WireTap (issues.md #11).
Used for controls where synthetic touches don't reach the gesture recognizer
(sliders, scrolls, modal dismissal).
`match` is a string searched in both label and value. `action` is one of:
`:increment`, `:decrement`, `:activate`, `:escape`, `:scroll_up`,
`:scroll_down`, `:scroll_left`, `:scroll_right`.
Mob.Test.ax_action(node, "Volume", :decrement)
Mob.Test.ax_action(node, "Cancel", :activate)
"""
@spec ax_action(node(), String.t(), atom()) :: :ok | {:error, atom()}
def ax_action(node, match, action) do
:rpc.call(node, :mob_nif, :ax_action, [match, action])
end
@doc """
Invoke an AX action on whatever element occupies the given screen coordinates.
Useful when label/value substring matching is ambiguous (e.g. multiple
sliders that all read "50%", a toggle whose accessibility label is empty).
Caller picks coordinates from `ui_tree/1` and points at the exact element.
Mob.Test.ax_action_at_xy(node, 187.0, 296.0, :increment)
## Platform support
- **iOS**: works once AX is active (VoiceOver on, today).
- **Android**: returns `{:error, :not_supported_on_android}` — see
`ax_action/3`.
"""
@spec ax_action_at_xy(node(), number(), number(), atom()) :: :ok | {:error, atom()}
def ax_action_at_xy(node, x, y, action) do
:rpc.call(node, :mob_nif, :ax_action_at_xy, [x * 1.0, y * 1.0, action])
end
@doc """
Toggle a switch by a label substring. SwiftUI exposes `Toggle` as a button
with an empty accessibility label and value `"0"` or `"1"` — so we find the
Text element matching `label_match`, then activate the next button below it.
Mob.Test.toggle(node, "Notifications")
## Known limitation (issues.md #8)
Mob's iOS Toggle component does not currently surface its `label:` prop as
a separate `:text` AX element, so `find_label_y/2` returns
`{:error, :label_not_found}`. Workaround: use `ax_action_at_xy/4` directly
with the toggle's frame from `ui_tree/1` (filter for `:button` with value
`"0"` or `"1"`). Once issue #8 lands, this helper works as documented.
"""
@spec toggle(node(), String.t()) :: :ok | {:error, atom()}
def toggle(node, label_match) do
with {:ok, label_y} <- find_label_y(node, label_match),
{:ok, {x, y, w, h}} <-
find_actionable_below(node, label_y, fn {_t, l, v, _f} ->
is_binary(v) and v in ["0", "1"] and to_string(l) == ""
end) do
ax_action_at_xy(node, x + w / 2, y + h / 2, :activate)