computer-use-linux 0.7.24

Native Linux desktop control over MCP and CLI — semantic AT-SPI accessibility trees, multi-compositor window targeting (GNOME, KDE/KWin, Hyprland, niri, COSMIC, i3, X11), bounded screenshots, Wayland/X11 input, and an on-screen agent activity indicator.
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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
use crate::diagnostics::hydrate_session_bus_env;
use anyhow::{anyhow, Context, Result};
use atspi::{
    proxy::{
        accessible::{AccessibleProxy, ObjectRefExt},
        action::ActionProxy,
        editable_text::EditableTextProxy,
        proxy_ext::{Proxies, ProxyExt},
        text::TextProxy,
    },
    CoordType, ObjectRef, ObjectRefOwned, StateSet,
};
// Direct dependency (p2p feature off) — see Cargo.toml for why we bypass
// atspi's "connection" re-export.
use atspi_connection::AccessibilityConnection;
use futures_util::{stream, StreamExt};
use schemars::JsonSchema;
use serde::Serialize;
use std::{collections::VecDeque, future::Future, time::Duration};
use tokio::time::{sleep_until, timeout, timeout_at, Instant};
use zbus::{
    fdo::DBusProxy,
    names::{BusName, UniqueName},
    zvariant::{ObjectPath, OwnedObjectPath},
};

#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct AccessibleAppSummary {
    pub object_ref: String,
    pub name: Option<String>,
    pub pid: Option<u32>,
    pub role: String,
    pub child_count: i32,
    pub bounds: Option<Bounds>,
}

#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct AccessibilityNode {
    pub index: u32,
    pub parent_index: Option<u32>,
    pub depth: u32,
    pub object_ref: String,
    pub role: String,
    pub name: Option<String>,
    pub description: Option<String>,
    pub child_count: i32,
    pub bounds: Option<Bounds>,
    pub states: Vec<String>,
    pub actions: Vec<AccessibilityAction>,
    pub value: Option<AccessibilityValue>,
    pub text: Option<AccessibilityText>,
    pub supports_editable_text: bool,
}

#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct Bounds {
    pub x: i32,
    pub y: i32,
    pub width: i32,
    pub height: i32,
}

#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct AccessibilityAction {
    pub index: i32,
    pub name: String,
    pub description: String,
    pub keybinding: String,
}

#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct AccessibilityValue {
    pub current: f64,
    pub minimum: f64,
    pub maximum: f64,
    pub minimum_increment: f64,
    pub text: Option<String>,
}

#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct AccessibilityText {
    pub character_count: i32,
    pub caret_offset: Option<i32>,
    pub content: Option<String>,
    pub truncated: bool,
    pub selections: Vec<AccessibilityTextSelection>,
}

#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct AccessibilityTextSelection {
    pub start_offset: i32,
    pub end_offset: i32,
}

#[derive(Debug, Clone)]
pub struct ActionInvocation {
    pub action_index: i32,
    pub action_name: Option<String>,
    pub ok: bool,
}

#[derive(Debug, Clone)]
pub enum ValueSetInvocation {
    Numeric { value: f64 },
    EditableText { outcome: EditableTextSetOutcome },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EditableTextSetOutcome {
    Verified,
    MismatchAfterDeadline,
    ReadbackFailed,
    ReadbackTimedOut,
    PasswordUnverifiable,
}

const MAX_TEXT_READBACK_CHARS: i32 = 4096;
const EDITABLE_TEXT_READ_CHUNK_UNITS: usize = 4096;
const EDITABLE_TEXT_VERIFY_TIMEOUT: Duration = Duration::from_secs(1);
const EDITABLE_TEXT_VERIFY_INTERVAL: Duration = Duration::from_millis(50);
const MAX_TEXT_SELECTIONS: i32 = 8;
const DEFAULT_SNAPSHOT_MAX_NODES: usize = 1_000;
const HARD_SNAPSHOT_MAX_NODES: usize = 2_000;
const DEFAULT_SNAPSHOT_MAX_DEPTH: u32 = 32;
const HARD_SNAPSHOT_MAX_DEPTH: u32 = 64;
const CHILD_READ_CONCURRENCY: usize = 16;
const SNAPSHOT_TIMEOUT: Duration = Duration::from_secs(10);
const MAX_ACTIONS_PER_OBJECT: i32 = 64;
const ACTION_QUERY_TIMEOUT: Duration = Duration::from_secs(5);
const MAX_DISCOVERY_ROOTS: usize = 256;
const ROOT_MATCH_CHILD_LIMIT: usize = 8;
const MAX_DISCOVERY_CHILD_READS: usize = MAX_DISCOVERY_ROOTS * ROOT_MATCH_CHILD_LIMIT;

fn snapshot_child_read_budgets(max_nodes: usize) -> (usize, usize, usize) {
    (MAX_DISCOVERY_ROOTS, MAX_DISCOVERY_CHILD_READS, max_nodes)
}

pub(crate) fn snapshot_limits(
    requested_max_nodes: Option<usize>,
    requested_max_depth: Option<u32>,
) -> (usize, u32) {
    (
        requested_max_nodes
            .unwrap_or(DEFAULT_SNAPSHOT_MAX_NODES)
            .clamp(1, HARD_SNAPSHOT_MAX_NODES),
        requested_max_depth
            .unwrap_or(DEFAULT_SNAPSHOT_MAX_DEPTH)
            .min(HARD_SNAPSHOT_MAX_DEPTH),
    )
}

struct BoundedTraversal<T> {
    queue: VecDeque<T>,
    attempted: usize,
    max_items: usize,
    /// Set once an enqueue had to drop offered items for lack of capacity.
    dropped: bool,
}

impl<T> BoundedTraversal<T> {
    fn new(max_items: usize) -> Self {
        Self {
            queue: VecDeque::new(),
            attempted: 0,
            max_items,
            dropped: false,
        }
    }

    fn enqueue(&mut self, items: impl IntoIterator<Item = T>) {
        let capacity = self.remaining_capacity();
        let mut items = items.into_iter();
        self.queue.extend(items.by_ref().take(capacity));
        if items.next().is_some() {
            self.dropped = true;
        }
    }

    fn pop(&mut self) -> Option<T> {
        if self.attempted >= self.max_items {
            return None;
        }
        let item = self.queue.pop_front()?;
        self.attempted += 1;
        Some(item)
    }

    fn remaining_capacity(&self) -> usize {
        self.max_items
            .saturating_sub(self.attempted.saturating_add(self.queue.len()))
    }

    /// True when the budget stopped work that was actually offered. `enqueue`
    /// is the only gate: it never exceeds `remaining_capacity`, so
    /// `attempted + queue.len() <= max_items` always holds and the queue can
    /// never be non-empty at the attempt cap. Dropped items are the whole story.
    fn truncated(&self) -> bool {
        self.dropped
    }
}

fn bounded_child_count(reported: i32, limit: usize) -> usize {
    usize::try_from(reported).unwrap_or_default().min(limit)
}

struct IndexedReadBatch<T> {
    items: Vec<T>,
    attempted: usize,
    /// True when fewer children were attempted than the parent reported, because
    /// the caller's limit or the shared read budget ran out. Failed reads do not
    /// count; they were attempted.
    incomplete: bool,
}

impl<T> IndexedReadBatch<T> {
    fn all_failed(&self) -> bool {
        self.attempted > 0 && self.items.is_empty()
    }
}

async fn fetch_indexed_up_to<T, E, F, Fut>(
    reported: i32,
    limit: usize,
    remaining_attempts: &mut usize,
    fetch: F,
) -> IndexedReadBatch<T>
where
    F: Fn(i32) -> Fut,
    Fut: Future<Output = std::result::Result<T, E>>,
{
    let attempt_count = bounded_child_count(reported, limit).min(*remaining_attempts);
    *remaining_attempts = (*remaining_attempts).saturating_sub(attempt_count);
    let end_index = i32::try_from(attempt_count).unwrap_or(i32::MAX);

    let items = stream::iter(0..end_index)
        .map(fetch)
        .buffered(CHILD_READ_CONCURRENCY)
        .filter_map(|result| async move { result.ok() })
        .collect()
        .await;

    IndexedReadBatch {
        items,
        attempted: attempt_count,
        incomplete: attempt_count < usize::try_from(reported).unwrap_or_default(),
    }
}

async fn children_up_to(
    proxy: &AccessibleProxy<'_>,
    limit: usize,
    remaining_attempts: &mut usize,
) -> zbus::Result<IndexedReadBatch<ObjectRefOwned>> {
    if limit == 0 || *remaining_attempts == 0 {
        // Budget already spent: stay I/O-free. `incomplete` is false here because
        // nothing was asked of the parent; callers that already hold the node's
        // child_count (snapshot_tree_inner) derive truncation from that instead.
        return Ok(IndexedReadBatch {
            items: Vec::new(),
            attempted: 0,
            incomplete: false,
        });
    }

    let child_count = proxy.child_count().await?;
    Ok(
        fetch_indexed_up_to(child_count, limit, remaining_attempts, |index| {
            child_at_index(proxy, index)
        })
        .await,
    )
}

async fn child_at_index(proxy: &AccessibleProxy<'_>, index: i32) -> zbus::Result<ObjectRefOwned> {
    // WebKit sockets return a well-known bus name. atspi's ObjectRef decoder
    // only accepts unique names, so resolve the wire reference before using it.
    let (name, path): (String, OwnedObjectPath) =
        proxy.inner().call("GetChildAtIndex", &(index,)).await?;
    if path.as_str() == "/org/a11y/atspi/null" {
        return Ok(ObjectRef::Null.into());
    }
    match BusName::try_from(name)? {
        BusName::Unique(name) => Ok(ObjectRef::new_owned(name, path)),
        name => {
            let owner = DBusProxy::new(proxy.inner().connection())
                .await?
                .get_name_owner(name)
                .await?;
            Ok(ObjectRef::new_owned(owner, path))
        }
    }
}

pub async fn list_accessible_apps(limit: usize) -> Result<Vec<AccessibleAppSummary>> {
    let conn = connect().await?;
    let mut remaining_child_reads = limit;
    let roots = registry_children(&conn, limit, &mut remaining_child_reads).await?;
    let dbus = DBusProxy::new(conn.connection()).await.ok();
    let mut apps = Vec::new();

    for object_ref in roots.into_iter().take(limit) {
        if let Ok(proxy) = open_accessible(&conn, &object_ref).await {
            apps.push(read_app_summary(&proxy, &object_ref, dbus.as_ref()).await);
        }
    }

    Ok(apps)
}

#[derive(Debug, Clone)]
pub(crate) struct AccessibilitySnapshot {
    pub nodes: Vec<AccessibilityNode>,
    /// True when registry roots were filtered to an app name and/or pid.
    pub scoped: bool,
    /// The pid every root belongs to, when roots were matched by pid. None
    /// when they were matched by app name alone or not filtered at all: those
    /// roots can belong to any app, so no single pid describes the tree.
    pub root_pid: Option<u32>,
    /// True when selected roots satisfy the supplied app/name filter, or no
    /// filter was supplied. Normal snapshots retain their PID-only fallback;
    /// action recovery requires this evidence before invoking a fresh node.
    pub app_filter_matched: bool,
    /// True when max_nodes, max_depth, or the child read budget stopped
    /// traversal with unread elements left. Failed element reads do not count.
    pub truncated: bool,
}

pub async fn snapshot_tree(
    app_name_or_bundle_identifier: Option<&str>,
    target_pid: Option<u32>,
    max_nodes: usize,
    max_depth: u32,
) -> Result<Vec<AccessibilityNode>> {
    Ok(snapshot_accessibility_tree(
        app_name_or_bundle_identifier,
        target_pid,
        max_nodes,
        max_depth,
    )
    .await?
    .nodes)
}

pub(crate) async fn snapshot_accessibility_tree(
    app_name_or_bundle_identifier: Option<&str>,
    target_pid: Option<u32>,
    max_nodes: usize,
    max_depth: u32,
) -> Result<AccessibilitySnapshot> {
    let (max_nodes, max_depth) = snapshot_limits(Some(max_nodes), Some(max_depth));
    timeout(
        SNAPSHOT_TIMEOUT,
        snapshot_tree_inner(
            app_name_or_bundle_identifier,
            target_pid,
            max_nodes,
            max_depth,
        ),
    )
    .await
    .context("AT-SPI snapshot exceeded its 10-second deadline")?
}

async fn snapshot_tree_inner(
    app_name_or_bundle_identifier: Option<&str>,
    target_pid: Option<u32>,
    max_nodes: usize,
    max_depth: u32,
) -> Result<AccessibilitySnapshot> {
    let conn = connect().await?;
    // App discovery is bounded independently so a tiny requested tree still
    // finds a target registered after the first accessibility root.
    let (mut remaining_registry_reads, mut remaining_filter_reads, mut remaining_traversal_reads) =
        snapshot_child_read_budgets(max_nodes);
    let roots =
        registry_children(&conn, MAX_DISCOVERY_ROOTS, &mut remaining_registry_reads).await?;
    let selected_roots = select_roots(
        &conn,
        roots,
        app_name_or_bundle_identifier,
        target_pid,
        &mut remaining_filter_reads,
    )
    .await;
    let scoped = selected_roots.scoped;
    let root_pid = selected_roots.pid;
    let app_filter_matched = selected_roots.app_filter_matched;
    let mut nodes = Vec::new();
    let mut truncated = false;
    let mut traversal = BoundedTraversal::new(max_nodes);

    traversal.enqueue(
        selected_roots
            .roots
            .into_iter()
            .map(|object_ref| (object_ref, 0_u32, None)),
    );

    while let Some((object_ref, depth, parent_index)) = traversal.pop() {
        let Ok(proxy) = open_accessible(&conn, &object_ref).await else {
            continue;
        };
        let index = nodes.len() as u32;
        let remaining = traversal.remaining_capacity();
        let node = read_node(&proxy, &object_ref, index, parent_index, depth).await;
        let child_refs = if depth < max_depth && remaining > 0 {
            match children_up_to(&proxy, remaining, &mut remaining_traversal_reads).await {
                Ok(batch) => {
                    // A read-budget cut inside the fetch reports `incomplete`; an
                    // already-exhausted budget returns the I/O-free empty batch, so
                    // fall back to the child_count read_node already fetched.
                    truncated |= batch.incomplete || (batch.attempted == 0 && node.child_count > 0);
                    batch.items
                }
                Err(_) => Vec::new(),
            }
        } else {
            // Depth or node cap reached: any child this node reports is unread.
            truncated |= node.child_count > 0;
            Vec::new()
        };

        nodes.push(node);

        traversal.enqueue(
            child_refs
                .into_iter()
                .map(|child| (child, depth + 1, Some(index))),
        );
    }
    truncated |= traversal.truncated();

    Ok(AccessibilitySnapshot {
        nodes,
        scoped,
        root_pid,
        app_filter_matched,
        truncated,
    })
}

/// Compact description of the AT-SPI element that currently holds keyboard
/// focus, used as post-input feedback for type_text/press_key.
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct FocusedElementSummary {
    pub role: String,
    pub name: Option<String>,
    pub editable: bool,
    pub states: Vec<String>,
    /// AT-SPI `Role::Terminal`, read from the role enum rather than the
    /// localized role name. Internal routing only; not part of the output.
    #[serde(skip)]
    #[schemars(skip)]
    pub is_terminal: bool,
}

const FOCUS_PROBE_MAX_NODES: usize = 400;
const FOCUS_PROBE_MAX_DEPTH: u32 = 16;

/// Find the element with the `focused` state inside the target app (by pid) or
/// across all apps. Best-effort and bounded: returns Ok(None) when no focused
/// element is reachable through AT-SPI (common for apps without accessibility
/// support, e.g. Electron without --force-renderer-accessibility).
/// Outcome of the bounded focused-element search.
#[derive(Debug, Clone)]
pub(crate) enum FocusProbe {
    Found(FocusedElementSummary),
    /// The search covered the target's whole tree and nothing holds focus.
    NoneFocused,
    /// A complete scoped search saw only window/menu chrome, no content.
    ShellOnly,
    /// A node, depth, or read limit stopped the search before it finished, so
    /// the focused element may exist past the limit.
    Incomplete,
    /// A pid was given but no AT-SPI app belongs to it (xterm, or Electron
    /// without --force-renderer-accessibility), so focus cannot be read.
    NoAccessibleApp,
}

/// Focused element in the app owning `target_pid`, or across all apps when no
/// pid is given. With a pid, only that app's tree is searched: falling back to
/// every other app would report some unrelated widget as the focus.
pub(crate) async fn probe_focused_element(target_pid: Option<u32>) -> Result<FocusProbe> {
    focused_element_probe(target_pid, target_pid.is_some()).await
}

/// The focused element in the app that owns `target_pid`, for callers that
/// only need an answer when one exists. Every non-`Found` probe result maps to
/// `None`; see [`probe_focused_element`] for the distinctions.
pub(crate) async fn focused_element_summary_in_app(
    target_pid: u32,
) -> Result<Option<FocusedElementSummary>> {
    Ok(match focused_element_probe(Some(target_pid), true).await? {
        FocusProbe::Found(summary) => Some(summary),
        _ => None,
    })
}

async fn focused_element_probe(
    target_pid: Option<u32>,
    require_scoped: bool,
) -> Result<FocusProbe> {
    let conn = connect().await?;
    let mut remaining_registry_reads = MAX_DISCOVERY_ROOTS;
    let roots =
        registry_children(&conn, MAX_DISCOVERY_ROOTS, &mut remaining_registry_reads).await?;
    let mut remaining_filter_reads = MAX_DISCOVERY_CHILD_READS;
    let selected_roots =
        select_roots(&conn, roots, None, target_pid, &mut remaining_filter_reads).await;
    if require_scoped && !selected_roots.scoped {
        return Ok(FocusProbe::NoAccessibleApp);
    }
    let mut traversal = BoundedTraversal::new(FOCUS_PROBE_MAX_NODES);
    let mut remaining_traversal_reads = FOCUS_PROBE_MAX_NODES;
    let mut incomplete = false;
    let mut shell_only = true;
    let mut observed_nodes = 0;

    traversal.enqueue(
        selected_roots
            .roots
            .into_iter()
            .map(|object_ref| (object_ref, 0_u32, false)),
    );

    while let Some((object_ref, depth, in_menu)) = traversal.pop() {
        let Ok(proxy) = open_accessible(&conn, &object_ref).await else {
            incomplete = true;
            continue;
        };
        let Ok(state) = proxy.get_state().await else {
            incomplete = true;
            continue;
        };
        observed_nodes += 1;
        let mut child_menu = false;
        if shell_only {
            match accessibility_chrome_context(&role_name(&proxy).await, in_menu) {
                Some(menu) => child_menu = menu,
                None => shell_only = false,
            }
        }
        if state.contains(atspi::State::Focused) {
            let proxies = proxy.proxies().await.ok();
            let is_terminal = matches!(proxy.get_role().await, Ok(atspi::Role::Terminal));
            return Ok(FocusProbe::Found(FocusedElementSummary {
                role: role_name(&proxy).await,
                name: optional_string(proxy.name().await.ok()),
                editable: supports_editable_text(proxies.as_ref()).await,
                states: state_labels(state),
                is_terminal,
            }));
        }
        let remaining = traversal.remaining_capacity();
        if depth < FOCUS_PROBE_MAX_DEPTH && remaining > 0 {
            if let Ok(batch) =
                children_up_to(&proxy, remaining, &mut remaining_traversal_reads).await
            {
                incomplete |= batch.incomplete;
                // An exhausted shared read budget takes children_up_to's
                // I/O-free path (attempted 0, incomplete false), so the node's
                // own child count has to say whether children went unread.
                // With budget left, attempted 0 just means a leaf: no read.
                if batch.attempted == 0 && remaining_traversal_reads == 0 && !incomplete {
                    incomplete = proxy.child_count().await.map_or(true, |count| count > 0);
                }
                traversal.enqueue(
                    batch
                        .items
                        .into_iter()
                        .map(|child| (child, depth + 1, child_menu)),
                );
            } else {
                incomplete = true;
            }
        } else if !incomplete {
            // Depth or node cap: any child this node reports goes unread. One
            // child-count read settles it, and only until the first cut is seen.
            incomplete = proxy.child_count().await.map_or(true, |count| count > 0);
        }
    }
    if incomplete || traversal.truncated() {
        return Ok(FocusProbe::Incomplete);
    }

    Ok(if require_scoped && shell_only && observed_nodes > 0 {
        FocusProbe::ShellOnly
    } else {
        FocusProbe::NoneFocused
    })
}

/// Window and native menu chrome can exist without Electron renderer content.
/// This is evidence about tree coverage, not positive Electron detection.
pub(crate) fn accessibility_chrome_context(role: &str, in_menu: bool) -> Option<bool> {
    match role {
        "application" | "frame" | "window" | "panel" | "filler" | "separator" => Some(in_menu),
        "menu bar" | "menu" | "menu item" | "check menu item" | "radio menu item"
        | "tearoff menu item" => Some(true),
        // Electron's native menu buttons are exposed as buttons, not menu items.
        "button" | "push button" | "label" | "static" | "image" | "icon" if in_menu => Some(true),
        _ => None,
    }
}

pub async fn perform_action(
    object_ref_id: &str,
    requested_action: Option<&str>,
) -> Result<ActionInvocation> {
    perform_action_inner(object_ref_id, requested_action, false).await
}

pub(crate) async fn perform_named_action(
    object_ref_id: &str,
    name: &str,
) -> Result<ActionInvocation> {
    perform_action_inner(object_ref_id, Some(name), true).await
}

async fn perform_action_inner(
    object_ref_id: &str,
    requested_action: Option<&str>,
    name_only: bool,
) -> Result<ActionInvocation> {
    let object_ref = object_ref_from_id(object_ref_id)?;
    let (action, action_index, action_name) = timeout(ACTION_QUERY_TIMEOUT, async {
        let conn = connect().await?;
        let proxy = open_accessible(&conn, &object_ref)
            .await
            .with_context(|| format!("failed to open AT-SPI object {object_ref_id}"))?;
        let action = proxy
            .proxies()
            .await?
            .action()
            .await
            .context("element does not expose the AT-SPI Action interface")?;
        let actions = read_actions(&action).await?;
        let action_index = if name_only {
            select_named_action_index(&actions, requested_action.unwrap_or_default())?
        } else {
            select_action_index(&actions, requested_action)?
        };
        let action_name = actions
            .get(action_index as usize)
            .map(|action| action.name.clone());
        Ok::<_, anyhow::Error>((action, action_index, action_name))
    })
    .await
    .context("AT-SPI action revalidation exceeded its 5-second deadline")??;
    // Only time out the reads: once DoAction is sent, it may already have acted.
    let ok = action
        .do_action(action_index)
        .await
        .with_context(|| format!("failed to invoke AT-SPI action {action_index}"))?;

    Ok(ActionInvocation {
        action_index,
        action_name,
        ok,
    })
}

pub async fn set_element_value(object_ref_id: &str, value: &str) -> Result<ValueSetInvocation> {
    let conn = connect().await?;
    let object_ref = object_ref_from_id(object_ref_id)?;
    let proxy = open_accessible(&conn, &object_ref)
        .await
        .with_context(|| format!("failed to open AT-SPI object {object_ref_id}"))?;
    let proxies = proxy.proxies().await?;
    set_element_value_with_proxies(&proxy, &proxies, value).await
}

async fn set_element_value_with_proxies(
    proxy: &AccessibleProxy<'_>,
    proxies: &Proxies<'_>,
    value: &str,
) -> Result<ValueSetInvocation> {
    if let Ok(numeric_value) = value.parse::<f64>() {
        if let Ok(value_proxy) = proxies.value().await {
            value_proxy
                .set_current_value(numeric_value)
                .await
                .with_context(|| {
                    format!("failed to set AT-SPI numeric value to {numeric_value}")
                })?;
            return Ok(ValueSetInvocation::Numeric {
                value: numeric_value,
            });
        }
    }

    if let Ok(editable_text) = proxies.editable_text().await {
        return set_editable_text_contents(proxy, proxies, &editable_text, value).await;
    }

    if value.parse::<f64>().is_err() && proxies.value().await.is_ok() {
        return Err(anyhow!(
            "element exposes the AT-SPI Value interface, but the requested value is not numeric"
        ));
    }

    Err(anyhow!(
        "element does not expose AT-SPI Value or EditableText interfaces"
    ))
}

async fn set_editable_text_contents(
    proxy: &AccessibleProxy<'_>,
    proxies: &Proxies<'_>,
    editable_text: &EditableTextProxy<'_>,
    value: &str,
) -> Result<ValueSetInvocation> {
    let ok = editable_text
        .set_text_contents(value)
        .await
        .context("failed to set AT-SPI editable text contents")?;
    if !ok {
        return Err(anyhow!("AT-SPI EditableText rejected the new contents"));
    }

    let outcome = verify_editable_text_contents(proxy, proxies, value).await;
    Ok(ValueSetInvocation::EditableText { outcome })
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EditableTextReadbackError {
    Failed,
    TimedOut,
}

async fn readback_within<T, E>(
    deadline: Instant,
    read: impl Future<Output = std::result::Result<T, E>>,
) -> std::result::Result<T, EditableTextReadbackError> {
    timeout_at(deadline, read)
        .await
        .map_err(|_| EditableTextReadbackError::TimedOut)?
        .map_err(|_| EditableTextReadbackError::Failed)
}

async fn text_readback_matches(
    text: &TextProxy<'_>,
    requested: &str,
    deadline: Instant,
) -> std::result::Result<bool, EditableTextReadbackError> {
    let character_count = readback_within(deadline, text.character_count()).await?;
    if character_count < 0 {
        return Err(EditableTextReadbackError::Failed);
    }
    if character_count as usize == requested.chars().count() {
        return unicode_scalar_text_readback_matches(text, requested, deadline).await;
    }

    let requested_utf16 = requested.encode_utf16().collect::<Vec<_>>();
    if character_count as usize != requested_utf16.len() {
        return Ok(false);
    }
    utf16_text_readback_matches(text, &requested_utf16, deadline).await
}

async fn unicode_scalar_text_readback_matches(
    text: &TextProxy<'_>,
    requested: &str,
    deadline: Instant,
) -> std::result::Result<bool, EditableTextReadbackError> {
    let requested_chars = requested.chars().collect::<Vec<_>>();
    let mut offset = 0;
    while offset < requested_chars.len() {
        let end = offset
            .saturating_add(EDITABLE_TEXT_READ_CHUNK_UNITS)
            .min(requested_chars.len());
        let chunk = readback_within(deadline, text.get_text(offset as i32, end as i32)).await?;
        if !chunk
            .chars()
            .eq(requested_chars[offset..end].iter().copied())
        {
            return Ok(false);
        }
        offset = end;
    }

    Ok(true)
}

async fn utf16_text_readback_matches(
    text: &TextProxy<'_>,
    requested: &[u16],
    deadline: Instant,
) -> std::result::Result<bool, EditableTextReadbackError> {
    let mut offset = 0;
    while offset < requested.len() {
        let mut end = offset
            .saturating_add(EDITABLE_TEXT_READ_CHUNK_UNITS)
            .min(requested.len());
        if end < requested.len() && (0xD800..=0xDBFF).contains(&requested[end - 1]) {
            end -= 1;
        }
        let chunk = readback_within(deadline, text.get_text(offset as i32, end as i32)).await?;
        if !chunk
            .encode_utf16()
            .eq(requested[offset..end].iter().copied())
        {
            return Ok(false);
        }
        offset = end;
    }

    Ok(true)
}

async fn verify_editable_text_contents(
    proxy: &AccessibleProxy<'_>,
    proxies: &Proxies<'_>,
    requested: &str,
) -> EditableTextSetOutcome {
    let deadline = Instant::now() + EDITABLE_TEXT_VERIFY_TIMEOUT;
    match readback_within(deadline, proxy.get_role()).await {
        Ok(atspi::Role::PasswordText) => return EditableTextSetOutcome::PasswordUnverifiable,
        Ok(_) => {}
        Err(EditableTextReadbackError::Failed) => {
            return EditableTextSetOutcome::ReadbackFailed;
        }
        Err(EditableTextReadbackError::TimedOut) => {
            return EditableTextSetOutcome::ReadbackTimedOut;
        }
    }
    let text = match readback_within(deadline, proxies.text()).await {
        Ok(text) => text,
        Err(EditableTextReadbackError::Failed) => {
            return EditableTextSetOutcome::ReadbackFailed;
        }
        Err(EditableTextReadbackError::TimedOut) => {
            return EditableTextSetOutcome::ReadbackTimedOut;
        }
    };

    loop {
        match text_readback_matches(&text, requested, deadline).await {
            Ok(true) => return EditableTextSetOutcome::Verified,
            Ok(false) => {}
            Err(EditableTextReadbackError::Failed) => {
                return EditableTextSetOutcome::ReadbackFailed;
            }
            Err(EditableTextReadbackError::TimedOut) => {
                return EditableTextSetOutcome::ReadbackTimedOut;
            }
        }

        let now = Instant::now();
        if now >= deadline {
            return EditableTextSetOutcome::MismatchAfterDeadline;
        }
        sleep_until((now + EDITABLE_TEXT_VERIFY_INTERVAL).min(deadline)).await;
        if Instant::now() >= deadline {
            return EditableTextSetOutcome::MismatchAfterDeadline;
        }
    }
}

async fn connect() -> Result<AccessibilityConnection> {
    hydrate_session_bus_env();
    AccessibilityConnection::new()
        .await
        .context("failed to connect to AT-SPI bus")
}

/// Open an `AccessibleProxy` for an object on the a11y bus.
///
/// We deliberately avoid `AccessibilityConnection::object_as_accessible` (the
/// `P2P` trait). For apps that advertise a peer-to-peer bus address it routes
/// reads over that socket, but for apps that don't (notably GTK4 apps such as
/// Nautilus / Text Editor / baobab, which don't implement the legacy
/// `GetApplicationBusAddress`) it falls back to a proxy built with only a path
/// and *no destination*. On the shared a11y bus that proxy can't address the
/// app and every call fails with `ServiceUnknown`, which surfaces as an empty
/// tree (`role: "unknown"`, `child_count: 0`). `as_accessible_proxy` always
/// pins the destination to the object's bus name, so it works for every app
/// regardless of P2P support. See issue #31.
async fn open_accessible<'r>(
    conn: &AccessibilityConnection,
    object_ref: &'r ObjectRefOwned,
) -> Result<AccessibleProxy<'r>, atspi::AtspiError> {
    object_ref.as_accessible_proxy(conn.connection()).await
}

async fn registry_children(
    conn: &AccessibilityConnection,
    limit: usize,
    remaining_child_reads: &mut usize,
) -> Result<Vec<ObjectRefOwned>> {
    let root = conn
        .root_accessible_on_registry()
        .await
        .context("failed to open AT-SPI registry root")?;
    let batch = children_up_to(&root, limit, remaining_child_reads)
        .await
        .context("failed to read AT-SPI registry children")?;
    if batch.all_failed() {
        return Err(anyhow!(
            "AT-SPI registry reported children, but every indexed child read failed"
        ));
    }
    Ok(batch.items)
}

struct SelectedRoots {
    roots: Vec<ObjectRefOwned>,
    scoped: bool,
    /// Set only when the roots were chosen because they belong to this pid.
    pid: Option<u32>,
    app_filter_matched: bool,
}

/// Normalized app-name filter, or `None` when the caller passed nothing usable.
/// A `None` needle with no pid match means the snapshot covers the whole desktop.
fn app_name_needle(app_name_or_bundle_identifier: Option<&str>) -> Option<String> {
    app_name_or_bundle_identifier
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .map(|value| value.to_ascii_lowercase())
}

async fn select_roots(
    conn: &AccessibilityConnection,
    roots: Vec<ObjectRefOwned>,
    app_name_or_bundle_identifier: Option<&str>,
    target_pid: Option<u32>,
    remaining_child_reads: &mut usize,
) -> SelectedRoots {
    let needle = app_name_needle(app_name_or_bundle_identifier);
    let dbus = DBusProxy::new(conn.connection()).await.ok();
    let mut remaining = roots;

    if let Some(target_pid) = target_pid {
        let mut pid_and_filter_matches = Vec::new();
        let mut pid_matches = Vec::new();
        let mut non_pid_matches = Vec::new();

        for object_ref in remaining {
            if object_ref_pid(dbus.as_ref(), &object_ref).await == Some(target_pid) {
                if let Some(needle) = needle.as_deref() {
                    if root_matches(conn, &object_ref, needle, remaining_child_reads).await {
                        pid_and_filter_matches.push(object_ref);
                    } else {
                        pid_matches.push(object_ref);
                    }
                } else {
                    pid_matches.push(object_ref);
                }
            } else {
                non_pid_matches.push(object_ref);
            }
        }

        if !pid_and_filter_matches.is_empty() {
            return SelectedRoots {
                roots: pid_and_filter_matches,
                scoped: true,
                pid: Some(target_pid),
                app_filter_matched: true,
            };
        }
        if !pid_matches.is_empty() {
            return SelectedRoots {
                roots: pid_matches,
                scoped: true,
                pid: Some(target_pid),
                app_filter_matched: needle.is_none(),
            };
        }

        remaining = non_pid_matches;
    }

    let Some(needle) = needle.as_deref() else {
        return SelectedRoots {
            roots: remaining,
            scoped: false,
            pid: None,
            app_filter_matched: true,
        };
    };

    let mut selected = Vec::new();
    for object_ref in remaining {
        if root_matches(conn, &object_ref, needle, remaining_child_reads).await {
            selected.push(object_ref);
        }
    }

    let app_filter_matched = !selected.is_empty();
    SelectedRoots {
        roots: selected,
        scoped: true,
        pid: None,
        app_filter_matched,
    }
}

async fn root_matches(
    conn: &AccessibilityConnection,
    object_ref: &ObjectRefOwned,
    needle: &str,
    remaining_child_reads: &mut usize,
) -> bool {
    let Ok(proxy) = open_accessible(conn, object_ref).await else {
        return object_ref_id(object_ref)
            .to_ascii_lowercase()
            .contains(needle);
    };

    if proxy_matches(&proxy, object_ref, needle).await {
        return true;
    }

    for child_ref in children_up_to(&proxy, ROOT_MATCH_CHILD_LIMIT, remaining_child_reads)
        .await
        .map(|batch| batch.items)
        .unwrap_or_default()
    {
        let Ok(child_proxy) = open_accessible(conn, &child_ref).await else {
            continue;
        };
        if proxy_matches(&child_proxy, &child_ref, needle).await {
            return true;
        }
    }

    false
}

async fn proxy_matches(
    proxy: &AccessibleProxy<'_>,
    object_ref: &ObjectRefOwned,
    needle: &str,
) -> bool {
    let name = proxy.name().await.unwrap_or_default();
    let role = proxy.get_role_name().await.unwrap_or_default();
    format!("{} {} {}", object_ref_id(object_ref), name, role)
        .to_ascii_lowercase()
        .contains(needle)
}

async fn read_app_summary(
    proxy: &AccessibleProxy<'_>,
    object_ref: &ObjectRefOwned,
    dbus: Option<&DBusProxy<'_>>,
) -> AccessibleAppSummary {
    AccessibleAppSummary {
        object_ref: object_ref_id(object_ref),
        name: optional_string(proxy.name().await.ok()),
        pid: object_ref_pid(dbus, object_ref).await,
        role: role_name(proxy).await,
        child_count: proxy.child_count().await.unwrap_or_default(),
        bounds: bounds(proxy).await,
    }
}

async fn read_node(
    proxy: &AccessibleProxy<'_>,
    object_ref: &ObjectRefOwned,
    index: u32,
    parent_index: Option<u32>,
    depth: u32,
) -> AccessibilityNode {
    let proxies = proxy.proxies().await.ok();

    AccessibilityNode {
        index,
        parent_index,
        depth,
        object_ref: object_ref_id(object_ref),
        role: role_name(proxy).await,
        name: optional_string(proxy.name().await.ok()),
        description: optional_string(proxy.description().await.ok()),
        child_count: proxy.child_count().await.unwrap_or_default(),
        bounds: bounds_from_proxies(proxies.as_ref(), proxy).await,
        states: states_from_proxy(proxy).await,
        actions: actions_from_proxies(proxies.as_ref()).await,
        value: value_from_proxies(proxies.as_ref()).await,
        text: text_from_proxies(proxies.as_ref()).await,
        supports_editable_text: supports_editable_text(proxies.as_ref()).await,
    }
}

/// Role reported when neither AT-SPI role read succeeds.
pub(crate) const UNKNOWN_ROLE: &str = "unknown";

async fn role_name(proxy: &AccessibleProxy<'_>) -> String {
    if let Ok(role) = proxy.get_role_name().await {
        if !role.trim().is_empty() {
            return role;
        }
    }
    proxy
        .get_role()
        .await
        .map(|role| format!("{role:?}"))
        .unwrap_or_else(|_| UNKNOWN_ROLE.to_string())
}

async fn bounds(proxy: &AccessibleProxy<'_>) -> Option<Bounds> {
    bounds_from_proxies(proxy.proxies().await.ok().as_ref(), proxy).await
}

/// Pid of the process that owns an AT-SPI object ref (`:bus/path`), from the
/// accessibility bus. `None` when the owner is gone or the bus cannot say.
pub(crate) async fn object_ref_owner_pid(object_ref_id: &str) -> Result<Option<u32>> {
    let object_ref = object_ref_from_id(object_ref_id)?;
    let conn = connect().await?;
    let dbus = DBusProxy::new(conn.connection()).await.ok();
    Ok(object_ref_pid(dbus.as_ref(), &object_ref).await)
}

async fn object_ref_pid(dbus: Option<&DBusProxy<'_>>, object_ref: &ObjectRefOwned) -> Option<u32> {
    let dbus = dbus?;
    let bus_name = BusName::try_from(object_ref.name_as_str()?.to_string()).ok()?;
    dbus.get_connection_unix_process_id(bus_name).await.ok()
}

async fn bounds_from_proxies(
    proxies: Option<&atspi::proxy::proxy_ext::Proxies<'_>>,
    proxy: &AccessibleProxy<'_>,
) -> Option<Bounds> {
    let owned_proxies;
    let proxies = if let Some(proxies) = proxies {
        proxies
    } else {
        owned_proxies = proxy.proxies().await.ok()?;
        &owned_proxies
    };
    let component = proxies.component().await.ok()?;
    let (x, y, width, height) = component.get_extents(CoordType::Screen).await.ok()?;
    normalize_bounds(Bounds {
        x,
        y,
        width,
        height,
    })
}

fn normalize_bounds(bounds: Bounds) -> Option<Bounds> {
    if bounds.width <= 0 || bounds.height <= 0 {
        return None;
    }
    if bounds.x <= i32::MIN / 2 || bounds.y <= i32::MIN / 2 {
        return None;
    }
    Some(bounds)
}

async fn actions_from_proxies(
    proxies: Option<&atspi::proxy::proxy_ext::Proxies<'_>>,
) -> Vec<AccessibilityAction> {
    let Some(proxies) = proxies else {
        return Vec::new();
    };
    let Ok(action_proxy) = proxies.action().await else {
        return Vec::new();
    };

    read_actions(&action_proxy)
        .await
        .unwrap_or_default()
        .into_iter()
        .enumerate()
        .map(|(index, action)| AccessibilityAction {
            index: index as i32,
            name: action.name,
            description: action.description,
            keybinding: action.keybinding,
        })
        .collect()
}

async fn read_actions(proxy: &ActionProxy<'_>) -> Result<Vec<atspi::Action>> {
    // WebKit can advertise GetActions without replying to it. The indexed
    // methods work, and must also be used when revalidating a cached action.
    // Keep the wire spelling: the current atspi binding asks for "Nactions".
    timeout(ACTION_QUERY_TIMEOUT, async {
        let count = proxy
            .inner()
            .get_property::<i32>("NActions")
            .await
            .context("failed to read AT-SPI action count")?;
        if count > MAX_ACTIONS_PER_OBJECT {
            return Err(anyhow!(
                "AT-SPI action count {count} exceeds the {MAX_ACTIONS_PER_OBJECT}-action read budget"
            ));
        }
        if count < 0 {
            return Err(anyhow!("invalid negative AT-SPI action count {count}"));
        }
        Ok(stream::iter(0..count)
            .map(|index| async move {
                let (name, description, keybinding) = tokio::join!(
                    proxy.get_name(index),
                    proxy.get_description(index),
                    proxy.get_key_binding(index),
                );
                atspi::Action {
                    name: name.unwrap_or_default(),
                    description: description.unwrap_or_default(),
                    keybinding: keybinding.unwrap_or_default(),
                }
            })
            .buffered(CHILD_READ_CONCURRENCY)
            .collect()
            .await)
    })
    .await
    .context("AT-SPI action reads exceeded their 5-second deadline")?
}

async fn states_from_proxy(proxy: &AccessibleProxy<'_>) -> Vec<String> {
    proxy
        .get_state()
        .await
        .map(state_labels)
        .unwrap_or_default()
}

async fn value_from_proxies(
    proxies: Option<&atspi::proxy::proxy_ext::Proxies<'_>>,
) -> Option<AccessibilityValue> {
    let value = proxies?.value().await.ok()?;
    Some(AccessibilityValue {
        current: value.current_value().await.ok()?,
        minimum: value.minimum_value().await.ok()?,
        maximum: value.maximum_value().await.ok()?,
        minimum_increment: value.minimum_increment().await.ok()?,
        text: optional_string(value.text().await.ok()),
    })
}

async fn text_from_proxies(
    proxies: Option<&atspi::proxy::proxy_ext::Proxies<'_>>,
) -> Option<AccessibilityText> {
    let text = proxies?.text().await.ok()?;
    let character_count = text.character_count().await.ok()?.max(0);
    let caret_offset = text.caret_offset().await.ok();
    let capped_count = character_count.min(MAX_TEXT_READBACK_CHARS);
    let content = if capped_count > 0 {
        optional_string(text.get_text(0, capped_count).await.ok())
    } else {
        None
    };
    let selection_count = text
        .get_nselections()
        .await
        .unwrap_or_default()
        .clamp(0, MAX_TEXT_SELECTIONS);
    let mut selections = Vec::new();
    for index in 0..selection_count {
        if let Ok((start_offset, end_offset)) = text.get_selection(index).await {
            selections.push(AccessibilityTextSelection {
                start_offset,
                end_offset,
            });
        }
    }

    Some(AccessibilityText {
        character_count,
        caret_offset,
        content,
        truncated: character_count > MAX_TEXT_READBACK_CHARS,
        selections,
    })
}

async fn supports_editable_text(proxies: Option<&atspi::proxy::proxy_ext::Proxies<'_>>) -> bool {
    let Some(proxies) = proxies else {
        return false;
    };
    proxies.editable_text().await.is_ok()
}

fn state_labels(state_set: StateSet) -> Vec<String> {
    state_set.iter().map(|state| state.to_string()).collect()
}

fn select_action_index(actions: &[atspi::Action], requested_action: Option<&str>) -> Result<i32> {
    if actions.is_empty() {
        return Err(anyhow!("element exposes no AT-SPI actions"));
    }

    if let Some(requested_action) = requested_action
        .map(str::trim)
        .filter(|value| !value.is_empty())
    {
        let requested_action = requested_action.to_ascii_lowercase();
        if let Some((index, _)) = actions.iter().enumerate().find(|(_, action)| {
            action.name.to_ascii_lowercase() == requested_action
                || action.description.to_ascii_lowercase() == requested_action
        }) {
            return Ok(index as i32);
        }

        if let Ok(index) = requested_action.parse::<usize>() {
            if index < actions.len() {
                return Ok(index as i32);
            }
        }

        return Err(anyhow!(
            "requested AT-SPI action was not found; available actions: {}",
            actions
                .iter()
                .map(|action| action.name.as_str())
                .collect::<Vec<_>>()
                .join(", ")
        ));
    }

    Ok(if actions.len() > 1 { 1 } else { 0 })
}

fn select_named_action_index(actions: &[atspi::Action], name: &str) -> Result<i32> {
    actions
        .iter()
        .position(|action| action.name.eq_ignore_ascii_case(name))
        .map(|index| index as i32)
        .ok_or_else(|| {
            anyhow!("cached AT-SPI action name is no longer available; refresh get_app_state")
        })
}

fn optional_string(value: Option<String>) -> Option<String> {
    value
        .map(|value| value.trim().to_string())
        .filter(|value| !value.is_empty())
}

fn object_ref_from_id(object_ref_id: &str) -> Result<ObjectRefOwned> {
    let (name, path) = split_object_ref_id(object_ref_id)?;
    let name = UniqueName::try_from(name.to_string())
        .with_context(|| format!("invalid AT-SPI bus name in object ref {object_ref_id}"))?;
    let path = ObjectPath::try_from(path.to_string())
        .with_context(|| format!("invalid AT-SPI object path in object ref {object_ref_id}"))?;
    Ok(ObjectRef::new_owned(name, path))
}

fn split_object_ref_id(object_ref_id: &str) -> Result<(&str, &str)> {
    let Some(path_start) = object_ref_id.find('/') else {
        return Err(anyhow!(
            "invalid AT-SPI object ref '{object_ref_id}'; expected ':bus/path'"
        ));
    };
    let (name, path) = object_ref_id.split_at(path_start);
    if name.is_empty() || path.is_empty() {
        return Err(anyhow!(
            "invalid AT-SPI object ref '{object_ref_id}'; expected ':bus/path'"
        ));
    }
    Ok((name, path))
}

fn object_ref_id(object_ref: &ObjectRefOwned) -> String {
    format!(
        "{}{}",
        object_ref.name_as_str().unwrap_or(""),
        object_ref.path_as_str()
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::{
        io::{BufRead, BufReader},
        process::{Child, Command, Stdio},
        sync::{
            atomic::{AtomicUsize, Ordering},
            Arc, Mutex,
        },
    };

    struct PrivateBus(Child);

    impl PrivateBus {
        fn start() -> (Self, String) {
            let mut bus = Self(
                Command::new("dbus-daemon")
                    .args(["--session", "--nofork", "--nopidfile", "--print-address=1"])
                    .stdout(Stdio::piped())
                    .spawn()
                    .unwrap(),
            );
            let mut address = String::new();
            BufReader::new(bus.0.stdout.take().unwrap())
                .read_line(&mut address)
                .unwrap();
            (bus, address.trim().to_string())
        }
    }

    impl Drop for PrivateBus {
        fn drop(&mut self) {
            let _ = self.0.kill();
            let _ = self.0.wait();
        }
    }

    const EDITABLE_FIXTURE_PATH: &str = "/editable";

    #[derive(Default)]
    struct FakeEditableState {
        contents: String,
        mutations: usize,
        character_count_reads: usize,
        get_text_reads: usize,
        numeric_value: f64,
        numeric_writes: usize,
    }

    #[derive(Clone, Copy)]
    enum FakeMutation {
        Apply,
        NoOp,
        Delayed,
        Normalize,
        Mask,
        Reject,
        Fail,
    }

    #[derive(Clone, Copy, Debug)]
    enum FakeTextOffsetModel {
        UnicodeScalars,
        Utf16CodeUnits,
    }

    #[derive(Clone, Copy)]
    enum FakeTextBehavior {
        Normal,
        CharacterCountError,
        GetTextError,
        NegativeCount,
        StallCharacterCount,
    }

    #[derive(Clone, Copy)]
    struct FakeEditableConfig {
        mutation: FakeMutation,
        text: FakeTextBehavior,
        text_offset_model: FakeTextOffsetModel,
        role: atspi::Role,
        has_text: bool,
        has_value: bool,
    }

    impl Default for FakeEditableConfig {
        fn default() -> Self {
            Self {
                mutation: FakeMutation::Apply,
                text: FakeTextBehavior::Normal,
                text_offset_model: FakeTextOffsetModel::Utf16CodeUnits,
                role: atspi::Role::Text,
                has_text: true,
                has_value: false,
            }
        }
    }

    struct FakeEditableAccessible(FakeEditableConfig);

    #[zbus::interface(name = "org.a11y.atspi.Accessible")]
    impl FakeEditableAccessible {
        #[zbus(property)]
        fn child_count(&self) -> i32 {
            0
        }

        fn get_interfaces(&self) -> Vec<&str> {
            let mut interfaces = vec!["org.a11y.atspi.Accessible", "org.a11y.atspi.EditableText"];
            if self.0.has_text {
                interfaces.push("org.a11y.atspi.Text");
            }
            if self.0.has_value {
                interfaces.push("org.a11y.atspi.Value");
            }
            interfaces
        }

        fn get_role(&self) -> atspi::Role {
            self.0.role
        }
    }

    struct FakeEditableText {
        state: Arc<Mutex<FakeEditableState>>,
        mutation: FakeMutation,
    }

    #[zbus::interface(name = "org.a11y.atspi.EditableText")]
    impl FakeEditableText {
        fn set_text_contents(&self, new_contents: &str) -> zbus::fdo::Result<bool> {
            self.state.lock().unwrap().mutations += 1;
            match self.mutation {
                FakeMutation::Apply => {
                    self.state.lock().unwrap().contents = new_contents.to_string();
                }
                FakeMutation::NoOp => {}
                FakeMutation::Delayed => {
                    let state = Arc::clone(&self.state);
                    let new_contents = new_contents.to_string();
                    tokio::spawn(async move {
                        tokio::time::sleep(Duration::from_millis(150)).await;
                        state.lock().unwrap().contents = new_contents;
                    });
                }
                FakeMutation::Normalize => {
                    self.state.lock().unwrap().contents = new_contents.replace("\r\n", "\n");
                }
                FakeMutation::Mask => {
                    self.state.lock().unwrap().contents = "•".repeat(new_contents.chars().count());
                }
                FakeMutation::Reject => return Ok(false),
                FakeMutation::Fail => {
                    return Err(zbus::fdo::Error::Failed(
                        "injected SetTextContents failure".into(),
                    ));
                }
            }
            Ok(true)
        }
    }

    fn unicode_scalar_offset_to_byte_index(contents: &str, offset: usize) -> Option<usize> {
        contents
            .char_indices()
            .map(|(byte_index, _)| byte_index)
            .chain(std::iter::once(contents.len()))
            .nth(offset)
    }

    fn utf16_offset_to_byte_index(contents: &str, offset: usize) -> Option<usize> {
        let mut utf16_offset = 0;
        for (byte_index, character) in contents.char_indices() {
            if utf16_offset == offset {
                return Some(byte_index);
            }
            utf16_offset += character.len_utf16();
        }
        (utf16_offset == offset).then_some(contents.len())
    }

    struct FakeText {
        state: Arc<Mutex<FakeEditableState>>,
        behavior: FakeTextBehavior,
        text_offset_model: FakeTextOffsetModel,
    }

    #[zbus::interface(name = "org.a11y.atspi.Text")]
    impl FakeText {
        #[zbus(property)]
        async fn character_count(&self) -> zbus::fdo::Result<i32> {
            self.state.lock().unwrap().character_count_reads += 1;
            match self.behavior {
                FakeTextBehavior::CharacterCountError => Err(zbus::fdo::Error::Failed(
                    "injected CharacterCount failure".into(),
                )),
                FakeTextBehavior::NegativeCount => Ok(-1),
                FakeTextBehavior::StallCharacterCount => std::future::pending().await,
                _ => {
                    let state = self.state.lock().unwrap();
                    let count = match self.text_offset_model {
                        FakeTextOffsetModel::UnicodeScalars => state.contents.chars().count(),
                        FakeTextOffsetModel::Utf16CodeUnits => {
                            state.contents.encode_utf16().count()
                        }
                    };
                    Ok(count as i32)
                }
            }
        }

        fn get_text(&self, start_offset: i32, end_offset: i32) -> zbus::fdo::Result<String> {
            let mut state = self.state.lock().unwrap();
            state.get_text_reads += 1;
            if matches!(self.behavior, FakeTextBehavior::GetTextError) {
                return Err(zbus::fdo::Error::Failed("injected GetText failure".into()));
            }
            if start_offset < 0 || end_offset < start_offset {
                return Err(zbus::fdo::Error::InvalidArgs("invalid text offsets".into()));
            }
            let offset_to_byte_index = match self.text_offset_model {
                FakeTextOffsetModel::UnicodeScalars => unicode_scalar_offset_to_byte_index,
                FakeTextOffsetModel::Utf16CodeUnits => utf16_offset_to_byte_index,
            };
            let start = offset_to_byte_index(&state.contents, start_offset as usize)
                .ok_or_else(|| zbus::fdo::Error::InvalidArgs("invalid text offsets".into()))?;
            let end = offset_to_byte_index(&state.contents, end_offset as usize)
                .ok_or_else(|| zbus::fdo::Error::InvalidArgs("invalid text offsets".into()))?;
            Ok(state.contents[start..end].to_string())
        }
    }

    struct FakeValue(Arc<Mutex<FakeEditableState>>);

    #[zbus::interface(name = "org.a11y.atspi.Value")]
    impl FakeValue {
        #[zbus(property)]
        fn current_value(&self) -> f64 {
            self.0.lock().unwrap().numeric_value
        }

        #[zbus(property)]
        fn set_current_value(&self, value: f64) {
            let mut state = self.0.lock().unwrap();
            state.numeric_value = value;
            state.numeric_writes += 1;
        }
    }

    async fn start_editable_fixture(
        initial_contents: &str,
        config: FakeEditableConfig,
    ) -> (
        PrivateBus,
        zbus::Connection,
        zbus::Connection,
        Arc<Mutex<FakeEditableState>>,
    ) {
        let (bus, address) = PrivateBus::start();
        let state = Arc::new(Mutex::new(FakeEditableState {
            contents: initial_contents.to_string(),
            ..Default::default()
        }));
        let mut builder = zbus::connection::Builder::address(address.as_str())
            .unwrap()
            .serve_at(EDITABLE_FIXTURE_PATH, FakeEditableAccessible(config))
            .unwrap()
            .serve_at(
                EDITABLE_FIXTURE_PATH,
                FakeEditableText {
                    state: Arc::clone(&state),
                    mutation: config.mutation,
                },
            )
            .unwrap();
        if config.has_text {
            builder = builder
                .serve_at(
                    EDITABLE_FIXTURE_PATH,
                    FakeText {
                        state: Arc::clone(&state),
                        behavior: config.text,
                        text_offset_model: config.text_offset_model,
                    },
                )
                .unwrap();
        }
        if config.has_value {
            builder = builder
                .serve_at(EDITABLE_FIXTURE_PATH, FakeValue(Arc::clone(&state)))
                .unwrap();
        }
        let peer = builder.build().await.unwrap();
        let client = zbus::connection::Builder::address(address.as_str())
            .unwrap()
            .build()
            .await
            .unwrap();
        (bus, peer, client, state)
    }

    async fn dispatch_editable_fixture(
        client: &zbus::Connection,
        peer: &zbus::Connection,
        value: &str,
    ) -> Result<ValueSetInvocation> {
        let proxy = AccessibleProxy::builder(client)
            .destination(peer.unique_name().unwrap().clone())
            .unwrap()
            .path(EDITABLE_FIXTURE_PATH)
            .unwrap()
            .cache_properties(zbus::proxy::CacheProperties::No)
            .build()
            .await
            .unwrap();
        let proxies = proxy.proxies().await.unwrap();
        set_element_value_with_proxies(&proxy, &proxies, value).await
    }

    fn editable_outcome(invocation: ValueSetInvocation) -> EditableTextSetOutcome {
        match invocation {
            ValueSetInvocation::EditableText { outcome } => outcome,
            ValueSetInvocation::Numeric { .. } => panic!("expected editable-text dispatch"),
        }
    }

    struct FakeAccessible {
        name: String,
        children: Vec<(String, OwnedObjectPath)>,
        has_action: bool,
    }

    #[zbus::interface(name = "org.a11y.atspi.Accessible")]
    impl FakeAccessible {
        #[zbus(property)]
        fn child_count(&self) -> i32 {
            self.children.len() as i32
        }

        #[zbus(property)]
        fn name(&self) -> &str {
            &self.name
        }

        fn get_interfaces(&self) -> Vec<&str> {
            let mut interfaces = vec!["org.a11y.atspi.Accessible"];
            if self.has_action {
                interfaces.push("org.a11y.atspi.Action");
            }
            interfaces
        }

        fn get_child_at_index(
            &self,
            index: i32,
        ) -> zbus::fdo::Result<((String, OwnedObjectPath),)> {
            self.children
                .get(index as usize)
                .cloned()
                .map(|child| (child,))
                .ok_or_else(|| zbus::fdo::Error::InvalidArgs("invalid child index".into()))
        }
    }

    struct FakeWebKitAction {
        count: i32,
        stall_indexed_reads: bool,
        name_reads: Arc<AtomicUsize>,
    }

    impl Default for FakeWebKitAction {
        fn default() -> Self {
            Self {
                count: 1,
                stall_indexed_reads: false,
                name_reads: Arc::default(),
            }
        }
    }

    #[zbus::interface(name = "org.a11y.atspi.Action")]
    impl FakeWebKitAction {
        async fn get_actions(&self) -> Vec<atspi::Action> {
            std::future::pending().await
        }

        #[zbus(property, name = "NActions")]
        fn nactions(&self) -> i32 {
            self.count
        }

        async fn get_name(&self, index: i32) -> &str {
            assert!((0..self.count).contains(&index));
            self.name_reads.fetch_add(1, Ordering::SeqCst);
            if self.stall_indexed_reads {
                std::future::pending::<()>().await;
            }
            "click"
        }

        async fn get_localized_name(&self, index: i32) -> &str {
            assert!((0..self.count).contains(&index));
            "Activate"
        }

        fn get_description(&self, index: i32) -> &str {
            assert!((0..self.count).contains(&index));
            "Activate the control"
        }

        fn get_key_binding(&self, index: i32) -> &str {
            assert!((0..self.count).contains(&index));
            "Return"
        }

        fn do_action(&self, index: i32) -> bool {
            index == 0
        }
    }

    struct FakeQtAction;

    #[zbus::interface(name = "org.a11y.atspi.Action")]
    impl FakeQtAction {
        #[zbus(property, name = "NActions")]
        fn nactions(&self) -> i32 {
            2
        }

        fn get_name(&self, index: i32) -> &str {
            match index {
                0 => "Press",
                1 => "Set Focus",
                _ => panic!("invalid action index"),
            }
        }

        fn get_description(&self, index: i32) -> &str {
            match index {
                0 => "Eylemi tetikler",
                1 => "Odağı ayarlar",
                _ => panic!("invalid action index"),
            }
        }

        fn get_key_binding(&self, _index: i32) -> &str {
            ""
        }
    }

    #[tokio::test]
    async fn editable_text_true_without_publication_is_mismatch_and_mutates_once() {
        let (_bus, peer, client, state) = start_editable_fixture(
            "original",
            FakeEditableConfig {
                mutation: FakeMutation::NoOp,
                ..Default::default()
            },
        )
        .await;

        let outcome = editable_outcome(
            dispatch_editable_fixture(&client, &peer, "modified")
                .await
                .unwrap(),
        );

        // A last poll can cross the same fixed deadline. Both outcomes mean
        // an unverified write; neither permits verification or replay.
        assert!(
            matches!(
                outcome,
                EditableTextSetOutcome::MismatchAfterDeadline
                    | EditableTextSetOutcome::ReadbackTimedOut
            ),
            "{outcome:?}"
        );
        let state = state.lock().unwrap();
        assert_eq!(state.mutations, 1);
        assert!(state.character_count_reads > 1);
        assert!(state.get_text_reads > 1);
        assert_eq!(state.contents, "original");
    }

    #[tokio::test]
    async fn editable_text_exact_readback_accepts_empty_whitespace_and_trailing_newline() {
        let (_bus, peer, client, state) =
            start_editable_fixture("initial", FakeEditableConfig::default()).await;
        let values = [
            "",
            " \t\n",
            "  leading and trailing\t \n",
            "trailing newline\n",
            "Case and unicode € 内容 😀🦀𐐷",
        ];

        for value in values {
            let outcome = editable_outcome(
                dispatch_editable_fixture(&client, &peer, value)
                    .await
                    .unwrap(),
            );
            assert_eq!(outcome, EditableTextSetOutcome::Verified);
            assert_eq!(state.lock().unwrap().contents, value);
        }
        assert_eq!(state.lock().unwrap().mutations, values.len());
    }

    #[tokio::test]
    async fn editable_text_non_bmp_readback_supports_scalar_and_utf16_peers() {
        let requested = "🦀 GTK verified ";
        for text_offset_model in [
            FakeTextOffsetModel::UnicodeScalars,
            FakeTextOffsetModel::Utf16CodeUnits,
        ] {
            let (_bus, peer, client, state) = start_editable_fixture(
                "",
                FakeEditableConfig {
                    text_offset_model,
                    ..Default::default()
                },
            )
            .await;

            let outcome = editable_outcome(
                dispatch_editable_fixture(&client, &peer, requested)
                    .await
                    .unwrap(),
            );

            assert_eq!(
                outcome,
                EditableTextSetOutcome::Verified,
                "{text_offset_model:?}"
            );
            let state = state.lock().unwrap();
            assert_eq!(state.mutations, 1);
            assert_eq!(state.contents, requested);
        }
    }

    #[tokio::test]
    async fn editable_text_non_bmp_matching_count_does_not_accept_different_content() {
        let requested = "🦀 GTK verified ";
        let published = "🦀 GTK verified!";
        assert_eq!(requested.chars().count(), published.chars().count());
        assert_eq!(
            requested.encode_utf16().count(),
            published.encode_utf16().count()
        );
        for text_offset_model in [
            FakeTextOffsetModel::UnicodeScalars,
            FakeTextOffsetModel::Utf16CodeUnits,
        ] {
            let (_bus, peer, client, state) = start_editable_fixture(
                published,
                FakeEditableConfig {
                    mutation: FakeMutation::NoOp,
                    text_offset_model,
                    ..Default::default()
                },
            )
            .await;

            let outcome = editable_outcome(
                dispatch_editable_fixture(&client, &peer, requested)
                    .await
                    .unwrap(),
            );

            // A last poll can cross the same fixed deadline. Both outcomes
            // leave the write unverified without extending its deadline.
            assert!(
                matches!(
                    outcome,
                    EditableTextSetOutcome::MismatchAfterDeadline
                        | EditableTextSetOutcome::ReadbackTimedOut
                ),
                "{text_offset_model:?}: {outcome:?}"
            );
            let state = state.lock().unwrap();
            assert_eq!(state.mutations, 1);
            assert!(state.get_text_reads > 0, "{text_offset_model:?}");
            assert_eq!(state.contents, published);
        }
    }

    #[tokio::test]
    async fn editable_text_readback_chunks_utf16_without_splitting_non_bmp() {
        let (_bus, peer, client, state) = start_editable_fixture(
            "",
            FakeEditableConfig {
                text_offset_model: FakeTextOffsetModel::Utf16CodeUnits,
                ..Default::default()
            },
        )
        .await;
        let mut expected = "a".repeat(EDITABLE_TEXT_READ_CHUNK_UNITS - 1);
        // The crab's surrogate pair straddles the first 4096-unit read boundary.
        expected.push_str("🦀é");
        expected.push_str(&"内容\n".repeat(1_200));
        assert!(expected.encode_utf16().count() > MAX_TEXT_READBACK_CHARS as usize);

        let outcome = editable_outcome(
            dispatch_editable_fixture(&client, &peer, &expected)
                .await
                .unwrap(),
        );

        assert_eq!(outcome, EditableTextSetOutcome::Verified);
        let state = state.lock().unwrap();
        assert_eq!(state.mutations, 1);
        assert!(state.get_text_reads >= 2);
        assert_eq!(state.contents, expected);
    }

    #[tokio::test]
    async fn editable_text_readback_waits_for_async_publication() {
        let (_bus, peer, client, state) = start_editable_fixture(
            "pending",
            FakeEditableConfig {
                mutation: FakeMutation::Delayed,
                ..Default::default()
            },
        )
        .await;

        let outcome = editable_outcome(
            dispatch_editable_fixture(&client, &peer, "published asynchronously")
                .await
                .unwrap(),
        );

        assert_eq!(outcome, EditableTextSetOutcome::Verified);
        let state = state.lock().unwrap();
        assert_eq!(state.mutations, 1);
        assert!(state.character_count_reads > 1);
        assert_eq!(state.contents, "published asynchronously");
    }

    #[tokio::test]
    async fn editable_text_normalization_mismatch_is_not_verified() {
        let (_bus, peer, client, state) = start_editable_fixture(
            "",
            FakeEditableConfig {
                mutation: FakeMutation::Normalize,
                ..Default::default()
            },
        )
        .await;

        let outcome = editable_outcome(
            dispatch_editable_fixture(&client, &peer, "first\r\nsecond\n")
                .await
                .unwrap(),
        );

        assert_eq!(outcome, EditableTextSetOutcome::MismatchAfterDeadline);
        let state = state.lock().unwrap();
        assert_eq!(state.mutations, 1);
        assert!(state.character_count_reads > 1);
        assert_eq!(state.contents, "first\nsecond\n");
    }

    #[tokio::test]
    async fn password_text_is_unverifiable_even_when_requested_text_is_bullets() {
        let (_bus, peer, client, state) = start_editable_fixture(
            "",
            FakeEditableConfig {
                mutation: FakeMutation::Mask,
                role: atspi::Role::PasswordText,
                ..Default::default()
            },
        )
        .await;

        let outcome = editable_outcome(
            dispatch_editable_fixture(&client, &peer, "••••••••")
                .await
                .unwrap(),
        );

        assert_eq!(outcome, EditableTextSetOutcome::PasswordUnverifiable);
        let state = state.lock().unwrap();
        assert_eq!(state.mutations, 1);
        assert_eq!(state.character_count_reads, 0);
        assert_eq!(state.contents, "••••••••");
    }

    #[tokio::test]
    async fn editable_text_missing_text_and_read_errors_are_structured_outcomes() {
        let configs = [
            FakeEditableConfig {
                has_text: false,
                ..Default::default()
            },
            FakeEditableConfig {
                text: FakeTextBehavior::CharacterCountError,
                ..Default::default()
            },
            FakeEditableConfig {
                text: FakeTextBehavior::GetTextError,
                ..Default::default()
            },
        ];

        for config in configs {
            let (_bus, peer, client, state) = start_editable_fixture("before", config).await;
            let outcome = editable_outcome(
                dispatch_editable_fixture(&client, &peer, "readback may have changed")
                    .await
                    .unwrap(),
            );
            assert_eq!(outcome, EditableTextSetOutcome::ReadbackFailed);
            assert_eq!(state.lock().unwrap().mutations, 1);
        }
    }

    #[tokio::test]
    async fn editable_text_negative_counts_and_stalled_readback_are_structured_outcomes() {
        let cases = [
            (
                FakeTextBehavior::NegativeCount,
                EditableTextSetOutcome::ReadbackFailed,
            ),
            (
                FakeTextBehavior::StallCharacterCount,
                EditableTextSetOutcome::ReadbackTimedOut,
            ),
        ];

        for (text, expected) in cases {
            let (_bus, peer, client, state) = start_editable_fixture(
                "before",
                FakeEditableConfig {
                    text,
                    ..Default::default()
                },
            )
            .await;
            let outcome = editable_outcome(
                dispatch_editable_fixture(&client, &peer, "after")
                    .await
                    .unwrap(),
            );
            assert_eq!(outcome, expected);
            let state = state.lock().unwrap();
            assert_eq!(state.mutations, 1);
            assert_eq!(state.get_text_reads, 0);
        }
    }

    #[tokio::test]
    async fn editable_text_rejection_and_mutation_errors_remain_errors() {
        let cases = [
            (FakeMutation::Reject, "rejected"),
            (FakeMutation::Fail, "failed to set"),
        ];

        for (mutation, expected_error) in cases {
            let (_bus, peer, client, state) = start_editable_fixture(
                "before",
                FakeEditableConfig {
                    mutation,
                    ..Default::default()
                },
            )
            .await;
            let error = dispatch_editable_fixture(&client, &peer, "after")
                .await
                .unwrap_err();
            assert!(error.to_string().contains(expected_error));
            let state = state.lock().unwrap();
            assert_eq!(state.mutations, 1);
            assert_eq!(state.character_count_reads, 0);
        }
    }

    #[tokio::test]
    async fn numeric_value_dispatch_remains_isolated_from_editable_text() {
        let (_bus, peer, client, state) = start_editable_fixture(
            "unchanged",
            FakeEditableConfig {
                has_value: true,
                ..Default::default()
            },
        )
        .await;

        let invocation = dispatch_editable_fixture(&client, &peer, "42.5")
            .await
            .unwrap();

        match invocation {
            ValueSetInvocation::Numeric { value } => assert_eq!(value, 42.5),
            ValueSetInvocation::EditableText { .. } => panic!("expected numeric dispatch"),
        }
        let state = state.lock().unwrap();
        assert_eq!(state.numeric_value, 42.5);
        assert_eq!(state.numeric_writes, 1);
        assert_eq!(state.mutations, 0);
        assert_eq!(state.character_count_reads, 0);
        assert_eq!(state.contents, "unchanged");
    }

    #[tokio::test]
    async fn qt_action_names_do_not_depend_on_localized_names() {
        let (_bus, address) = PrivateBus::start();
        let peer = zbus::connection::Builder::address(address.as_str())
            .unwrap()
            .serve_at("/actions/qt", FakeQtAction)
            .unwrap()
            .build()
            .await
            .unwrap();
        let client = zbus::connection::Builder::address(address.as_str())
            .unwrap()
            .build()
            .await
            .unwrap();
        let action = ActionProxy::builder(&client)
            .destination(peer.unique_name().unwrap().clone())
            .unwrap()
            .path("/actions/qt")
            .unwrap()
            .cache_properties(zbus::proxy::CacheProperties::No)
            .build()
            .await
            .unwrap();

        let actions = timeout(Duration::from_secs(1), read_actions(&action))
            .await
            .expect("Qt action reads must not require GetLocalizedName")
            .unwrap();

        assert_eq!(actions.len(), 2);
        assert_eq!(actions[0].name, "Press");
        assert_eq!(actions[0].description, "Eylemi tetikler");
        assert_eq!(actions[1].name, "Set Focus");
        assert_eq!(actions[1].description, "Odağı ayarlar");
        assert_eq!(select_named_action_index(&actions, "press").unwrap(), 0);
    }

    #[tokio::test]
    async fn indexed_children_resolve_webkit_names_on_the_accessibility_bus() {
        let (_bus, address) = PrivateBus::start();

        let webkit_name = "org.webkit.MockWebProcess";
        let child_path = "/org/a11y/webkit/accessible/child";
        let webkit = zbus::connection::Builder::address(address.trim())
            .unwrap()
            .name(webkit_name)
            .unwrap()
            .serve_at(
                child_path,
                FakeAccessible {
                    name: "WebKit page".into(),
                    children: Vec::new(),
                    has_action: true,
                },
            )
            .unwrap()
            .serve_at(child_path, FakeWebKitAction::default())
            .unwrap()
            .build()
            .await
            .unwrap();
        let owner = webkit.unique_name().unwrap().to_string();
        let gtk = zbus::connection::Builder::address(address.trim())
            .unwrap()
            .serve_at(
                "/org/a11y/atspi/accessible/root",
                FakeAccessible {
                    name: "GTK socket".into(),
                    has_action: false,
                    children: vec![
                        (webkit_name.into(), child_path.try_into().unwrap()),
                        (owner.clone(), child_path.try_into().unwrap()),
                        (String::new(), "/org/a11y/atspi/null".try_into().unwrap()),
                        (
                            "org.webkit.UnownedWebProcess".into(),
                            child_path.try_into().unwrap(),
                        ),
                    ],
                },
            )
            .unwrap()
            .build()
            .await
            .unwrap();
        let client = zbus::connection::Builder::address(address.trim())
            .unwrap()
            .build()
            .await
            .unwrap();
        let proxy = AccessibleProxy::builder(&client)
            .destination(gtk.unique_name().unwrap().clone())
            .unwrap()
            .path("/org/a11y/atspi/accessible/root")
            .unwrap()
            .build()
            .await
            .unwrap();
        let mut remaining = 4;
        let reply = proxy
            .inner()
            .call_method("GetChildAtIndex", &(0_i32,))
            .await
            .unwrap();
        assert_eq!(reply.body().signature().to_string(), "(so)");
        let batch = children_up_to(&proxy, 4, &mut remaining).await.unwrap();

        assert_eq!(batch.attempted, 4);
        assert_eq!(remaining, 0);
        assert!(!batch.incomplete);
        assert_eq!(batch.items.len(), 3, "only the unowned name should fail");
        assert_eq!(batch.items[0].name_as_str(), Some(owner.as_str()));
        assert_eq!(batch.items[0].path_as_str(), child_path);
        assert_eq!(batch.items[0], batch.items[1]);
        assert!(batch.items[2].is_null());

        // The canonical reference remains usable by the normal read/action path.
        let child = batch.items[0].as_accessible_proxy(&client).await.unwrap();
        assert_eq!(child.name().await.unwrap(), "WebKit page");
        assert_eq!(
            object_ref_from_id(&object_ref_id(&batch.items[0])).unwrap(),
            batch.items[0]
        );
        let action = child.proxies().await.unwrap().action().await.unwrap();
        let actions = timeout(Duration::from_secs(1), read_actions(&action))
            .await
            .expect("indexed action reads must not wait for GetActions")
            .unwrap();
        assert_eq!(actions.len(), 1);
        assert_eq!(actions[0].name, "click");
        assert_eq!(actions[0].description, "Activate the control");
        assert_eq!(actions[0].keybinding, "Return");
        assert_eq!(select_named_action_index(&actions, "click").unwrap(), 0);
        assert!(action.do_action(0).await.unwrap());
    }

    #[tokio::test]
    async fn indexed_actions_bound_untrusted_counts_before_reading_indices() {
        let (_bus, address) = PrivateBus::start();
        let name_reads = Arc::new(AtomicUsize::new(0));
        let counts = [
            -1,
            MAX_ACTIONS_PER_OBJECT + 1,
            i32::MAX,
            0,
            MAX_ACTIONS_PER_OBJECT,
        ];
        let mut builder = zbus::connection::Builder::address(address.as_str()).unwrap();
        for (index, count) in counts.iter().enumerate() {
            builder = builder
                .serve_at(
                    format!("/actions/{index}"),
                    FakeWebKitAction {
                        count: *count,
                        name_reads: Arc::clone(&name_reads),
                        ..Default::default()
                    },
                )
                .unwrap();
        }
        let peer = builder.build().await.unwrap();
        let client = zbus::connection::Builder::address(address.as_str())
            .unwrap()
            .build()
            .await
            .unwrap();

        for (index, count) in counts.iter().enumerate() {
            let action = ActionProxy::builder(&client)
                .destination(peer.unique_name().unwrap().clone())
                .unwrap()
                .path(format!("/actions/{index}"))
                .unwrap()
                .cache_properties(zbus::proxy::CacheProperties::No)
                .build()
                .await
                .unwrap();
            let result = timeout(Duration::from_secs(1), read_actions(&action))
                .await
                .expect("untrusted counts must not cause unbounded work");
            if (0..=MAX_ACTIONS_PER_OBJECT).contains(count) {
                assert_eq!(result.unwrap().len(), *count as usize);
            } else {
                let error = result.unwrap_err().to_string();
                assert!(error.contains("action count"), "{error}");
                assert_eq!(name_reads.load(Ordering::SeqCst), 0);
            }
        }
        assert_eq!(
            name_reads.load(Ordering::SeqCst),
            MAX_ACTIONS_PER_OBJECT as usize
        );
    }

    #[tokio::test]
    async fn indexed_actions_time_out_the_entire_read() {
        let (_bus, address) = PrivateBus::start();
        let name_reads = Arc::new(AtomicUsize::new(0));
        let peer = zbus::connection::Builder::address(address.as_str())
            .unwrap()
            .serve_at(
                "/actions/stalled",
                FakeWebKitAction {
                    stall_indexed_reads: true,
                    name_reads: Arc::clone(&name_reads),
                    ..Default::default()
                },
            )
            .unwrap()
            .build()
            .await
            .unwrap();
        let client = zbus::connection::Builder::address(address.as_str())
            .unwrap()
            .build()
            .await
            .unwrap();
        let action = ActionProxy::builder(&client)
            .destination(peer.unique_name().unwrap().clone())
            .unwrap()
            .path("/actions/stalled")
            .unwrap()
            .cache_properties(zbus::proxy::CacheProperties::No)
            .build()
            .await
            .unwrap();

        let error = timeout(
            ACTION_QUERY_TIMEOUT + Duration::from_secs(1),
            read_actions(&action),
        )
        .await
        .expect("indexed reads must have an overall deadline")
        .unwrap_err();
        assert!(error.to_string().contains("5-second deadline"));
        assert_eq!(name_reads.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn split_object_ref_id_separates_bus_name_and_path() {
        let (name, path) = split_object_ref_id(":1.42/org/a11y/atspi/accessible/7").unwrap();

        assert_eq!(name, ":1.42");
        assert_eq!(path, "/org/a11y/atspi/accessible/7");
    }

    #[test]
    fn select_action_index_uses_named_action() {
        let actions = vec![
            atspi::Action {
                name: "click".to_string(),
                description: "Clicks".to_string(),
                keybinding: String::new(),
            },
            atspi::Action {
                name: "show-menu".to_string(),
                description: "Shows menu".to_string(),
                keybinding: String::new(),
            },
        ];

        assert_eq!(select_action_index(&actions, Some("show-menu")).unwrap(), 1);
    }

    #[test]
    fn cached_action_name_is_revalidated_against_current_actions() {
        let mut actions = vec![atspi::Action {
            name: "show-menu".into(),
            description: "Click".into(),
            keybinding: String::new(),
        }];
        // Neither a stale index nor a matching description may invoke another action.
        assert!(select_named_action_index(&actions, "Click").is_err());
        actions.push(atspi::Action {
            name: "click".into(),
            description: String::new(),
            keybinding: String::new(),
        });
        assert_eq!(select_named_action_index(&actions, "Click").unwrap(), 1);
    }

    #[test]
    fn select_action_index_defaults_to_secondary_when_available() {
        let actions = vec![
            atspi::Action {
                name: "click".to_string(),
                description: String::new(),
                keybinding: String::new(),
            },
            atspi::Action {
                name: "show-menu".to_string(),
                description: String::new(),
                keybinding: String::new(),
            },
        ];

        assert_eq!(select_action_index(&actions, None).unwrap(), 1);
    }

    #[test]
    fn state_labels_serialize_in_bit_order() {
        let labels = state_labels(StateSet::new(atspi::State::Focused | atspi::State::Checked));

        assert_eq!(labels, vec!["checked".to_string(), "focused".to_string()]);
    }

    #[test]
    fn default_snapshot_limits_cover_deep_gtk4_trees() {
        // Nautilus 50 places file-list cells below depth 20 and can expose
        // more than 850 raw nodes. Keep the defaults above that known shape.
        assert_eq!(snapshot_limits(None, None), (1_000, 32));
    }

    #[test]
    fn app_name_needle_ignores_blank_values_and_normalizes_the_rest() {
        assert_eq!(app_name_needle(None), None);
        assert_eq!(app_name_needle(Some("")), None);
        assert_eq!(app_name_needle(Some("   ")), None);
        assert_eq!(
            app_name_needle(Some("Calculator")).as_deref(),
            Some("calculator")
        );
        assert_eq!(
            app_name_needle(Some(" :1.64/org/a11y/atspi/accessible/root ")).as_deref(),
            Some(":1.64/org/a11y/atspi/accessible/root")
        );
    }

    #[test]
    fn requested_snapshot_limits_remain_bounded() {
        assert_eq!(snapshot_limits(Some(0), Some(0)), (1, 0));
        assert_eq!(snapshot_limits(Some(10_000), Some(128)), (2_000, 64));
    }

    #[test]
    fn app_discovery_budget_is_independent_of_requested_tree_size() {
        assert_eq!(snapshot_child_read_budgets(1), (256, 2_048, 1));
    }

    #[test]
    fn traversal_attempts_and_queue_share_one_work_budget() {
        let mut traversal = BoundedTraversal::new(4);
        traversal.enqueue([1]);

        assert_eq!(traversal.pop(), Some(1));
        traversal.enqueue(2..=10_000);
        assert_eq!(traversal.queue, VecDeque::from([2, 3, 4]));

        assert_eq!(traversal.pop(), Some(2));
        traversal.enqueue(5..=10_000);
        assert_eq!(traversal.queue, VecDeque::from([3, 4]));
        assert_eq!(traversal.pop(), Some(3));
        assert_eq!(traversal.pop(), Some(4));
        assert_eq!(traversal.pop(), None);
        assert_eq!(traversal.attempted, 4);
        assert!(
            traversal.truncated(),
            "dropped enqueue items must be reported"
        );
    }

    #[test]
    fn traversal_that_drains_within_budget_is_not_truncated() {
        let mut traversal = BoundedTraversal::new(3);
        traversal.enqueue([1, 2, 3]);
        assert_eq!(traversal.pop(), Some(1));
        assert_eq!(traversal.pop(), Some(2));
        assert_eq!(traversal.pop(), Some(3));
        assert_eq!(traversal.pop(), None);
        assert!(
            !traversal.truncated(),
            "exactly max_items real nodes is complete"
        );
    }

    #[test]
    fn enqueue_at_zero_capacity_marks_the_traversal_truncated() {
        let mut traversal = BoundedTraversal::new(2);
        traversal.enqueue([1, 2]);
        assert_eq!(traversal.pop(), Some(1));
        assert_eq!(traversal.pop(), Some(2));
        assert!(!traversal.truncated(), "nothing dropped yet");
        // Capacity is zero; the offered item is dropped, which is the only
        // path that can mark truncation.
        traversal.enqueue([3]);
        assert!(traversal.queue.is_empty());
        assert_eq!(traversal.pop(), None);
        assert!(traversal.truncated());
    }

    #[test]
    fn child_count_is_clamped_before_indexed_reads() {
        assert_eq!(bounded_child_count(-1, 4), 0);
        assert_eq!(bounded_child_count(3, 4), 3);
        assert_eq!(bounded_child_count(i32::MAX, 4), 4);
    }

    #[tokio::test]
    async fn indexed_child_reads_consume_attempts_even_when_one_fails() {
        let calls = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let mut remaining_attempts = 3;
        let batch = fetch_indexed_up_to(100, 10, &mut remaining_attempts, {
            let calls = calls.clone();
            move |index| {
                let calls = calls.clone();
                async move {
                    calls.lock().unwrap().push(index);
                    if index == 1 {
                        Err(())
                    } else {
                        Ok(index)
                    }
                }
            }
        })
        .await;

        assert_eq!(batch.items, vec![0, 2]);
        assert_eq!(batch.attempted, 3);
        assert!(
            batch.incomplete,
            "100 reported children, 3 attempted: budget cut must be reported"
        );
        assert!(!batch.all_failed());
        assert_eq!(*calls.lock().unwrap(), vec![0, 1, 2]);
        assert_eq!(remaining_attempts, 0);

        let no_children = fetch_indexed_up_to(100, 10, &mut remaining_attempts, |_| async {
            Ok::<_, ()>(99)
        })
        .await;
        assert!(no_children.items.is_empty());
        assert_eq!(no_children.attempted, 0);
        assert!(!no_children.all_failed());

        let mut failed_attempts = 2;
        let all_failed =
            fetch_indexed_up_to(2, 2, &mut failed_attempts, |_| async { Err::<i32, _>(()) }).await;
        assert!(all_failed.all_failed());
    }
}