tauri-plugin-background-service 1.0.1

Background service lifecycle plugin for Tauri v2 — run long-lived tasks on Android, iOS, and desktop
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
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
//! Actor-based service manager.
//!
//! The [`manager_loop`] function runs as a single-owner Tokio task that receives
//! [`ManagerCommand`] messages through an `mpsc` channel. This serialises all
//! state mutations (start, stop, is_running) and prevents concurrent interleaving.
//!
//! Most of this module is `pub(crate)` — the public API surface is re-exported
//! from the crate root. Items that are `pub` only for the iOS lifecycle bridge
//! are marked `#[doc(hidden)]`.

use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};

use tauri::{AppHandle, Emitter, Runtime};
use tokio::sync::{mpsc, oneshot};
use tokio_util::sync::CancellationToken;

use crate::desired_state::DesiredStateBackend;
use crate::error::ServiceError;
use crate::models::{
    validate_fg_type_against_allowlist, validate_foreground_service_type, LifecycleMode,
    LifecycleState, LifecycleStatus, PluginEvent, ServiceContext, ServiceState as ServiceLifecycle,
    ServiceStatus, StartConfig, StopReason, ValidationIssue,
};
use crate::notifier::{Notifier, NotifierPolicy, NotifySink};
use crate::service_trait::BackgroundService;

/// Callback fired when the service task completes. Receives `true` on success.
#[doc(hidden)]
pub type OnCompleteCallback = Box<dyn Fn(bool) + Send + Sync>;

/// Abstraction over mobile keepalive operations.
///
/// Defined here (not behind `#[cfg(mobile)]`) so the actor can reference it
/// on all platforms. On desktop, `ServiceState.mobile` is `None` and these
/// methods are never called. On mobile, `MobileLifecycle` implements this trait.
pub(crate) trait MobileKeepalive: Send + Sync {
    /// Start the OS-specific keepalive (Android foreground service / iOS BGTask).
    #[allow(clippy::too_many_arguments)]
    fn start_keepalive(
        &self,
        label: &str,
        foreground_service_type: &str,
        ios_safety_timeout_secs: Option<f64>,
        ios_processing_safety_timeout_secs: Option<f64>,
        ios_earliest_refresh_begin_minutes: Option<f64>,
        ios_earliest_processing_begin_minutes: Option<f64>,
        ios_requires_external_power: Option<bool>,
        ios_requires_network_connectivity: Option<bool>,
        ios_processing_ceiling_multiplier: Option<f64>,
    ) -> Result<(), ServiceError>;
    /// Stop the OS-specific keepalive.
    fn stop_keepalive(&self) -> Result<(), ServiceError>;
    /// Whether a `start_keepalive` failure should be treated as a non-fatal
    /// degraded warning rather than a fatal start rollback (H9).
    ///
    /// `true` on iOS: BGTask scheduling can be unavailable (Simulator /
    /// degraded device) while the in-process Core still runs in the
    /// foreground — so a scheduling failure leaves the service running and
    /// surfaces a "scheduling degraded / foreground-only" status. `false`
    /// (default) on Android/desktop, where a foreground-service denial is a
    /// genuine start failure that must roll back.
    fn scheduling_is_advisory(&self) -> bool {
        false
    }
    /// Query the Android native service state from the Kotlin bridge.
    ///
    /// Returns `None` on non-Android platforms (iOS, desktop). On Android,
    /// returns `Some(AndroidServiceState)` with the native service status or
    /// an error if the bridge call fails.
    fn get_android_service_state(
        &self,
    ) -> Result<Option<crate::models::AndroidServiceState>, ServiceError> {
        Ok(None)
    }
    /// Whether the OS enforces foreground-service *types* (Android only, M5/M6).
    ///
    /// Android returns `true`: the 14 valid types are validated
    /// ([`validate_foreground_service_type`]) and the running service's type can
    /// be swapped (`remoteMessaging` ↔ `phoneCall`) via the native
    /// `updateForegroundServiceType` handler. iOS and desktop return `false` —
    /// neither has an OS foreground-service-type concept, so the type validation
    /// (M6) and the native type-swap (M5) must NOT run there (calling them on iOS
    /// only produced missing-native-method error noise). The real
    /// [`MobileLifecycle`](crate::mobile::MobileLifecycle) override returns
    /// `cfg!(target_os = "android")`; the host mock lets tests simulate each
    /// platform. Default `false` (desktop / no bridge attached).
    fn enforces_foreground_service_type(&self) -> bool {
        false
    }
    /// Swap the foreground service type of the already-running service
    /// (Android only, spec 08 C6 Step 15): `remoteMessaging` → `phoneCall`
    /// on answer and back on end, without restarting the headless core.
    /// Default no-op on non-Android / desktop. The caller additionally gates
    /// this behind [`enforces_foreground_service_type`](Self::enforces_foreground_service_type)
    /// so iOS never reaches the native handler (M5).
    fn update_keepalive_type(&self, _foreground_service_type: &str) -> Result<(), ServiceError> {
        Ok(())
    }
    /// Fire the native incoming-call notification (Android only, spec 08 C6):
    /// `CallStyle` + full-screen intent when granted, ringtone fallback (F4)
    /// otherwise. Default no-op on non-Android / desktop.
    fn show_incoming_call(
        &self,
        _call_id: &str,
        _caller_name: &str,
        _is_video: bool,
    ) -> Result<(), ServiceError> {
        Ok(())
    }
    /// Fire an actionable native message notification. Android implements
    /// content tap, inline reply, and mark-as-read without requiring the
    /// webview. Other platforms no-op unless they add a real native handler.
    #[allow(clippy::too_many_arguments)]
    fn show_message_notification(
        &self,
        _notification_id: i32,
        _chat_id: &str,
        _message_id: &str,
        _title: &str,
        _body: &str,
        _route_uri: &str,
    ) -> Result<(), ServiceError> {
        Ok(())
    }
    /// Cancel the native incoming-call notification (Android only, spec 08 C6).
    fn cancel_incoming_call(&self, _call_id: &str) -> Result<(), ServiceError> {
        Ok(())
    }
    /// Set the active call's device audio route (M-NATIVE-3 / CCF-11, Step 11):
    /// `speaker`/`earpiece`/`bluetooth`/`system`. Android applies it to the live
    /// self-managed `BackgroundCallConnection` via `Connection.setAudioRoute`; iOS via
    /// `AVAudioSession.overrideOutputAudioPort`. Default no-op on non-mobile / desktop.
    fn set_call_audio_route(&self, _call_id: &str, _route: &str) -> Result<(), ServiceError> {
        Ok(())
    }
    /// Open the OS app-settings screen (M-DIAG-2 / CCF-12, Step 17): Android
    /// opens the app-details / permission settings; iOS opens
    /// `UIApplication.openSettingsURLString`. Default no-op on non-mobile / desktop.
    fn open_app_settings(&self) -> Result<(), ServiceError> {
        Ok(())
    }
    /// Mirror the Rust-authoritative desired state into native persistence
    /// (H4 / D1). On iOS this writes `desiredRunning` (+ optional
    /// `last_start_config`) into `UserDefaults` and (re)schedules or cancels
    /// BGTasks so the intent-only recovery commands have a real, observable
    /// effect — never a silent `Ok`. Default no-op on non-iOS / desktop, where
    /// the start/stop keepalive paths (or Kotlin `DurableState`) already own
    /// native desired-state persistence.
    fn mirror_desired_state(
        &self,
        _desired_running: bool,
        _last_start_config: Option<&serde_json::Value>,
    ) -> Result<(), ServiceError> {
        Ok(())
    }
    /// Query the platform-tagged native authority for reconcile + status (H6).
    ///
    /// Default: Android authority via the Kotlin bridge — preserves the
    /// existing behavior for the Android (and desktop/host-mock) path. iOS
    /// overrides this to return an [`NativeAuthority::Ios`] snapshot assembled
    /// from the typed iOS queries, so the status path never round-trips to
    /// `get_android_service_state` on iOS (L4).
    fn query_native_state(&self) -> Result<Option<NativeAuthority>, ServiceError> {
        Ok(self
            .get_android_service_state()?
            .map(NativeAuthority::Android))
    }
    /// Query the iOS native background-task snapshot (H6).
    ///
    /// Returns `None` on non-iOS / desktop. On iOS, assembled from
    /// `getSchedulingStatus` / `getDesiredStateStatus` / `getPendingBgTask`.
    /// Consumed by the real iOS `MobileLifecycle::query_native_state` override
    /// and the host iOS-mock tests; the desktop/Android path uses the
    /// `query_native_state` default instead.
    #[allow(dead_code)]
    fn get_ios_native_state(&self) -> Result<Option<crate::models::IosNativeState>, ServiceError> {
        Ok(None)
    }
}

/// Platform-tagged native authority returned by
/// [`MobileKeepalive::query_native_state`].
///
/// Lets `build_lifecycle_status` / `reconcile_running_with_native` consume the
/// correct native source per platform without the status path calling
/// `get_android_service_state` on iOS (L4): `Android` carries the long-lived
/// foreground-service state; `Ios` carries the BGTask/scheduling snapshot (H6).
#[allow(dead_code)] // `Ios` is constructed only on iOS / in tests.
pub(crate) enum NativeAuthority {
    Android(crate::models::AndroidServiceState),
    Ios(crate::models::IosNativeState),
}

/// Type-erased factory: produces a fresh `Box<dyn BackgroundService<R>>` on demand.
#[doc(hidden)]
pub type ServiceFactory<R> = Box<dyn Fn() -> Box<dyn BackgroundService<R>> + Send + Sync>;

// ─── Commands ───────────────────────────────────────────────────────────

/// Commands sent to the service manager actor.
///
/// Internal implementation detail — not part of the public API.
///
/// This enum is `#[non_exhaustive]` to prevent external construction.
/// Use [`ServiceManagerHandle`] methods instead.
#[non_exhaustive]
pub enum ManagerCommand<R: Runtime> {
    Start {
        config: StartConfig,
        reply: oneshot::Sender<Result<(), ServiceError>>,
        app: AppHandle<R>,
    },
    Stop {
        reply: oneshot::Sender<Result<(), ServiceError>>,
    },
    StopWithReason {
        reason: StopReason,
        reply: oneshot::Sender<Result<(), ServiceError>>,
    },
    /// spec 08 C6 (Step 15): swap the running FGS type (remoteMessaging ↔
    /// phoneCall) without restarting the headless core.
    UpdateForegroundServiceType {
        foreground_service_type: String,
        reply: oneshot::Sender<Result<(), ServiceError>>,
    },
    /// spec 08 C6 (Step 15): fire the native incoming-call notification.
    NotifyIncomingCall {
        call_id: String,
        caller_name: String,
        is_video: bool,
        reply: oneshot::Sender<Result<(), ServiceError>>,
    },
    /// Fire an actionable native message notification.
    NotifyMessage {
        notification_id: i32,
        chat_id: String,
        message_id: String,
        title: String,
        body: String,
        route_uri: String,
        reply: oneshot::Sender<Result<(), ServiceError>>,
    },
    /// spec 08 C6 (Step 15): cancel the native incoming-call notification.
    CancelIncomingCall {
        call_id: String,
        reply: oneshot::Sender<Result<(), ServiceError>>,
    },
    /// M-NATIVE-3 (Step 11): set the active call's device audio route.
    SetCallAudioRoute {
        call_id: String,
        route: String,
        reply: oneshot::Sender<Result<(), ServiceError>>,
    },
    /// M-DIAG-2 (Step 17): open the OS app-settings screen so the user can grant
    /// a denied camera/mic permission.
    OpenAppSettings {
        reply: oneshot::Sender<Result<(), ServiceError>>,
    },
    IsRunning {
        reply: oneshot::Sender<bool>,
    },
    GetState {
        reply: oneshot::Sender<ServiceStatus>,
    },
    SetOnComplete {
        callback: OnCompleteCallback,
    },
    #[allow(dead_code, private_interfaces)]
    SetMobile {
        mobile: Arc<dyn MobileKeepalive>,
    },
    SetDesiredRunning {
        desired: bool,
        config: Option<StartConfig>,
        reply: oneshot::Sender<Result<(), ServiceError>>,
    },
    EnableAutoRestart {
        config: Option<StartConfig>,
        reply: oneshot::Sender<Result<(), ServiceError>>,
    },
    DisableAutoRestart {
        reply: oneshot::Sender<Result<(), ServiceError>>,
    },
    GetDesiredState {
        reply: oneshot::Sender<Option<crate::desired_state::DesiredState>>,
    },
    NativeLifecycleEvent {
        event: crate::models::NativeLifecycleEvent,
        reply: oneshot::Sender<Result<(), ServiceError>>,
    },
    GetLifecycleStatus {
        desktop_mode: Option<String>,
        reply: oneshot::Sender<LifecycleStatus>,
    },
    /// Gracefully drain service-owned state before the host process exits
    /// (BGS-31, doc-08 Step 9). Sent by the headless SIGTERM/SIGINT handler
    /// AFTER `Stop`, so a service override can perform a bounded Core-level
    /// drain instead of the abrupt process-exit `Drop` abort. Appended at the
    /// END of this `#[non_exhaustive]` enum (contract-compliant, non-breaking).
    ShutdownGracefully {
        reply: oneshot::Sender<Result<(), ServiceError>>,
    },
}

// ─── Handle ────────────────────────────────────────────────────────────

/// Handle to the service manager actor. Stored as Tauri managed state.
///
/// Tauri commands send messages through the internal channel; the actor
/// task processes them sequentially, preventing concurrent start/stop
/// interleaving.
pub struct ServiceManagerHandle<R: Runtime> {
    pub(crate) cmd_tx: mpsc::Sender<ManagerCommand<R>>,
}

impl<R: Runtime> ServiceManagerHandle<R> {
    /// Create a new handle backed by the given channel sender.
    pub fn new(cmd_tx: mpsc::Sender<ManagerCommand<R>>) -> Self {
        Self { cmd_tx }
    }

    /// Start a background service.
    ///
    /// Sends a `Start` command to the actor. Returns `AlreadyRunning` if a
    /// service is already active.
    pub async fn start(&self, app: AppHandle<R>, config: StartConfig) -> Result<(), ServiceError> {
        let (reply, rx) = oneshot::channel();
        self.cmd_tx
            .send(ManagerCommand::Start { config, reply, app })
            .await
            .map_err(|_| ServiceError::Runtime("manager actor shut down".into()))?;
        rx.await
            .map_err(|_| ServiceError::Runtime("manager actor dropped reply".into()))?
    }

    /// Stop the running background service.
    ///
    /// Sends a `Stop` command to the actor. Returns `NotRunning` if no
    /// service is active.
    pub async fn stop(&self) -> Result<(), ServiceError> {
        let (reply, rx) = oneshot::channel();
        self.cmd_tx
            .send(ManagerCommand::Stop { reply })
            .await
            .map_err(|_| ServiceError::Runtime("manager actor shut down".into()))?;
        rx.await
            .map_err(|_| ServiceError::Runtime("manager actor dropped reply".into()))?
    }

    /// Swap the foreground service type of the running service (spec 08 C6,
    /// Step 15) — e.g. `remoteMessaging` → `phoneCall` on call answer.
    ///
    /// Validates the type against the Android valid-types list and the plugin
    /// config allowlist, then forwards to the mobile bridge. Returns
    /// `NotRunning` if no service is active. No-op (Ok) on desktop.
    pub async fn update_foreground_service_type(
        &self,
        foreground_service_type: String,
    ) -> Result<(), ServiceError> {
        let (reply, rx) = oneshot::channel();
        self.cmd_tx
            .send(ManagerCommand::UpdateForegroundServiceType {
                foreground_service_type,
                reply,
            })
            .await
            .map_err(|_| ServiceError::Runtime("manager actor shut down".into()))?;
        rx.await
            .map_err(|_| ServiceError::Runtime("manager actor dropped reply".into()))?
    }

    /// Fire the native incoming-call notification (spec 08 C6, Step 15).
    pub async fn notify_incoming_call(
        &self,
        call_id: String,
        caller_name: String,
        is_video: bool,
    ) -> Result<(), ServiceError> {
        let (reply, rx) = oneshot::channel();
        self.cmd_tx
            .send(ManagerCommand::NotifyIncomingCall {
                call_id,
                caller_name,
                is_video,
                reply,
            })
            .await
            .map_err(|_| ServiceError::Runtime("manager actor shut down".into()))?;
        rx.await
            .map_err(|_| ServiceError::Runtime("manager actor dropped reply".into()))?
    }

    /// Fire an actionable native message notification.
    #[allow(clippy::too_many_arguments)]
    pub async fn notify_message(
        &self,
        notification_id: i32,
        chat_id: String,
        message_id: String,
        title: String,
        body: String,
        route_uri: String,
    ) -> Result<(), ServiceError> {
        let (reply, rx) = oneshot::channel();
        self.cmd_tx
            .send(ManagerCommand::NotifyMessage {
                notification_id,
                chat_id,
                message_id,
                title,
                body,
                route_uri,
                reply,
            })
            .await
            .map_err(|_| ServiceError::Runtime("manager actor shut down".into()))?;
        rx.await
            .map_err(|_| ServiceError::Runtime("manager actor dropped reply".into()))?
    }

    /// Cancel the native incoming-call notification (spec 08 C6, Step 15).
    pub async fn cancel_incoming_call(&self, call_id: String) -> Result<(), ServiceError> {
        let (reply, rx) = oneshot::channel();
        self.cmd_tx
            .send(ManagerCommand::CancelIncomingCall { call_id, reply })
            .await
            .map_err(|_| ServiceError::Runtime("manager actor shut down".into()))?;
        rx.await
            .map_err(|_| ServiceError::Runtime("manager actor dropped reply".into()))?
    }

    /// Set the active call's device audio route (M-NATIVE-3 / CCF-11, Step 11).
    pub async fn set_call_audio_route(
        &self,
        call_id: String,
        route: String,
    ) -> Result<(), ServiceError> {
        let (reply, rx) = oneshot::channel();
        self.cmd_tx
            .send(ManagerCommand::SetCallAudioRoute {
                call_id,
                route,
                reply,
            })
            .await
            .map_err(|_| ServiceError::Runtime("manager actor shut down".into()))?;
        rx.await
            .map_err(|_| ServiceError::Runtime("manager actor dropped reply".into()))?
    }

    /// Open the OS app-settings screen (M-DIAG-2 / CCF-12, Step 17) so the user
    /// can grant a denied camera/mic permission. Forwards to the native plugin
    /// (Android settings intent / iOS `openSettingsURLString`); a no-op when no
    /// mobile bridge is attached.
    pub async fn open_app_settings(&self) -> Result<(), ServiceError> {
        let (reply, rx) = oneshot::channel();
        self.cmd_tx
            .send(ManagerCommand::OpenAppSettings { reply })
            .await
            .map_err(|_| ServiceError::Runtime("manager actor shut down".into()))?;
        rx.await
            .map_err(|_| ServiceError::Runtime("manager actor dropped reply".into()))?
    }

    /// Stop the running background service synchronously.
    ///
    /// Uses `blocking_send` so this can be called from synchronous contexts
    /// (e.g., a Tauri `on_event` closure). Returns `NotRunning` if no
    /// service is active.
    pub fn stop_blocking(&self) -> Result<(), ServiceError> {
        let (reply, rx) = oneshot::channel();
        self.cmd_tx
            .blocking_send(ManagerCommand::Stop { reply })
            .map_err(|_| ServiceError::Runtime("manager actor shut down".into()))?;
        rx.blocking_recv()
            .map_err(|_| ServiceError::Runtime("manager actor dropped reply".into()))?
    }

    /// Stop the running background service with a specific reason.
    ///
    /// Applies a reason-based desired-state policy: intentional stops
    /// (UserStop, AppStop, etc.) clear desired state, while platform
    /// errors and timeouts preserve it for auto-restart recovery.
    pub async fn stop_with_reason(&self, reason: StopReason) -> Result<(), ServiceError> {
        let (reply, rx) = oneshot::channel();
        self.cmd_tx
            .send(ManagerCommand::StopWithReason { reason, reply })
            .await
            .map_err(|_| ServiceError::Runtime("manager actor shut down".into()))?;
        rx.await
            .map_err(|_| ServiceError::Runtime("manager actor dropped reply".into()))?
    }

    /// Gracefully drain service-owned state before exit (BGS-31, doc-08 Step 9).
    ///
    /// Sends a `ShutdownGracefully` command that drives the registered
    /// service's [`BackgroundService::shutdown_gracefully`] hook (a bounded
    /// Core-level drain). Intended to be sent AFTER [`stop`](Self::stop) from
    /// the headless SIGTERM/SIGINT handler, so the bookkeeping `Stop` and the
    /// bounded drain both complete before the IPC token is cancelled.
    pub async fn shutdown_gracefully(&self) -> Result<(), ServiceError> {
        let (reply, rx) = oneshot::channel();
        self.cmd_tx
            .send(ManagerCommand::ShutdownGracefully { reply })
            .await
            .map_err(|_| ServiceError::Runtime("manager actor shut down".into()))?;
        rx.await
            .map_err(|_| ServiceError::Runtime("manager actor dropped reply".into()))?
    }

    /// Stop the running background service synchronously with a specific reason.
    ///
    /// Blocking variant of [`ServiceManagerHandle::stop_with_reason`].
    pub fn stop_blocking_with_reason(&self, reason: StopReason) -> Result<(), ServiceError> {
        let (reply, rx) = oneshot::channel();
        self.cmd_tx
            .blocking_send(ManagerCommand::StopWithReason { reason, reply })
            .map_err(|_| ServiceError::Runtime("manager actor shut down".into()))?;
        rx.blocking_recv()
            .map_err(|_| ServiceError::Runtime("manager actor dropped reply".into()))?
    }

    /// Check whether a background service is currently running.
    pub async fn is_running(&self) -> bool {
        let (reply, rx) = oneshot::channel();
        if self
            .cmd_tx
            .send(ManagerCommand::IsRunning { reply })
            .await
            .is_err()
        {
            return false;
        }
        rx.await.unwrap_or(false)
    }

    /// Set the callback fired when the service task completes.
    ///
    /// The callback is captured at spawn time (generation-guarded), so calling
    /// this while a service is running will only affect the *next* start.
    #[doc(hidden)]
    pub async fn set_on_complete(&self, callback: OnCompleteCallback) {
        let _ = self
            .cmd_tx
            .send(ManagerCommand::SetOnComplete { callback })
            .await;
    }

    /// Get the current service lifecycle status.
    pub async fn get_state(&self) -> ServiceStatus {
        let (reply, rx) = oneshot::channel();
        if self
            .cmd_tx
            .send(ManagerCommand::GetState { reply })
            .await
            .is_err()
        {
            return ServiceStatus {
                state: ServiceLifecycle::Idle,
                ..Default::default()
            };
        }
        rx.await.unwrap_or(ServiceStatus {
            state: ServiceLifecycle::Idle,
            ..Default::default()
        })
    }

    /// Send a native lifecycle event to the actor.
    ///
    /// Maps the native event to the appropriate [`StopReason`] and delegates
    /// to [`handle_stop_with_reason`].
    #[doc(hidden)]
    pub async fn send_native_lifecycle_event(
        &self,
        event: crate::models::NativeLifecycleEvent,
    ) -> Result<(), ServiceError> {
        let (reply, rx) = oneshot::channel();
        self.cmd_tx
            .send(ManagerCommand::NativeLifecycleEvent { event, reply })
            .await
            .map_err(|_| ServiceError::Runtime("manager actor shut down".into()))?;
        rx.await
            .map_err(|_| ServiceError::Runtime("manager actor dropped reply".into()))?
    }
}

// ─── Actor State ───────────────────────────────────────────────────────

/// Internal state owned exclusively by the actor task.
struct ServiceState<R: Runtime> {
    /// Fast path: `true` when a service task is active.
    /// Set by `handle_start`, cleared by `handle_stop` or task cleanup.
    /// Avoids acquiring the Mutex for status-only queries.
    is_running: Arc<AtomicBool>,
    /// Cancellation token: `Some` means a service is running.
    /// Shared with the spawned service task via `Arc<Mutex<>>` so it can
    /// clear the slot when the task finishes.
    token: Arc<Mutex<Option<CancellationToken>>>,
    /// Generation counter for the race-condition guard.
    /// Incremented on each start; shared via `Arc<AtomicU64>`.
    generation: Arc<AtomicU64>,
    /// Callback fired once when the service task completes.
    /// Captured via `take()` at spawn time so a new callback can be set
    /// for the next start.
    on_complete: Option<OnCompleteCallback>,
    /// Factory that creates fresh service instances.
    factory: ServiceFactory<R>,
    /// Mobile keepalive handle. Set via `SetMobile` command on mobile platforms.
    mobile: Option<Arc<dyn MobileKeepalive>>,
    /// Last `AppHandle` provided by a `Start` command.
    /// Used for event emission during merge (degraded-state detection).
    app: Option<AppHandle<R>>,
    /// iOS safety timeout in seconds (from PluginConfig, default 28.0).
    /// Passed to mobile via `start_keepalive`. Android ignores this field.
    ios_safety_timeout_secs: f64,
    /// iOS BGProcessingTask safety timeout in seconds (from PluginConfig, default 0.0).
    /// When > 0.0, caps processing task duration. Passed as `Some(value)` to mobile.
    /// When 0.0, passed as `None` (no cap).
    ios_processing_safety_timeout_secs: f64,
    /// iOS BGAppRefreshTask earliest begin date in minutes (default 15.0).
    ios_earliest_refresh_begin_minutes: f64,
    /// iOS BGProcessingTask earliest begin date in minutes (default 15.0).
    ios_earliest_processing_begin_minutes: f64,
    /// iOS BGProcessingTask requires external power (default false).
    ios_requires_external_power: bool,
    /// iOS BGProcessingTask requires network connectivity (default false).
    ios_requires_network_connectivity: bool,
    /// iOS adaptive processing ceiling multiplier (default 4.0).
    /// Bounds the Swift adaptive scheduler's back-off for the processing task.
    ios_processing_ceiling_multiplier: f64,
    /// Current lifecycle state of the service.
    /// Shared with spawned task for transitions (Initializing→Running→Stopped).
    lifecycle_state: Arc<Mutex<ServiceLifecycle>>,
    /// Last error message from init/run failure.
    /// Shared with spawned task for error capture.
    last_error: Arc<Mutex<Option<String>>>,
    /// Set by `handle_start` when an *advisory* (iOS BGTask) `start_keepalive`
    /// fails: the Core keeps running in the foreground but background scheduling
    /// is unavailable. Surfaced by `build_lifecycle_status` as a distinct
    /// "scheduling degraded / foreground-only" status (H9). Cleared on the next
    /// start attempt and on stop.
    scheduling_degraded: Arc<Mutex<Option<String>>>,
    /// CORE-01: terminal reason slot, scoped to the current generation.
    /// Set by `handle_stop_with_reason` BEFORE `token.cancel()` so the
    /// spawned cleanup path can emit `PluginEvent::Stopped { reason }` with
    /// the user-meaningful reason (UserStop, PlatformTimeout, ...) instead of
    /// always emitting `TaskCompleted`. Cleared on every `handle_start`.
    /// Read under the generation guard so a stale task cannot stomp a newer
    /// generation's reason. Stored as `(generation, reason)` so a stale task
    /// whose generation has been cleared by a newer start still sees its OWN
    /// reason and not None (which would wrongly fall through to natural
    /// completion).
    terminal_reason: Arc<Mutex<Option<(u64, StopReason)>>>,
    /// Desired-state persistence backend.
    /// `None` on platforms that haven't set one up yet.
    desired_state: Option<Arc<dyn DesiredStateBackend>>,
    /// Current platform's lifecycle mode (FGS, BGTask, in-process, OS-service).
    lifecycle_mode: LifecycleMode,
    /// Android foreground service types allowed by plugin config.
    /// Used by `handle_start` to validate before calling mobile start.
    android_fg_service_types: Vec<String>,
    /// Whether to validate the requested foreground service type against
    /// `android_fg_service_types` before starting the native service.
    android_validate_fg_type: bool,
    /// Which lifecycle notifications are enabled, derived from PluginConfig
    /// per DEC-002 (Android suppression). Default: everything off.
    notifier_policy: NotifierPolicy,
    /// Notification dispatch seam. `None` when no notification-capable
    /// app handle is available (headless daemon, tests without a sink).
    notify_sink: Option<Arc<dyn NotifySink>>,
}

// ─── Actor Loop ────────────────────────────────────────────────────────

/// Main actor loop: receives commands and dispatches to handlers.
///
/// Runs as a spawned Tokio task. The loop exits when all `Sender` halves
/// are dropped (i.e., the handle is dropped).
#[doc(hidden)]
#[allow(clippy::too_many_arguments)]
pub async fn manager_loop<R: Runtime>(
    mut rx: mpsc::Receiver<ManagerCommand<R>>,
    factory: ServiceFactory<R>,
    // iOS safety timeout in seconds. From PluginConfig.
    // Default: 28.0 (Apple recommends keeping BG tasks under ~30s).
    // Passed to mobile via actor's `start_keepalive` call.
    ios_safety_timeout_secs: f64,
    // iOS BGProcessingTask safety timeout in seconds. From PluginConfig.
    // Default: 0.0 (no cap). When > 0.0, passed as Some(value) to mobile.
    ios_processing_safety_timeout_secs: f64,
    // iOS BGAppRefreshTask earliest begin date in minutes. From PluginConfig.
    ios_earliest_refresh_begin_minutes: f64,
    // iOS BGProcessingTask earliest begin date in minutes. From PluginConfig.
    ios_earliest_processing_begin_minutes: f64,
    // iOS BGProcessingTask requires external power. From PluginConfig.
    ios_requires_external_power: bool,
    // iOS BGProcessingTask requires network connectivity. From PluginConfig.
    ios_requires_network_connectivity: bool,
    // iOS adaptive processing ceiling multiplier. From PluginConfig.
    // Default: 4.0. Bounds the Swift adaptive scheduler's back-off.
    ios_processing_ceiling_multiplier: f64,
    // Desired-state persistence backend. None if not configured.
    desired_state_backend: Option<Arc<dyn DesiredStateBackend>>,
    // Android foreground service type allowlist from PluginConfig.
    android_fg_service_types: Vec<String>,
    // Whether to validate foreground service type against the allowlist.
    android_validate_fg_type: bool,
    // Lifecycle-notification policy derived from PluginConfig (D1, DEC-002).
    // Default: everything off.
    notifier_policy: NotifierPolicy,
    // Notification dispatch seam. None if no notification-capable app
    // handle exists at spawn (headless daemon, tests without a sink).
    notify_sink: Option<Arc<dyn NotifySink>>,
    // BGS-05 Leg B: an optional AppHandle for boot Start-replay. When `Some`
    // AND desktop lifecycle mode AND the persisted desired-state says
    // `desired_running`, the loop replays a `Start` on entry via `handle_start`
    // (the SAME path a runtime `ManagerCommand::Start` takes — minus the IPC
    // reply). `None` for GUI in-process + IPC-client callers (no boot-replay).
    boot_app: Option<AppHandle<R>>,
    // BGS-05 re-fix (Critic Blocker 2 — Leg A/Leg B coordination): the boot
    // Start-replay fires ONLY when the host app's consent policy allows
    // auto-unlock (`consent.enabled && consent.auto_unlock`, computed LIVE in
    // `run_headless` and threaded through `headless_main_with_desired_state`).
    // Before this, the replay guard was `desired_running`-ONLY — consent-blind —
    // so consent OFF + credential on disk + `desired_running=true` replayed a
    // Start that reached the (then consent-UN-aware) `start_headless_core` and
    // unlocked unattended. This is belt-and-suspenders alongside F3 (the
    // load-bearing builder gate in `start_headless_core`): `false` here simply
    // suppresses the spurious replay; F3 LIVE-reads consent regardless. GUI
    // in-process + IPC-client callers pass `false` (they set `boot_app = None`
    // so the replay short-circuits anyway).
    consent_allows_auto_unlock: bool,
) {
    let lifecycle_mode = {
        #[cfg(target_os = "android")]
        {
            LifecycleMode::AndroidForegroundService
        }
        #[cfg(target_os = "ios")]
        {
            LifecycleMode::IosBgTaskScheduler
        }
        #[cfg(not(any(target_os = "android", target_os = "ios")))]
        {
            LifecycleMode::DesktopInProcess
        }
    };

    let mut state = ServiceState {
        is_running: Arc::new(AtomicBool::new(false)),
        token: Arc::new(Mutex::new(None)),
        generation: Arc::new(AtomicU64::new(0)),
        on_complete: None,
        factory,
        mobile: None,
        app: None,
        ios_safety_timeout_secs,
        ios_processing_safety_timeout_secs,
        ios_earliest_refresh_begin_minutes,
        ios_earliest_processing_begin_minutes,
        ios_requires_external_power,
        ios_requires_network_connectivity,
        ios_processing_ceiling_multiplier,
        lifecycle_state: Arc::new(Mutex::new(ServiceLifecycle::Idle)),
        last_error: Arc::new(Mutex::new(None)),
        scheduling_degraded: Arc::new(Mutex::new(None)),
        terminal_reason: Arc::new(Mutex::new(None)),
        desired_state: desired_state_backend,
        lifecycle_mode,
        android_fg_service_types,
        android_validate_fg_type,
        notifier_policy,
        notify_sink,
    };

    // BGS-05 Leg B: replay a Start on boot if the user last left the service
    // desired-running (desktop only; Android/iOS use their own native resubmit
    // at the platform layer). The dispatch IS `handle_start`, the same path a
    // runtime `ManagerCommand::Start` takes.
    //
    // BGS-05 re-fix (Critic Blocker 2): the replay is ALSO gated on
    // `consent_allows_auto_unlock` (threaded LIVE from `run_headless`'s consent
    // read) — consent OFF ⇒ no replay ⇒ no boot-reachable Start. The original
    // guard was `desired_running`-only (consent-blind), which combined with the
    // then-ungated `start_headless_core` unlocked the daemon unattended with
    // consent OFF. F3 (`start_headless_core`'s LIVE consent gate) is the
    // load-bearing backstop; this coordination suppresses the spurious replay
    // and keeps Leg A (boot_restore_core) + Leg B (this replay) acting on the
    // SAME consent decision.
    if matches!(
        state.lifecycle_mode,
        LifecycleMode::DesktopInProcess | LifecycleMode::DesktopOsService
    ) && boot_app.is_some()
        && consent_allows_auto_unlock
    {
        if let Some(ref backend) = state.desired_state {
            if let Ok(ds) = backend.load() {
                if should_replay_on_boot(&ds) {
                    if let Some(app) = boot_app.as_ref() {
                        let config_result = ds
                            .last_start_config
                            .as_ref()
                            .map(|v| serde_json::from_value::<StartConfig>(v.clone()));
                        match config_result {
                            None => {
                                // CORE-05: no last_start_config persisted —
                                // nothing to replay. This is the expected
                                // state on a fresh install; no diagnostic.
                            }
                            Some(Ok(config)) => match handle_start(&mut state, app.clone(), config)
                            {
                                Ok(()) => {
                                    log::info!(
                                        "BGS-05: replayed Start on boot (desired_running=true)"
                                    );
                                }
                                Err(e) => {
                                    log::warn!("BGS-05: boot Start-replay failed: {e}");
                                }
                            },
                            // CORE-05: a malformed persisted `last_start_config`
                            // was previously swallowed silently via `.ok()`. Now
                            // surface a diagnostic so the operator can see that
                            // boot replay was attempted and skipped due to a
                            // corrupted StartConfig rather than failing invisibly.
                            Some(Err(e)) => {
                                log::warn!(
                                    "BGS-05: boot Start-replay skipped — \
                                     malformed persisted last_start_config: {e}"
                                );
                            }
                        }
                    }
                }
            }
        }
    }

    while let Some(cmd) = rx.recv().await {
        match cmd {
            ManagerCommand::Start { config, reply, app } => {
                let _ = reply.send(handle_start(&mut state, app, config));
            }
            ManagerCommand::Stop { reply } => {
                let _ = reply.send(handle_stop(&mut state));
            }
            ManagerCommand::StopWithReason { reason, reply } => {
                let _ = reply.send(handle_stop_with_reason(&mut state, reason));
            }
            ManagerCommand::ShutdownGracefully { reply } => {
                // BGS-31 (doc-08 Step 9): bounded Core-level drain driven from
                // the SIGTERM/SIGINT handler. The service override reaches
                // process-wide state (the host app core) through `ctx.app`; the
                // running service task is owned by a spawned task and is not
                // reachable here, so `handle_shutdown_gracefully` constructs a
                // fresh service via the factory + a context from the last
                // `AppHandle` and invokes the hook on it.
                let result = handle_shutdown_gracefully(&mut state).await;
                let _ = reply.send(result);
            }
            ManagerCommand::UpdateForegroundServiceType {
                foreground_service_type,
                reply,
            } => {
                let _ = reply.send(handle_update_foreground_service_type(
                    &mut state,
                    foreground_service_type,
                ));
            }
            ManagerCommand::NotifyIncomingCall {
                call_id,
                caller_name,
                is_video,
                reply,
            } => {
                let _ = reply.send(handle_notify_incoming_call(
                    &state,
                    call_id,
                    caller_name,
                    is_video,
                ));
            }
            ManagerCommand::NotifyMessage {
                notification_id,
                chat_id,
                message_id,
                title,
                body,
                route_uri,
                reply,
            } => {
                let _ = reply.send(handle_notify_message(
                    &state,
                    notification_id,
                    chat_id,
                    message_id,
                    title,
                    body,
                    route_uri,
                ));
            }
            ManagerCommand::CancelIncomingCall { call_id, reply } => {
                let _ = reply.send(handle_cancel_incoming_call(&state, call_id));
            }
            ManagerCommand::SetCallAudioRoute {
                call_id,
                route,
                reply,
            } => {
                let _ = reply.send(handle_set_call_audio_route(&state, call_id, route));
            }
            ManagerCommand::OpenAppSettings { reply } => {
                let _ = reply.send(handle_open_app_settings(&state));
            }
            ManagerCommand::IsRunning { reply } => {
                // Native `LifecycleService.isRunning` is the single source of
                // truth (R-W1.4): reconcile the actor's belief before reporting
                // so a stop/timeout with the UI closed can never surface a stale
                // "running" (closes the split-brain window — harness Scenario 8).
                let _ = reply.send(reconcile_running_with_native(&state));
            }
            ManagerCommand::SetOnComplete { callback } => {
                state.on_complete = Some(callback);
            }
            ManagerCommand::SetMobile { mobile } => {
                state.mobile = Some(mobile);
            }
            ManagerCommand::GetState { reply } => {
                let mut status = ServiceStatus {
                    state: *state.lifecycle_state.lock().unwrap(),
                    last_error: state.last_error.lock().unwrap().clone(),
                    platform_mode: Some(state.lifecycle_mode),
                    ..Default::default()
                };

                if let Some(ref backend) = state.desired_state {
                    if let Ok(ds) = backend.load() {
                        status.desired_running = Some(ds.desired_running);
                        status.native_state = ds
                            .last_native_state
                            .as_deref()
                            .and_then(|s| serde_json::from_str(&format!("\"{s}\"")).ok());
                        status.last_start_config = ds
                            .last_start_config
                            .and_then(|v| serde_json::from_value(v).ok());
                        status.last_heartbeat_at = ds.last_heartbeat_epoch_ms;
                        status.restart_attempt = if ds.restart_attempt > 0 {
                            Some(ds.restart_attempt)
                        } else {
                            None
                        };
                        status.recovery_reason = ds.recovery_reason;
                        status.platform_error = ds.last_platform_error;
                    }
                }

                let _ = reply.send(status);
            }
            ManagerCommand::SetDesiredRunning {
                desired,
                config,
                reply,
            } => {
                let _ = reply.send(handle_set_desired_running(&mut state, desired, config));
            }
            ManagerCommand::EnableAutoRestart { config, reply } => {
                let _ = reply.send(handle_enable_auto_restart(&mut state, config));
            }
            ManagerCommand::DisableAutoRestart { reply } => {
                let _ = reply.send(handle_disable_auto_restart(&mut state));
            }
            ManagerCommand::GetDesiredState { reply } => {
                let _ = reply.send(handle_get_desired_state(&state));
            }
            ManagerCommand::NativeLifecycleEvent { event, reply } => {
                let _ = reply.send(handle_native_lifecycle_event(&mut state, event));
            }
            ManagerCommand::GetLifecycleStatus {
                desktop_mode,
                reply,
            } => {
                let _ = reply.send(build_lifecycle_status(&state, desktop_mode.as_deref()));
            }
        }
    }
}

// ─── Command Handlers ──────────────────────────────────────────────────

/// Handle a `Start` command.
///
/// Order of operations (critical for the race-condition fix):
/// 1. Check `AlreadyRunning` — reject early, no side-effects.
/// 2. Create token, increment generation.
/// 3. Start mobile keepalive (AFTER AlreadyRunning check).
///    On failure: rollback token and callback, return error.
/// 4. Spawn service task (init -> run -> cleanup).
fn handle_start<R: Runtime>(
    state: &mut ServiceState<R>,
    app: AppHandle<R>,
    config: StartConfig,
) -> Result<(), ServiceError> {
    log::info!("handle_start: entry (label={})", config.service_label);

    let mut guard = state.token.lock().unwrap();

    // CORE-05: `state.app` MUST be assigned only after the AlreadyRunning and
    // validation guards succeed. Previously this ran unconditionally on entry,
    // so a rejected `AlreadyRunning` start (or a validation-rejected start)
    // overwrote the previously-stored `AppHandle`, leaking the old handle's
    // event subscribers.
    if guard.is_some() {
        return Err(ServiceError::AlreadyRunning);
    }

    // Validate foreground service type against the 14 valid Android types.
    // Only relevant where the OS enforces foreground-service types — i.e.
    // Android (M6). iOS has no FGS-type concept, and on desktop the type is
    // ignored (no OS enforcement mechanism), so both skip this. Gated through
    // the bridge so the decision is platform-accurate and host-testable.
    if state
        .mobile
        .as_ref()
        .is_some_and(|m| m.enforces_foreground_service_type())
    {
        validate_foreground_service_type(&config.foreground_service_type)?;
    }

    // Validate against plugin config allowlist (all platforms).
    // This is the user-configured restriction: even if a type is valid
    // (one of the 14 Android types), it must also be in the plugin's
    // android_foreground_service_types list.
    validate_fg_type_against_allowlist(
        &config.foreground_service_type,
        &state.android_fg_service_types,
        state.android_validate_fg_type,
    )?;

    // Guards passed — now it is safe to remember the app handle for this
    // generation's event emission.
    state.app = Some(app.clone());

    let token = CancellationToken::new();
    let shutdown = token.clone();
    *guard = Some(token);
    let my_gen = state.generation.fetch_add(1, Ordering::Release) + 1;
    state.is_running.store(true, Ordering::SeqCst);
    *state.lifecycle_state.lock().unwrap() = ServiceLifecycle::Initializing;
    *state.last_error.lock().unwrap() = None;
    // Clear any prior advisory scheduling-degraded marker for this fresh start.
    *state.scheduling_degraded.lock().unwrap() = None;
    // CORE-01: the terminal_reason slot is generation-tagged, so a newer
    // start does NOT need to clear it — stale entries simply do not match
    // the new generation's cleanup read. Clearing would race an in-flight
    // stale task's emit (the new start lands between the old task's
    // shutdown.cancelled() wake and its terminal_reason read).

    drop(guard);

    // Capture on_complete at spawn time (generation-guarded).
    // Takes the callback out of the slot so a new start can set a fresh one.
    let captured_callback = state.on_complete.take();

    // Start mobile keepalive AFTER AlreadyRunning check.
    //
    // On Android/desktop a keepalive failure is fatal: rollback (clear token,
    // restore callback) and propagate the error.
    //
    // On iOS (H9), BGTask scheduling is *advisory* — it can be unavailable on
    // the Simulator / a degraded device while the in-process Core still runs in
    // the foreground. There a failure must NOT roll back the service: record a
    // distinct "scheduling degraded / foreground-only" marker, emit a non-fatal
    // warning, and fall through to spawn the Core anyway.

    if let Some(ref mobile) = state.mobile {
        let processing_timeout = if state.ios_processing_safety_timeout_secs > 0.0 {
            Some(state.ios_processing_safety_timeout_secs)
        } else {
            None
        };
        if let Err(e) = mobile.start_keepalive(
            &config.service_label,
            &config.foreground_service_type,
            Some(state.ios_safety_timeout_secs),
            processing_timeout,
            Some(state.ios_earliest_refresh_begin_minutes),
            Some(state.ios_earliest_processing_begin_minutes),
            Some(state.ios_requires_external_power),
            Some(state.ios_requires_network_connectivity),
            Some(state.ios_processing_ceiling_multiplier),
        ) {
            if mobile.scheduling_is_advisory() {
                // Non-fatal: the Core still starts in the foreground; only
                // background scheduling is degraded.
                log::warn!(
                    "start_keepalive: advisory scheduling unavailable ({e}); \
                     starting Core foreground-only (degraded)"
                );
                *state.scheduling_degraded.lock().unwrap() = Some(e.to_string());
                let _ = app.emit(
                    "background-service:state-degraded",
                    serde_json::json!({
                        "degraded": true,
                        "reason": "scheduling_degraded_foreground_only",
                        "error": e.to_string(),
                    }),
                );
                // Fall through: do NOT roll back.
            } else {
                // Rollback: clear the token we just set.
                state.token.lock().unwrap().take();
                state.is_running.store(false, Ordering::SeqCst);
                *state.lifecycle_state.lock().unwrap() = ServiceLifecycle::Idle;
                // Rollback: restore the callback we took.
                state.on_complete = captured_callback;
                return Err(e);
            }
        }
    }

    // Shared refs for the spawned task's cleanup logic.
    let token_ref = state.token.clone();
    let gen_ref = state.generation.clone();
    let is_running_ref = state.is_running.clone();
    let lifecycle_ref = state.lifecycle_state.clone();
    let last_error_ref = state.last_error.clone();
    // CORE-01: shared terminal-reason slot. Read under the generation guard
    // so a stale task cannot emit a reason set by a newer generation's stop.
    let terminal_reason_ref = state.terminal_reason.clone();
    // CORE-01: desired-state backend and mobile bridge are needed in the
    // cleanup path so natural completion can clear persisted desired intent
    // (mirroring `handle_stop_with_reason`'s `should_clear_desired_state`
    // branch) without bouncing a message back through the actor.
    let desired_state_ref = state.desired_state.clone();
    let mobile_ref = state.mobile.clone();
    let lifecycle_mode_ref = state.lifecycle_mode;

    let mut service = (state.factory)();

    let ctx = ServiceContext {
        notifier: Notifier { app: app.clone() },
        app: app.clone(),
        shutdown,
        #[cfg(mobile)]
        service_label: config.service_label.clone(),
        #[cfg(mobile)]
        foreground_service_type: config.foreground_service_type.clone(),
    };

    // Use tauri::async_runtime::spawn() instead of tokio::spawn() because
    // the plugin setup closure may run before a Tokio runtime context is
    // entered on the current thread (e.g. Android auto-start in setup).
    tauri::async_runtime::spawn(async move {
        // Phase 1: init
        if let Err(e) = service.init(&ctx).await {
            let _ = app.emit(
                "background-service://event",
                PluginEvent::Error {
                    message: e.to_string(),
                },
            );
            // Clear token only if generation hasn't advanced. Hold the token
            // lock across the generation check so a concurrent handle_start —
            // which bumps the generation while holding this same lock — cannot
            // have its freshly installed token taken by this stale task.
            {
                let mut tok = token_ref.lock().unwrap();
                if gen_ref.load(Ordering::Acquire) == my_gen {
                    tok.take();
                    is_running_ref.store(false, Ordering::SeqCst);
                    // Initializing → Stopped on init failure.
                    {
                        let mut lc = lifecycle_ref.lock().unwrap();
                        if *lc == ServiceLifecycle::Initializing {
                            *lc = ServiceLifecycle::Stopped;
                        }
                    }
                    *last_error_ref.lock().unwrap() = Some(e.to_string());
                }
            }
            // Fire callback with false on init failure.
            if let Some(cb) = captured_callback {
                cb(false);
            }
            return;
        }

        // Initializing → Running after successful init (generation + state guarded).
        if gen_ref.load(Ordering::Acquire) == my_gen {
            let mut lc = lifecycle_ref.lock().unwrap();
            if *lc == ServiceLifecycle::Initializing {
                *lc = ServiceLifecycle::Running;
            }
        }

        // Emit Started
        let _ = app.emit("background-service://event", PluginEvent::Started);

        // Phase 2: run
        let result = service.run(&ctx).await;

        // CORE-01: determine the terminal reason for THIS generation. Read
        // `terminal_reason_ref` under the generation guard so a stale task
        // cannot pick up a reason set by a newer generation's stop. An
        // explicit reason (set by `handle_stop_with_reason` before
        // `token.cancel()`) wins; the inline Ok/Err classification is the
        // fallback for natural completion / unprompted error.
        let explicit_reason: Option<StopReason> = {
            let tr = terminal_reason_ref.lock().unwrap();
            // CORE-01: read the terminal reason only if it was set for THIS
            // generation. A newer start bumps generation and clears the slot,
            // but the tuple-tagged storage means a stale task whose
            // generation has been cleared still finds its OWN reason here
            // (matches my_gen) rather than falling through to natural
            // completion.
            tr.and_then(|(gen, reason)| if gen == my_gen { Some(reason) } else { None })
        };

        // Emit terminal event exactly once. Explicit stop reason always
        // surfaces as `Stopped{reason}` — even if the cooperative shutdown
        // returned an Err, the user-meaningful reason is the explicit stop,
        // not an internal error from the cancelled task.
        if let Some(r) = explicit_reason {
            // Explicit stop reason always wins, even when the cooperative
            // shutdown returned an Err. The user-meaningful reason is the
            // explicit stop, not an internal error from the cancelled task.
            let _ = app.emit(
                "background-service://event",
                PluginEvent::Stopped { reason: r },
            );
        } else {
            // Natural completion / unprompted error classification.
            match &result {
                Ok(()) => {
                    let _ = app.emit(
                        "background-service://event",
                        PluginEvent::Stopped {
                            reason: StopReason::TaskCompleted,
                        },
                    );
                }
                Err(e) => {
                    let _ = app.emit(
                        "background-service://event",
                        PluginEvent::Error {
                            message: e.to_string(),
                        },
                    );
                }
            }
        }

        // CORE-01: natural completion clears persisted/native desired intent
        // (mirroring `handle_stop_with_reason`'s `should_clear_desired_state
        // (TaskCompleted)` branch). Unprompted error PRESERVES desired state
        // so recovery can resume. Explicit-reason clears/preserves were
        // already handled by `handle_stop_with_reason` before cancel(); do
        // not double-write here.
        if explicit_reason.is_none() && result.is_ok() {
            save_desired_running_via(
                &desired_state_ref,
                &mobile_ref,
                lifecycle_mode_ref,
                false,
                None,
            );
        }
        // Err path: leave desired_running alone (recovery may resume).

        // Fire on_complete callback (captured at spawn time).
        // MUST fire before clearing the token so that
        // `wait_until_stopped` only returns after the callback ran.
        if let Some(cb) = captured_callback {
            cb(result.is_ok());
        }

        // Clear token only if generation hasn't advanced. Hold the token lock
        // across the generation check so a concurrent handle_start — which bumps
        // the generation while holding this same lock — cannot have its freshly
        // installed token taken by this stale task. Without this, a restart that
        // races this cleanup loses its token and the next stop sees NotRunning.
        {
            let mut tok = token_ref.lock().unwrap();
            if gen_ref.load(Ordering::Acquire) == my_gen {
                tok.take();
                is_running_ref.store(false, Ordering::SeqCst);
                // → Stopped on run completion (generation guarded).
                {
                    let mut lc = lifecycle_ref.lock().unwrap();
                    if matches!(
                        *lc,
                        ServiceLifecycle::Initializing | ServiceLifecycle::Running
                    ) {
                        *lc = ServiceLifecycle::Stopped;
                    }
                }
                if let Err(e) = &result {
                    *last_error_ref.lock().unwrap() = Some(e.to_string());
                }
            }
        }
    });

    // Persist desired_running=true after successful start.
    save_desired_running(state, true, Some(&config));

    Ok(())
}

/// Handle a `Stop` command.
///
/// Takes the token from state and cancels it, then stops mobile keepalive.
/// Returns `NotRunning` if no service is active.
fn handle_stop<R: Runtime>(state: &mut ServiceState<R>) -> Result<(), ServiceError> {
    handle_stop_with_reason(state, StopReason::UserStop)
}

/// Handle a `ShutdownGracefully` command (BGS-31, doc-08 Step 9).
///
/// Builds a fresh service instance via the factory + a [`ServiceContext`] from
/// the last `AppHandle` provided to `Start`, and invokes the service's
/// [`BackgroundService::shutdown_gracefully`] hook. The running service task is
/// owned by a spawned task and is not reachable from the actor loop; the hook
/// is intentionally STATELESS w.r.t. the instance — an override reaches
/// process-wide state (the host app core) through `ctx.app.state::<AppState>()`,
/// so invoking it on a fresh factory instance is equivalent to invoking it on
/// the running one.
///
/// Tolerates Core-absent / no-app: `state.app` is `None` until a `Start`
/// supplies an `AppHandle`, and the headless daemon's `AppState` is locked at
/// boot. If no `AppHandle` is available there is nothing to drain, so this
/// returns `Ok(())` (never panics). This is the bounded-drain path; it does
/// NOT reshape `Core::drop`.
async fn handle_shutdown_gracefully<R: Runtime>(
    state: &mut ServiceState<R>,
) -> Result<(), ServiceError> {
    let Some(app) = state.app.clone() else {
        // No AppHandle ever provided (no Start happened): nothing to drain.
        return Ok(());
    };
    let mut service = (state.factory)();
    let ctx = ServiceContext {
        notifier: Notifier { app: app.clone() },
        app,
        shutdown: CancellationToken::new(),
        #[cfg(mobile)]
        service_label: String::new(),
        #[cfg(mobile)]
        foreground_service_type: String::new(),
    };
    service.shutdown_gracefully(&ctx).await
}

/// Handle a `StopWithReason` command.
fn handle_stop_with_reason<R: Runtime>(
    state: &mut ServiceState<R>,
    reason: StopReason,
) -> Result<(), ServiceError> {
    let mut guard = state.token.lock().unwrap();
    match guard.take() {
        Some(token) => {
            // CORE-01: record the explicit stop reason for this generation
            // BEFORE cancelling the token. The spawned task's cleanup reads
            // this under the generation guard and emits
            // `PluginEvent::Stopped { reason }` with this reason instead of
            // the inline `TaskCompleted`/`Error` classification. Explicit
            // reason wins; the cleanup path's own Ok/Err branch is only used
            // when no explicit reason was set (natural completion or
            // unprompted error).
            *state.terminal_reason.lock().unwrap() =
                Some((state.generation.load(Ordering::Acquire), reason));
            token.cancel();
            state.is_running.store(false, Ordering::SeqCst);
            *state.lifecycle_state.lock().unwrap() = ServiceLifecycle::Stopped;
            *state.last_error.lock().unwrap() = None;
            // Clear any advisory scheduling-degraded marker (H9): once stopped,
            // foreground-only degradation no longer applies.
            *state.scheduling_degraded.lock().unwrap() = None;
            drop(guard);
            if should_stop_keepalive(reason) {
                if let Some(ref mobile) = state.mobile {
                    if let Err(e) = mobile.stop_keepalive() {
                        log::warn!("stop_keepalive failed: {e}");
                    }
                }
            }
            if should_clear_desired_state(reason) {
                save_desired_running(state, false, None);
            } else if should_reconcile_resubmit(reason) {
                // M13 reconcile: a cancel-listener PlatformTimeout paused the
                // service but `desired_running` survives. Surface the degraded
                // state and re-submit native scheduling (on iOS this reschedules
                // the BGTask) so background delivery resumes instead of silently
                // dying. No-op on desktop / when desired_running is false.
                if let Some(ds) = state.desired_state.as_ref().and_then(|b| b.load().ok()) {
                    if ds.desired_running {
                        log::warn!(
                            "background service degraded after platform timeout; \
                             desired_running=true — re-submitting native scheduling"
                        );
                        let config: Option<StartConfig> = ds
                            .last_start_config
                            .as_ref()
                            .and_then(|v| serde_json::from_value(v.clone()).ok());
                        mirror_desired_to_native(state, true, config.as_ref());
                    }
                }
            }
            // D1 timeout fire point: policy gate first, then the sink.
            if state.notifier_policy.on_timeout && should_notify_timeout(reason) {
                if let Some(ref sink) = state.notify_sink {
                    sink.notify(
                        "bg-timeout",
                        "Background service paused",
                        "The OS paused background delivery; it will resume automatically.",
                    );
                }
            }
            Ok(())
        }
        None => Err(ServiceError::NotRunning),
    }
}

/// Handle `UpdateForegroundServiceType` (spec 08 C6, Step 15).
///
/// Validates the type against the Android valid-types list (mobile) and the
/// plugin config allowlist (all platforms), then forwards to the mobile bridge
/// to swap the running FGS type (e.g. `remoteMessaging` → `phoneCall`) without
/// restarting the headless core. Returns `NotRunning` if no service is active.
fn handle_update_foreground_service_type<R: Runtime>(
    state: &mut ServiceState<R>,
    foreground_service_type: String,
) -> Result<(), ServiceError> {
    let running = state.token.lock().unwrap().is_some();
    if !running {
        return Err(ServiceError::NotRunning);
    }
    // Mirror handle_start's validation ordering. The 14-type validation and the
    // native type-swap are Android-only (M5/M6): iOS has no FGS-type concept, so
    // neither runs there. The plugin-config allowlist check stays all-platform.
    let enforces = state
        .mobile
        .as_ref()
        .is_some_and(|m| m.enforces_foreground_service_type());
    if enforces {
        validate_foreground_service_type(&foreground_service_type)?;
    }
    validate_fg_type_against_allowlist(
        &foreground_service_type,
        &state.android_fg_service_types,
        state.android_validate_fg_type,
    )?;
    if enforces {
        if let Some(ref mobile) = state.mobile {
            // The token stays; only the FGS *type* swaps.
            mobile.update_keepalive_type(&foreground_service_type)?;
        }
    }
    Ok(())
}

/// Handle `NotifyIncomingCall` (spec 08 C6, Step 15): fire the native
/// incoming-call notification. No-op (Ok) when no mobile bridge is attached.
fn handle_notify_incoming_call<R: Runtime>(
    state: &ServiceState<R>,
    call_id: String,
    caller_name: String,
    is_video: bool,
) -> Result<(), ServiceError> {
    if let Some(ref mobile) = state.mobile {
        mobile.show_incoming_call(&call_id, &caller_name, is_video)?;
    }
    Ok(())
}

/// Handle `NotifyMessage`: fire an actionable native message notification. No-op
/// when no mobile bridge is attached.
#[allow(clippy::too_many_arguments)]
fn handle_notify_message<R: Runtime>(
    state: &ServiceState<R>,
    notification_id: i32,
    chat_id: String,
    message_id: String,
    title: String,
    body: String,
    route_uri: String,
) -> Result<(), ServiceError> {
    if let Some(ref mobile) = state.mobile {
        mobile.show_message_notification(
            notification_id,
            &chat_id,
            &message_id,
            &title,
            &body,
            &route_uri,
        )?;
    }
    Ok(())
}

/// Handle `CancelIncomingCall` (spec 08 C6, Step 15).
fn handle_cancel_incoming_call<R: Runtime>(
    state: &ServiceState<R>,
    call_id: String,
) -> Result<(), ServiceError> {
    if let Some(ref mobile) = state.mobile {
        mobile.cancel_incoming_call(&call_id)?;
    }
    Ok(())
}

/// Handle `SetCallAudioRoute` (M-NATIVE-3 / CCF-11, Step 11): set the active
/// call's device audio route. No-op (Ok) when no mobile bridge is attached.
fn handle_set_call_audio_route<R: Runtime>(
    state: &ServiceState<R>,
    call_id: String,
    route: String,
) -> Result<(), ServiceError> {
    if let Some(ref mobile) = state.mobile {
        mobile.set_call_audio_route(&call_id, &route)?;
    }
    Ok(())
}

/// Handle `OpenAppSettings` (M-DIAG-2 / CCF-12, Step 17): open the OS
/// app-settings screen. No-op (Ok) when no mobile bridge is attached.
fn handle_open_app_settings<R: Runtime>(state: &ServiceState<R>) -> Result<(), ServiceError> {
    if let Some(ref mobile) = state.mobile {
        mobile.open_app_settings()?;
    }
    Ok(())
}

/// Handle a `NativeLifecycleEvent` command.
///
/// Recovery-acceptance events (an OsRestart/BootRecovery start the native
/// layer ACCEPTED) are not stops: they fire the policy-gated `bg-recovery`
/// notification and leave the actor's run state alone — the native layer
/// owns that restart. Every other event maps to a stop reason and delegates
/// to [`handle_stop_with_reason`].
fn handle_native_lifecycle_event<R: Runtime>(
    state: &mut ServiceState<R>,
    event: crate::models::NativeLifecycleEvent,
) -> Result<(), ServiceError> {
    if event.is_recovery_acceptance() {
        // D1 recovery fire point: policy gate first, then the sink.
        if state.notifier_policy.on_recovery {
            if let Some(ref sink) = state.notify_sink {
                sink.notify(
                    "bg-recovery",
                    "Background service restored",
                    "Background delivery restored.",
                );
            }
        }
        return Ok(());
    }
    handle_stop_with_reason(state, event.to_stop_reason())
}

/// BGS-05 Leg B: whether the manager should replay a `Start` on boot from the
/// persisted desired-state.
///
/// Pure (host-testable). The desktop lifecycle gate + the `handle_start`
/// dispatch live in `manager_loop`'s pre-loop block; mobile uses its own native
/// resubmit at the platform layer. Consent is the host app's concern (Leg A) —
/// this fn is `desired_running`-only. NV-MUT (force `false`) REDs only the
/// replay test; NV-MUT (force `true`) REDs the no-replay guards.
fn should_replay_on_boot(ds: &crate::desired_state::DesiredState) -> bool {
    ds.desired_running
}

/// Returns `true` if the given stop reason should clear the desired-state
/// (i.e. set `desired_running = false`). Intentional user/app stops clear
/// desired state so auto-restart won't fight the user's intent. Platform
/// timeouts and errors preserve desired state so recovery can restart.
fn should_clear_desired_state(reason: StopReason) -> bool {
    matches!(
        reason,
        StopReason::UserStop
            | StopReason::AppStop
            | StopReason::NativeNotificationStop
            | StopReason::TaskCompleted
    )
}

/// Returns `true` if the "paused, will resume" timeout notification should
/// fire for the given stop reason: a platform pause (timeout/expiration)
/// whose desired state survives so recovery will restart the service.
/// Reuses [`should_clear_desired_state`] for the recoverable classification
/// rather than re-mapping reasons.
fn should_notify_timeout(reason: StopReason) -> bool {
    !should_clear_desired_state(reason)
        && matches!(
            reason,
            StopReason::PlatformTimeout | StopReason::PlatformExpiration
        )
}

/// Returns `true` if `stop_keepalive` should be called for the given reason.
///
/// Platform pauses and OS-driven exits are skipped because the OS has already
/// paused/killed the background window — tearing down the keepalive would be
/// redundant and, on iOS, would cancel the BGTask schedule recovery still needs:
/// - `PlatformExpiration`: the BGTask expiration handler already fired.
/// - `PlatformTimeout` (M13): the cancel-listener safety timeout / Android FGS
///   timeout — the OS owns the pause; keep the schedule so delivery resumes.
/// - `ProcessExit` (H2): the host process is exiting; the BGTask schedule must
///   survive so a future launch resumes background delivery.
fn should_stop_keepalive(reason: StopReason) -> bool {
    !matches!(
        reason,
        StopReason::PlatformExpiration | StopReason::PlatformTimeout | StopReason::ProcessExit
    )
}

/// Returns `true` if a stop should trigger a reconcile re-submit of native
/// scheduling (M13). A cancel-listener `PlatformTimeout` pauses the service while
/// `desired_running` survives; without re-submitting the BGTask schedule the
/// background delivery would silently end. Other preserve-desired reasons keep
/// their existing schedule (nothing was torn down), so they need no re-submit.
fn should_reconcile_resubmit(reason: StopReason) -> bool {
    matches!(reason, StopReason::PlatformTimeout)
}

// ─── Desired-State Helpers ──────────────────────────────────────────────

/// Save desired-state to the backend (if configured).
///
/// On `desired=true`: saves `desired_running=true` with config and timestamp.
/// On `desired=false`: saves `desired_running=false` and clears recovery fields.
fn save_desired_running<R: Runtime>(
    state: &ServiceState<R>,
    desired: bool,
    config: Option<&StartConfig>,
) {
    let Some(ref backend) = state.desired_state else {
        return;
    };

    let mut ds = backend.load().unwrap_or_default();
    ds.desired_running = desired;
    if desired {
        ds.last_start_config = config.map(|c| serde_json::to_value(c).unwrap_or_default());
        ds.last_start_epoch_ms = Some(
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis() as u64,
        );
    } else {
        ds.last_start_config = None;
        ds.last_start_epoch_ms = None;
        ds.recovery_pending = false;
        ds.recovery_reason = None;
        ds.restart_attempt = 0;
    }
    if let Err(e) = backend.save(&ds) {
        log::warn!("failed to save desired state: {e}");
    }
}

/// CORE-01: same payload as `save_desired_running` but callable from the
/// spawned task where only the desired-state backend / mobile bridge clones
/// are available (no `&ServiceState`). Used by the natural-completion path
/// to clear persisted/native desired intent when `run()` returns `Ok` and no
/// explicit stop reason was set.
fn save_desired_running_via(
    desired_state: &Option<std::sync::Arc<dyn DesiredStateBackend>>,
    mobile: &Option<std::sync::Arc<dyn MobileKeepalive>>,
    lifecycle_mode: LifecycleMode,
    desired: bool,
    config: Option<&StartConfig>,
) {
    if let Some(backend) = desired_state {
        let mut ds = backend.load().unwrap_or_default();
        ds.desired_running = desired;
        if desired {
            ds.last_start_config = config.map(|c| serde_json::to_value(c).unwrap_or_default());
            ds.last_start_epoch_ms = Some(
                std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_millis() as u64,
            );
        } else {
            ds.last_start_config = None;
            ds.last_start_epoch_ms = None;
            ds.recovery_pending = false;
            ds.recovery_reason = None;
            ds.restart_attempt = 0;
        }
        if let Err(e) = backend.save(&ds) {
            log::warn!("failed to save desired state from spawned task: {e}");
        }
    }
    // Mirror to native on iOS so UserDefaults + BGTask scheduling follow.
    // Desktop has no mobile bridge; the explicit-stop path already mirrored.
    if matches!(lifecycle_mode, LifecycleMode::IosBgTaskScheduler) {
        if let Some(m) = mobile {
            let config_value = config.map(|c| serde_json::to_value(c).unwrap_or_default());
            if let Err(e) = m.mirror_desired_state(desired, config_value.as_ref()) {
                log::warn!("failed to mirror desired state to native from spawned task: {e}");
            }
        }
    }
}

/// Mirror the Rust-authoritative desired state into native persistence (H4/D1).
///
/// Called by the intent-only recovery commands (`SetDesiredRunning`,
/// `EnableAutoRestart`, `DisableAutoRestart`) so that on iOS they update
/// `UserDefaults` + BGTask scheduling instead of silently no-op'ing. The actual
/// start/stop paths are NOT mirrored here — they already reach native via
/// `start_keepalive`/`stop_keepalive`, so mirroring there would re-schedule
/// redundantly. No-op when no mobile bridge is present (desktop).
fn mirror_desired_to_native<R: Runtime>(
    state: &ServiceState<R>,
    desired: bool,
    config: Option<&StartConfig>,
) {
    let Some(ref mobile) = state.mobile else {
        return;
    };
    let config_value = config.map(|c| serde_json::to_value(c).unwrap_or_default());
    if let Err(e) = mobile.mirror_desired_state(desired, config_value.as_ref()) {
        log::warn!("failed to mirror desired state to native: {e}");
    }
}

/// Handle a `SetDesiredRunning` command.
///
/// Persists the desired running state WITHOUT affecting the actual running state.
/// This is used by `enableAutoRestart()` / `disableAutoRestart()` to set intent
/// for recovery without starting/stopping the service.
fn handle_set_desired_running<R: Runtime>(
    state: &mut ServiceState<R>,
    desired: bool,
    config: Option<StartConfig>,
) -> Result<(), ServiceError> {
    save_desired_running(state, desired, config.as_ref());
    mirror_desired_to_native(state, desired, config.as_ref());
    Ok(())
}

/// Handle an `EnableAutoRestart` command.
///
/// Persists `desired_running=true` with the optional config WITHOUT starting
/// the service. Used to set recovery intent for future restart/reboot.
fn handle_enable_auto_restart<R: Runtime>(
    state: &mut ServiceState<R>,
    config: Option<StartConfig>,
) -> Result<(), ServiceError> {
    save_desired_running(state, true, config.as_ref());
    mirror_desired_to_native(state, true, config.as_ref());
    Ok(())
}

/// Handle a `DisableAutoRestart` command.
///
/// Persists `desired_running=false` with cleared recovery fields WITHOUT
/// stopping the service.
fn handle_disable_auto_restart<R: Runtime>(
    state: &mut ServiceState<R>,
) -> Result<(), ServiceError> {
    save_desired_running(state, false, None);
    mirror_desired_to_native(state, false, None);
    Ok(())
}

/// Handle a `GetDesiredState` command.
///
/// Returns the persisted desired state, or `None` if no backend is configured.
fn handle_get_desired_state<R: Runtime>(
    state: &ServiceState<R>,
) -> Option<crate::desired_state::DesiredState> {
    state
        .desired_state
        .as_ref()
        .and_then(|backend| backend.load().ok())
}

/// Reconcile the actor's running-state belief against the native authority.
///
/// Native `LifecycleService.isRunning` is the single source of truth for
/// service running-state (R-W1.4). When the actor's in-memory belief diverges
/// from the native report, the actor **converges to native** and **logs** the
/// divergence — never silently (NFR-1 / NFR-5). This closes the split-brain
/// window where a stop/timeout with the UI closed could otherwise leave the
/// actor stuck believing the service still runs (harness Scenario 8).
///
/// Returns the reconciled running-state. No-op — returns the actor's current
/// belief unchanged — when no native authority is reachable (desktop, iOS, or a
/// bridge query failure): there is nothing more authoritative to defer to.
fn reconcile_running_with_native<R: Runtime>(state: &ServiceState<R>) -> bool {
    let rust_running = state.is_running.load(Ordering::Acquire);

    // Query the native authority. On desktop / bridge failure there is no
    // authority to reconcile against, so keep the actor's belief unchanged.
    let Some(authority) = state
        .mobile
        .as_ref()
        .and_then(|m| m.query_native_state().ok().flatten())
    else {
        return rust_running;
    };

    // iOS has no long-lived native service whose running bit can override the
    // actor: during a BGTask the Rust actor *is* the runtime authority and the
    // cancel-listener owns the stop. Keep the actor's belief unchanged (L4: no
    // Android round-trip on iOS).
    let native = match authority {
        NativeAuthority::Android(ns) => ns,
        NativeAuthority::Ios(_) => return rust_running,
    };

    if native.native_running == rust_running {
        return rust_running;
    }

    // Divergence: native wins. Converge + log, never swallow (NFR-1 / NFR-5).
    log::warn!(
        "running-state diverged from native authority \
         (rust_running={rust_running}, native_running={}, durable_state={}); \
         converging to native",
        native.native_running,
        native.durable_state,
    );
    state
        .is_running
        .store(native.native_running, Ordering::Release);
    *state.lifecycle_state.lock().unwrap() = if native.native_running {
        crate::models::ServiceState::Running
    } else {
        crate::models::ServiceState::Stopped
    };
    // CORE-02: when native authority says the service has stopped, also
    // take/cancel the Rust-side token so a subsequent Start does not hit
    // `AlreadyRunning` and permanently block restart. Previously this path
    // flipped `is_running` to false but left `token=Some`, leaking the slot
    // until process restart.
    if !native.native_running {
        if let Some(token) = state.token.lock().unwrap().take() {
            token.cancel();
            // Surface the native-stop reason on the terminal slot so any
            // in-flight task cleanup emits the user-meaningful reason.
            *state.terminal_reason.lock().unwrap() = Some((
                state.generation.load(Ordering::Acquire),
                crate::models::StopReason::NativeNotificationStop,
            ));
        }
    }
    native.native_running
}

/// Compose a [`LifecycleStatus`] snapshot from the actor's current state.
///
/// Gathers: service lifecycle state → `LifecycleState`, desired-state fields
/// from the persistence backend, native Android state via the mobile bridge,
/// merge logic (adopt / auto-heal / normal), platform capabilities, and
/// validation issues.
fn build_lifecycle_status<R: Runtime>(
    state: &ServiceState<R>,
    desktop_mode: Option<&str>,
) -> LifecycleStatus {
    let last_error = state.last_error.lock().unwrap().clone();

    // Load desired-state fields.
    let desired = state.desired_state.as_ref().and_then(|b| b.load().ok());

    let desired_running = desired.as_ref().is_some_and(|d| d.desired_running);
    let recovery_enabled = desired_running;
    let recovery_reason = desired.as_ref().and_then(|d| d.recovery_reason.clone());
    let last_start_config = desired
        .as_ref()
        .and_then(|d| d.last_start_config.clone())
        .and_then(|v| serde_json::from_value(v).ok());
    let mut last_platform_state = desired.as_ref().and_then(|d| d.last_native_state.clone());
    let mut last_platform_error = desired.as_ref().and_then(|d| d.last_platform_error.clone());

    // Query the platform-tagged native authority when the mobile bridge is
    // available. On failure, fall back to Rust-only state (no native fields
    // populated). The Android merge logic below operates on `native_state`
    // (Android only); the iOS snapshot is handled by a dedicated branch so the
    // status path never round-trips to `get_android_service_state` on iOS (L4).
    let authority = state
        .mobile
        .as_ref()
        .and_then(|m| m.query_native_state().ok().flatten());
    let native_state = match &authority {
        Some(NativeAuthority::Android(ns)) => Some(ns.clone()),
        _ => None,
    };
    let ios_native = match &authority {
        Some(NativeAuthority::Ios(s)) => Some(s.clone()),
        _ => None,
    };

    let (mut native_running, mut native_foreground) = match &native_state {
        Some(ns) => (Some(ns.native_running), Some(ns.native_foreground)),
        None => (None, None),
    };

    // ── Merge rules ─────────────────────────────────────────────────────
    // Compare native Android state with Rust actor state.
    // Authority: native for service state, Rust for Core state.
    let rust_running = state.is_running.load(Ordering::Acquire);

    let (adopted, degraded, degraded_reason, should_emit) = match &native_state {
        Some(ns) if ns.native_running && !rust_running => {
            // Rule 1: Native running, Rust idle → adopt (bookkeeping only).
            state.is_running.store(true, Ordering::Release);
            *state.lifecycle_state.lock().unwrap() = crate::models::ServiceState::Running;
            (Some(true), Some(false), None, false)
        }
        Some(ns) if !ns.native_running && rust_running => {
            // Rule 2: Native stopped, Rust running → auto-heal to idle.
            // Native is the authority (R-W1.4): converge + log, never silently
            // swallow the divergence (NFR-1 / NFR-5).
            log::warn!(
                "running-state diverged from native authority \
                 (rust_running=true, native_running=false, durable_state={}); \
                 converging to native (auto-heal)",
                ns.durable_state,
            );
            state.is_running.store(false, Ordering::Release);
            *state.lifecycle_state.lock().unwrap() = crate::models::ServiceState::Stopped;
            (
                None,
                Some(true),
                Some("native_stopped_rust_running".into()),
                true,
            )
        }
        Some(ns) if ns.native_running && rust_running => {
            // Rule 3: Both running → normal.
            (Some(false), Some(false), None, false)
        }
        Some(_ns) => {
            // Rule 4: Both idle → normal.
            (Some(false), Some(false), None, false)
        }
        None => {
            // No native state (non-Android or bridge failure).
            (None, None, None, false)
        }
    };

    // Rule 5: Timeout detection — native DurableState says timeout.
    // Detects timeout regardless of Rust actor state so that stale DurableState
    // from a previous session (app relaunch after JS-less timeout) surfaces.
    let (mut degraded, mut degraded_reason) = if degraded == Some(true) {
        (degraded, degraded_reason)
    } else if let Some(ns) = &native_state {
        if ns.durable_state == "timeout" {
            let reason = if rust_running {
                "native_timeout"
            } else {
                "stale_timeout"
            };
            (Some(true), Some(reason.into()))
        } else {
            (degraded, degraded_reason)
        }
    } else {
        (degraded, degraded_reason)
    };

    // Rule 6: Surface recovery_pending from native state.
    let recovery_pending = desired.as_ref().is_some_and(|d| d.recovery_pending)
        || native_state.as_ref().is_some_and(|ns| ns.recovery_pending);

    // ── iOS native authority (H6) ─────────────────────────────────────────
    // iOS has no persistent foreground service: surface the *real* BGTask /
    // scheduling situation from the native snapshot so the status reflects
    // native facts (a task executing, a pending task waiting, a scheduling
    // error, an exhausted budget) rather than the actor's possibly-stale
    // in-memory lifecycle state. A scheduling error / out-of-budget is degraded
    // and is never swallowed silently (NFR-1 / NFR-5).
    if let Some(ios) = &ios_native {
        // A BGTask is not a foreground service; report whether one is currently
        // executing as the "native running" bit (honest `false` when waiting).
        native_running = Some(ios.active_task_kind.is_some());
        native_foreground = Some(false);

        let phase = if ios.active_task_kind.is_some() {
            "running"
        } else if ios.pending_task.is_some() {
            "pendingBgTask"
        } else if ios.desired_running {
            "waitingForBgTask"
        } else {
            "stopped"
        };
        last_platform_state = Some(phase.to_string());

        // "last-failed?" is split per task type (M7); surface whichever failed
        // (refresh preferred) as the degraded scheduling error.
        let schedule_error = ios
            .last_refresh_error
            .as_ref()
            .or(ios.last_processing_error.as_ref());
        if let Some(err) = schedule_error {
            last_platform_error = Some(err.clone());
            degraded = Some(true);
            degraded_reason = Some("ios_scheduling_error".to_string());
        } else if ios.desired_running && !ios.in_budget {
            degraded = Some(true);
            degraded_reason = Some("ios_out_of_budget".to_string());
        } else {
            degraded = Some(false);
            degraded_reason = None;
        }
    }

    // H9: an advisory scheduling failure recorded at start time surfaces as a
    // distinct "scheduling degraded / foreground-only" status — the Core runs in
    // the foreground but background scheduling is unavailable. A more specific
    // native iOS health problem (already `degraded == Some(true)` above) wins.
    if degraded != Some(true) {
        if let Some(reason) = state.scheduling_degraded.lock().unwrap().as_ref() {
            last_platform_error = Some(reason.clone());
            degraded = Some(true);
            degraded_reason = Some("scheduling_degraded_foreground_only".to_string());
        }
    }

    // Emit degraded event on mismatch, stale timeout, or an iOS health problem.
    if should_emit
        || (degraded == Some(true)
            && matches!(
                degraded_reason.as_deref(),
                Some("native_timeout")
                    | Some("stale_timeout")
                    | Some("ios_scheduling_error")
                    | Some("ios_out_of_budget")
                    | Some("scheduling_degraded_foreground_only")
            ))
    {
        if let Some(ref app) = state.app {
            let _ = app.emit(
                "background-service:state-degraded",
                serde_json::json!({
                    "degraded": true,
                    "reason": degraded_reason,
                    "native_running": native_running,
                    "rust_running": rust_running,
                }),
            );
        }
    }

    // Read lifecycle state AFTER merge (merge may have updated it).
    let mut lifecycle_state: LifecycleState = (*state.lifecycle_state.lock().unwrap()).into();

    // Override lifecycle state for native setup_idle/locked_idle durable states.
    // These are healthy states where the service is running but waiting for
    // user action (account setup or unlock). They are NOT errors.
    if let Some(ns) = &native_state {
        match ns.durable_state.as_str() {
            "setup_idle" => lifecycle_state = LifecycleState::SetupIdle,
            "locked_idle" => lifecycle_state = LifecycleState::LockedIdle,
            _ => {}
        }
    }

    // iOS (H6): don't report a stale "Running" lifecycle when the native
    // snapshot shows no BGTask executing and the service is not desired — the
    // actor's in-memory state may be stale after a JS-less expiration.
    if let Some(ios) = &ios_native {
        if ios.active_task_kind.is_none() && !ios.desired_running {
            lifecycle_state = LifecycleState::Stopped;
        }
    }

    // Surface data_dir from native state for path validation.
    let data_dir = native_state.as_ref().map(|ns| ns.data_dir.clone());

    let (platform, detected_mode) =
        crate::capabilities::CapabilityProvider::detect_platform(desktop_mode);
    let capabilities = crate::capabilities::CapabilityProvider::capabilities(
        platform,
        // DESK-04: prefer the per-request detected mode over the actor's
        // spawn-time lifecycle_mode. The headless server passes
        // `Some("osService")` so a connected GUI reports DesktopOsService.
        detected_mode,
        false,
    );
    let report = crate::validator::SetupValidator::validate(platform);
    let mut issues: Vec<ValidationIssue> = report
        .errors
        .into_iter()
        .map(|i| ValidationIssue {
            severity: crate::models::Severity::Error,
            code: i.code,
            message: i.message,
            fix: i.fix,
            platform,
        })
        .collect();
    issues.extend(report.warnings.into_iter().map(|i| ValidationIssue {
        severity: crate::models::Severity::Warning,
        code: i.code,
        message: i.message,
        fix: i.fix,
        platform,
    }));

    LifecycleStatus {
        state: lifecycle_state,
        desired_running,
        recovery_enabled,
        recovery_pending,
        recovery_reason,
        last_start_config,
        last_platform_state,
        last_platform_error,
        last_error,
        platform,
        capabilities,
        issues,
        native_running,
        native_foreground,
        adopted,
        degraded,
        degraded_reason,
        data_dir,
    }
}

#[cfg(test)]
#[allow(clippy::field_reassign_with_default)]
mod tests {
    use super::*;
    use crate::desired_state::DesiredState;
    use crate::models::{NativeLifecycleEvent, NativeState};
    use async_trait::async_trait;
    use std::sync::atomic::{AtomicI8, AtomicU8, AtomicUsize};
    use tauri::Listener;

    // ── Mock mobile for keepalive testing ─────────────────────────────

    /// Mock mobile that records start/stop_keepalive calls.
    struct MockMobile {
        start_called: AtomicUsize,
        stop_called: AtomicUsize,
        start_fail: bool,
        last_label: std::sync::Mutex<Option<String>>,
        last_fst: std::sync::Mutex<Option<String>>,
        last_timeout_secs: std::sync::Mutex<Option<f64>>,
        last_processing_timeout_secs: std::sync::Mutex<Option<f64>>,
        last_earliest_refresh_begin_minutes: std::sync::Mutex<Option<f64>>,
        last_earliest_processing_begin_minutes: std::sync::Mutex<Option<f64>>,
        last_requires_external_power: std::sync::Mutex<Option<bool>>,
        last_requires_network_connectivity: std::sync::Mutex<Option<bool>>,
        last_processing_ceiling_multiplier: std::sync::Mutex<Option<f64>>,
        /// Records every `mirror_desired_state` call as `(desired, config)`
        /// — the H4 desired-state mirror seam.
        mirror_calls: std::sync::Mutex<Vec<(bool, Option<serde_json::Value>)>>,
        /// When true, `scheduling_is_advisory()` returns true — models the iOS
        /// BGTask scheduler whose failure is a non-fatal degraded warning (H9).
        advisory_scheduling: bool,
        /// When true, `enforces_foreground_service_type()` returns true — models
        /// Android (FGS types are OS-enforced). When false, models iOS/desktop
        /// (no FGS-type concept) — the M5/M6 gate seam.
        enforces_fst: bool,
        /// Records every `update_keepalive_type` (native `updateForegroundServiceType`)
        /// call — proves zero native swaps fire on the iOS-like path (M5).
        update_type_calls: std::sync::Mutex<Vec<String>>,
    }

    impl MockMobile {
        fn new() -> Arc<Self> {
            Arc::new(Self {
                start_called: AtomicUsize::new(0),
                stop_called: AtomicUsize::new(0),
                start_fail: false,
                last_label: std::sync::Mutex::new(None),
                last_fst: std::sync::Mutex::new(None),
                last_timeout_secs: std::sync::Mutex::new(None),
                last_processing_timeout_secs: std::sync::Mutex::new(None),
                last_earliest_refresh_begin_minutes: std::sync::Mutex::new(None),
                last_earliest_processing_begin_minutes: std::sync::Mutex::new(None),
                last_requires_external_power: std::sync::Mutex::new(None),
                last_requires_network_connectivity: std::sync::Mutex::new(None),
                last_processing_ceiling_multiplier: std::sync::Mutex::new(None),
                mirror_calls: std::sync::Mutex::new(Vec::new()),
                advisory_scheduling: false,
                enforces_fst: false,
                update_type_calls: std::sync::Mutex::new(Vec::new()),
            })
        }

        fn new_failing() -> Arc<Self> {
            Arc::new(Self {
                start_called: AtomicUsize::new(0),
                stop_called: AtomicUsize::new(0),
                start_fail: true,
                last_label: std::sync::Mutex::new(None),
                last_fst: std::sync::Mutex::new(None),
                last_timeout_secs: std::sync::Mutex::new(None),
                last_processing_timeout_secs: std::sync::Mutex::new(None),
                last_earliest_refresh_begin_minutes: std::sync::Mutex::new(None),
                last_earliest_processing_begin_minutes: std::sync::Mutex::new(None),
                last_requires_external_power: std::sync::Mutex::new(None),
                last_requires_network_connectivity: std::sync::Mutex::new(None),
                last_processing_ceiling_multiplier: std::sync::Mutex::new(None),
                mirror_calls: std::sync::Mutex::new(Vec::new()),
                advisory_scheduling: false,
                enforces_fst: false,
                update_type_calls: std::sync::Mutex::new(Vec::new()),
            })
        }

        /// Failing mock whose scheduling is *advisory* (iOS BGTask): the failure
        /// must be treated as a non-fatal degraded warning, not a rollback (H9).
        fn new_failing_advisory() -> Arc<Self> {
            Arc::new(Self {
                start_called: AtomicUsize::new(0),
                stop_called: AtomicUsize::new(0),
                start_fail: true,
                last_label: std::sync::Mutex::new(None),
                last_fst: std::sync::Mutex::new(None),
                last_timeout_secs: std::sync::Mutex::new(None),
                last_processing_timeout_secs: std::sync::Mutex::new(None),
                last_earliest_refresh_begin_minutes: std::sync::Mutex::new(None),
                last_earliest_processing_begin_minutes: std::sync::Mutex::new(None),
                last_requires_external_power: std::sync::Mutex::new(None),
                last_requires_network_connectivity: std::sync::Mutex::new(None),
                last_processing_ceiling_multiplier: std::sync::Mutex::new(None),
                mirror_calls: std::sync::Mutex::new(Vec::new()),
                advisory_scheduling: true,
                enforces_fst: false,
                update_type_calls: std::sync::Mutex::new(Vec::new()),
            })
        }

        /// Mock whose platform enforces foreground-service types — models
        /// Android (`enforces_foreground_service_type()` → true). Used by the
        /// M5/M6 gating tests to prove validation + the native type-swap run on
        /// the Android path. The default [`new`](Self::new) mock models
        /// iOS/desktop (enforces → false).
        fn new_enforcing() -> Arc<Self> {
            Arc::new(Self {
                start_called: AtomicUsize::new(0),
                stop_called: AtomicUsize::new(0),
                start_fail: false,
                last_label: std::sync::Mutex::new(None),
                last_fst: std::sync::Mutex::new(None),
                last_timeout_secs: std::sync::Mutex::new(None),
                last_processing_timeout_secs: std::sync::Mutex::new(None),
                last_earliest_refresh_begin_minutes: std::sync::Mutex::new(None),
                last_earliest_processing_begin_minutes: std::sync::Mutex::new(None),
                last_requires_external_power: std::sync::Mutex::new(None),
                last_requires_network_connectivity: std::sync::Mutex::new(None),
                last_processing_ceiling_multiplier: std::sync::Mutex::new(None),
                mirror_calls: std::sync::Mutex::new(Vec::new()),
                advisory_scheduling: false,
                enforces_fst: true,
                update_type_calls: std::sync::Mutex::new(Vec::new()),
            })
        }

        /// Snapshot of every `update_keepalive_type` argument recorded so far.
        fn update_type_calls(&self) -> Vec<String> {
            self.update_type_calls.lock().unwrap().clone()
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn mock_start_keepalive(
        mock: &MockMobile,
        label: &str,
        foreground_service_type: &str,
        ios_safety_timeout_secs: Option<f64>,
        ios_processing_safety_timeout_secs: Option<f64>,
        ios_earliest_refresh_begin_minutes: Option<f64>,
        ios_earliest_processing_begin_minutes: Option<f64>,
        ios_requires_external_power: Option<bool>,
        ios_requires_network_connectivity: Option<bool>,
        ios_processing_ceiling_multiplier: Option<f64>,
    ) -> Result<(), ServiceError> {
        mock.start_called.fetch_add(1, Ordering::Release);
        *mock.last_label.lock().unwrap() = Some(label.to_string());
        *mock.last_fst.lock().unwrap() = Some(foreground_service_type.to_string());
        *mock.last_timeout_secs.lock().unwrap() = ios_safety_timeout_secs;
        *mock.last_processing_timeout_secs.lock().unwrap() = ios_processing_safety_timeout_secs;
        *mock.last_earliest_refresh_begin_minutes.lock().unwrap() =
            ios_earliest_refresh_begin_minutes;
        *mock.last_earliest_processing_begin_minutes.lock().unwrap() =
            ios_earliest_processing_begin_minutes;
        *mock.last_requires_external_power.lock().unwrap() = ios_requires_external_power;
        *mock.last_requires_network_connectivity.lock().unwrap() =
            ios_requires_network_connectivity;
        *mock.last_processing_ceiling_multiplier.lock().unwrap() =
            ios_processing_ceiling_multiplier;
        if mock.start_fail {
            return Err(ServiceError::Platform("mock keepalive failure".into()));
        }
        Ok(())
    }

    impl MobileKeepalive for MockMobile {
        #[allow(clippy::too_many_arguments)]
        fn start_keepalive(
            &self,
            label: &str,
            foreground_service_type: &str,
            ios_safety_timeout_secs: Option<f64>,
            ios_processing_safety_timeout_secs: Option<f64>,
            ios_earliest_refresh_begin_minutes: Option<f64>,
            ios_earliest_processing_begin_minutes: Option<f64>,
            ios_requires_external_power: Option<bool>,
            ios_requires_network_connectivity: Option<bool>,
            ios_processing_ceiling_multiplier: Option<f64>,
        ) -> Result<(), ServiceError> {
            mock_start_keepalive(
                self,
                label,
                foreground_service_type,
                ios_safety_timeout_secs,
                ios_processing_safety_timeout_secs,
                ios_earliest_refresh_begin_minutes,
                ios_earliest_processing_begin_minutes,
                ios_requires_external_power,
                ios_requires_network_connectivity,
                ios_processing_ceiling_multiplier,
            )
        }

        fn stop_keepalive(&self) -> Result<(), ServiceError> {
            self.stop_called.fetch_add(1, Ordering::Release);
            Ok(())
        }

        fn scheduling_is_advisory(&self) -> bool {
            self.advisory_scheduling
        }

        fn enforces_foreground_service_type(&self) -> bool {
            self.enforces_fst
        }

        fn update_keepalive_type(&self, foreground_service_type: &str) -> Result<(), ServiceError> {
            self.update_type_calls
                .lock()
                .unwrap()
                .push(foreground_service_type.to_string());
            Ok(())
        }

        fn mirror_desired_state(
            &self,
            desired_running: bool,
            last_start_config: Option<&serde_json::Value>,
        ) -> Result<(), ServiceError> {
            self.mirror_calls
                .lock()
                .unwrap()
                .push((desired_running, last_start_config.cloned()));
            Ok(())
        }
    }

    // ── Recording sink for D1 notification testing ────────────────────

    /// Test double for [`NotifySink`] that records every `notify()` call.
    /// Step 3's fire-point tests assert on the recorded calls; in this step
    /// it proves wiring a sink into the actor changes no behavior.
    struct RecordingSink {
        calls: std::sync::Mutex<Vec<(String, String, String)>>,
    }

    impl RecordingSink {
        fn new() -> Arc<Self> {
            Arc::new(Self {
                calls: std::sync::Mutex::new(Vec::new()),
            })
        }

        fn calls(&self) -> Vec<(String, String, String)> {
            self.calls.lock().unwrap().clone()
        }
    }

    impl NotifySink for RecordingSink {
        fn notify(&self, id: &str, title: &str, body: &str) {
            self.calls
                .lock()
                .unwrap()
                .push((id.into(), title.into(), body.into()));
        }
    }

    /// Service that blocks in run() until cancelled.
    /// Used for lifecycle tests where is_running must remain true.
    struct BlockingService;

    #[async_trait]
    impl BackgroundService<tauri::test::MockRuntime> for BlockingService {
        async fn init(
            &mut self,
            _ctx: &ServiceContext<tauri::test::MockRuntime>,
        ) -> Result<(), ServiceError> {
            Ok(())
        }

        async fn run(
            &mut self,
            ctx: &ServiceContext<tauri::test::MockRuntime>,
        ) -> Result<(), ServiceError> {
            ctx.shutdown.cancelled().await;
            Ok(())
        }
    }

    /// Create a manager actor with a BlockingService factory.
    fn setup_manager() -> ServiceManagerHandle<tauri::test::MockRuntime> {
        setup_manager_with_backend(None)
    }

    /// Create a manager actor with a desired-state backend.
    fn setup_manager_with_backend(
        backend: Option<Arc<dyn DesiredStateBackend>>,
    ) -> ServiceManagerHandle<tauri::test::MockRuntime> {
        setup_manager_with_backend_and_allowlist(backend, vec!["remoteMessaging".into()], true)
    }

    /// Create a manager actor with a desired-state backend and custom allowlist.
    fn setup_manager_with_backend_and_allowlist(
        backend: Option<Arc<dyn DesiredStateBackend>>,
        android_fg_service_types: Vec<String>,
        android_validate_fg_type: bool,
    ) -> ServiceManagerHandle<tauri::test::MockRuntime> {
        let (cmd_tx, cmd_rx) = mpsc::channel(16);
        let handle = ServiceManagerHandle::new(cmd_tx);
        let factory: ServiceFactory<tauri::test::MockRuntime> =
            Box::new(|| Box::new(BlockingService));
        tokio::spawn(manager_loop(
            cmd_rx,
            factory,
            28.0,
            0.0,
            15.0,
            15.0,
            false,
            false,
            4.0,
            backend,
            android_fg_service_types,
            android_validate_fg_type,
            NotifierPolicy::default(),
            None,
            None,
            false,
        ));
        handle
    }

    /// Create a manager actor with a notifier policy and notify sink (D1).
    fn setup_manager_with_sink(
        policy: NotifierPolicy,
        sink: Arc<dyn NotifySink>,
    ) -> ServiceManagerHandle<tauri::test::MockRuntime> {
        setup_manager_with_policy_and_sink(policy, Some(sink))
    }

    /// Create a manager actor with a notifier policy and an optional sink
    /// (D1; `None` models the headless daemon with no notification handle).
    fn setup_manager_with_policy_and_sink(
        policy: NotifierPolicy,
        sink: Option<Arc<dyn NotifySink>>,
    ) -> ServiceManagerHandle<tauri::test::MockRuntime> {
        let (cmd_tx, cmd_rx) = mpsc::channel(16);
        let handle = ServiceManagerHandle::new(cmd_tx);
        let factory: ServiceFactory<tauri::test::MockRuntime> =
            Box::new(|| Box::new(BlockingService));
        tokio::spawn(manager_loop(
            cmd_rx,
            factory,
            28.0,
            0.0,
            15.0,
            15.0,
            false,
            false,
            4.0,
            None,
            vec!["remoteMessaging".into()],
            true,
            policy,
            sink,
            None,
            false,
        ));
        handle
    }

    async fn send_start(
        handle: &ServiceManagerHandle<tauri::test::MockRuntime>,
        app: AppHandle<tauri::test::MockRuntime>,
    ) -> Result<(), ServiceError> {
        send_start_with_config(handle, StartConfig::default(), app).await
    }

    async fn send_start_with_config(
        handle: &ServiceManagerHandle<tauri::test::MockRuntime>,
        config: StartConfig,
        app: AppHandle<tauri::test::MockRuntime>,
    ) -> Result<(), ServiceError> {
        let (tx, rx) = oneshot::channel();
        handle
            .cmd_tx
            .send(ManagerCommand::Start {
                config,
                reply: tx,
                app,
            })
            .await
            .unwrap();
        rx.await.unwrap()
    }

    async fn send_stop(
        handle: &ServiceManagerHandle<tauri::test::MockRuntime>,
    ) -> Result<(), ServiceError> {
        let (tx, rx) = oneshot::channel();
        handle
            .cmd_tx
            .send(ManagerCommand::Stop { reply: tx })
            .await
            .unwrap();
        rx.await.unwrap()
    }

    async fn send_is_running(handle: &ServiceManagerHandle<tauri::test::MockRuntime>) -> bool {
        let (tx, rx) = oneshot::channel();
        handle
            .cmd_tx
            .send(ManagerCommand::IsRunning { reply: tx })
            .await
            .unwrap();
        rx.await.unwrap()
    }

    // ── AC1: Start from idle succeeds ────────────────────────────────

    #[tokio::test]
    async fn start_from_idle() {
        let handle = setup_manager();
        let app = tauri::test::mock_app();

        let result = send_start(&handle, app.handle().clone()).await;
        assert!(result.is_ok(), "start should succeed from idle");
        assert!(
            send_is_running(&handle).await,
            "should be running after start"
        );
    }

    // ── AC2: Stop from running succeeds ──────────────────────────────

    #[tokio::test]
    async fn stop_from_running() {
        let handle = setup_manager();
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();

        let result = send_stop(&handle).await;
        assert!(result.is_ok(), "stop should succeed from running");
        assert!(
            !send_is_running(&handle).await,
            "should not be running after stop"
        );
    }

    // ── AC3: Double start returns AlreadyRunning ────────────────────

    #[tokio::test]
    async fn double_start_returns_already_running() {
        let handle = setup_manager();
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();

        let result = send_start(&handle, app.handle().clone()).await;
        assert!(
            matches!(result, Err(ServiceError::AlreadyRunning)),
            "second start should return AlreadyRunning"
        );
    }

    // ── AC4: Stop when not running returns NotRunning ────────────────

    #[tokio::test]
    async fn stop_when_not_running_returns_not_running() {
        let handle = setup_manager();

        let result = send_stop(&handle).await;
        assert!(
            matches!(result, Err(ServiceError::NotRunning)),
            "stop should return NotRunning when idle"
        );
    }

    // ── AC5: Start-stop-restart cycle works ──────────────────────────

    #[tokio::test]
    async fn start_stop_restart_cycle() {
        let handle = setup_manager();
        let app = tauri::test::mock_app();

        // Start
        send_start(&handle, app.handle().clone()).await.unwrap();
        assert!(send_is_running(&handle).await);

        // Stop
        send_stop(&handle).await.unwrap();
        assert!(!send_is_running(&handle).await);

        // Restart
        let result = send_start(&handle, app.handle().clone()).await;
        assert!(result.is_ok(), "restart should succeed after stop");
        assert!(
            send_is_running(&handle).await,
            "should be running after restart"
        );
    }

    // ── Test services for callback testing ────────────────────────────

    /// Service that completes run() immediately with success.
    struct ImmediateSuccessService;

    #[async_trait]
    impl BackgroundService<tauri::test::MockRuntime> for ImmediateSuccessService {
        async fn init(
            &mut self,
            _ctx: &ServiceContext<tauri::test::MockRuntime>,
        ) -> Result<(), ServiceError> {
            Ok(())
        }

        async fn run(
            &mut self,
            _ctx: &ServiceContext<tauri::test::MockRuntime>,
        ) -> Result<(), ServiceError> {
            Ok(())
        }
    }

    /// Service whose run() returns an error immediately.
    struct ImmediateErrorService;

    #[async_trait]
    impl BackgroundService<tauri::test::MockRuntime> for ImmediateErrorService {
        async fn init(
            &mut self,
            _ctx: &ServiceContext<tauri::test::MockRuntime>,
        ) -> Result<(), ServiceError> {
            Ok(())
        }

        async fn run(
            &mut self,
            _ctx: &ServiceContext<tauri::test::MockRuntime>,
        ) -> Result<(), ServiceError> {
            Err(ServiceError::Runtime("run error".into()))
        }
    }

    /// Service whose init() fails.
    struct FailingInitService;

    #[async_trait]
    impl BackgroundService<tauri::test::MockRuntime> for FailingInitService {
        async fn init(
            &mut self,
            _ctx: &ServiceContext<tauri::test::MockRuntime>,
        ) -> Result<(), ServiceError> {
            Err(ServiceError::Init("init error".into()))
        }

        async fn run(
            &mut self,
            _ctx: &ServiceContext<tauri::test::MockRuntime>,
        ) -> Result<(), ServiceError> {
            Ok(())
        }
    }

    /// Create a manager actor with a custom factory.
    fn setup_manager_with_factory(
        factory: ServiceFactory<tauri::test::MockRuntime>,
    ) -> ServiceManagerHandle<tauri::test::MockRuntime> {
        setup_manager_with_factory_and_backend(factory, None)
    }

    /// Create a manager actor with a custom factory and desired-state backend.
    fn setup_manager_with_factory_and_backend(
        factory: ServiceFactory<tauri::test::MockRuntime>,
        backend: Option<Arc<dyn DesiredStateBackend>>,
    ) -> ServiceManagerHandle<tauri::test::MockRuntime> {
        setup_manager_with_factory_backend_and_boot_app(factory, backend, None, false)
    }

    /// Create a manager actor with a custom factory, desired-state backend, and
    /// an optional boot-replay AppHandle (BGS-05 Leg B), plus the consent flag
    /// that gates the boot Start-replay (BGS-05 re-fix Leg A/Leg B coordination).
    fn setup_manager_with_factory_backend_and_boot_app(
        factory: ServiceFactory<tauri::test::MockRuntime>,
        backend: Option<Arc<dyn DesiredStateBackend>>,
        boot_app: Option<AppHandle<tauri::test::MockRuntime>>,
        consent_allows_auto_unlock: bool,
    ) -> ServiceManagerHandle<tauri::test::MockRuntime> {
        let (cmd_tx, cmd_rx) = mpsc::channel(16);
        let handle = ServiceManagerHandle::new(cmd_tx);
        tokio::spawn(manager_loop(
            cmd_rx,
            factory,
            28.0,
            0.0,
            15.0,
            15.0,
            false,
            false,
            4.0,
            backend,
            vec!["remoteMessaging".into()],
            true,
            NotifierPolicy::default(),
            None,
            boot_app,
            consent_allows_auto_unlock,
        ));
        handle
    }

    async fn send_set_on_complete(
        handle: &ServiceManagerHandle<tauri::test::MockRuntime>,
        callback: OnCompleteCallback,
    ) {
        handle
            .cmd_tx
            .send(ManagerCommand::SetOnComplete { callback })
            .await
            .unwrap();
    }

    /// Wait for the service to finish (is_running becomes false).
    /// Polls with a short sleep between attempts.
    async fn wait_until_stopped(
        handle: &ServiceManagerHandle<tauri::test::MockRuntime>,
        timeout_ms: u64,
    ) {
        let start = std::time::Instant::now();
        while start.elapsed().as_millis() < timeout_ms as u128 {
            if !send_is_running(handle).await {
                return;
            }
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }
        panic!("Service did not stop within {timeout_ms}ms");
    }

    // ── AC6 (Step 3): Callback fires on success ──────────────────────

    #[tokio::test]
    async fn callback_fires_on_success() {
        let handle = setup_manager_with_factory(Box::new(|| Box::new(ImmediateSuccessService)));
        let app = tauri::test::mock_app();

        let called = Arc::new(AtomicI8::new(-1));
        let called_clone = called.clone();
        send_set_on_complete(
            &handle,
            Box::new(move |success| {
                called_clone.store(if success { 1 } else { 0 }, Ordering::Release);
            }),
        )
        .await;

        send_start(&handle, app.handle().clone()).await.unwrap();
        wait_until_stopped(&handle, 1000).await;

        assert_eq!(
            called.load(Ordering::Acquire),
            1,
            "callback should be called with true"
        );
    }

    // ── AC7 (Step 3): Callback fires on error ────────────────────────

    #[tokio::test]
    async fn callback_fires_on_error() {
        let handle = setup_manager_with_factory(Box::new(|| Box::new(ImmediateErrorService)));
        let app = tauri::test::mock_app();

        let called = Arc::new(AtomicI8::new(-1));
        let called_clone = called.clone();
        send_set_on_complete(
            &handle,
            Box::new(move |success| {
                called_clone.store(if success { 1 } else { 0 }, Ordering::Release);
            }),
        )
        .await;

        send_start(&handle, app.handle().clone()).await.unwrap();
        wait_until_stopped(&handle, 1000).await;

        assert_eq!(
            called.load(Ordering::Acquire),
            0,
            "callback should be called with false on error"
        );
    }

    // ── AC8 (Step 3): Callback fires on init failure ─────────────────

    #[tokio::test]
    async fn callback_fires_on_init_failure() {
        let handle = setup_manager_with_factory(Box::new(|| Box::new(FailingInitService)));
        let app = tauri::test::mock_app();

        let called = Arc::new(AtomicI8::new(-1));
        let called_clone = called.clone();
        send_set_on_complete(
            &handle,
            Box::new(move |success| {
                called_clone.store(if success { 1 } else { 0 }, Ordering::Release);
            }),
        )
        .await;

        send_start(&handle, app.handle().clone()).await.unwrap();

        // Init failure: service was never truly running, so token gets cleared quickly.
        // Wait a short time for the spawned task to complete.
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        assert_eq!(
            called.load(Ordering::Acquire),
            0,
            "callback should be called with false on init failure"
        );
        assert!(
            !send_is_running(&handle).await,
            "should not be running after init failure"
        );
    }

    // ── AC9 (Step 3): No callback no panic ───────────────────────────

    #[tokio::test]
    async fn no_callback_no_panic() {
        let handle = setup_manager_with_factory(Box::new(|| Box::new(ImmediateSuccessService)));
        let app = tauri::test::mock_app();

        // Deliberately do NOT call SetOnComplete.
        let result = send_start(&handle, app.handle().clone()).await;
        assert!(result.is_ok(), "start without callback should succeed");

        wait_until_stopped(&handle, 1000).await;
        // If we get here without panicking, the test passes.
    }

    // ── N2: is_running returns false after natural completion ────────

    #[tokio::test]
    async fn is_running_false_after_natural_completion() {
        // Use a service that yields during run() so the is_running check
        // doesn't race with immediate completion.
        struct YieldingService;

        #[async_trait]
        impl BackgroundService<tauri::test::MockRuntime> for YieldingService {
            async fn init(
                &mut self,
                _ctx: &ServiceContext<tauri::test::MockRuntime>,
            ) -> Result<(), ServiceError> {
                Ok(())
            }

            async fn run(
                &mut self,
                _ctx: &ServiceContext<tauri::test::MockRuntime>,
            ) -> Result<(), ServiceError> {
                // Sleep long enough for the caller to observe is_running=true,
                // then complete naturally (no cancellation).
                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
                Ok(())
            }
        }

        let handle = setup_manager_with_factory(Box::new(|| Box::new(YieldingService)));
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        assert!(
            send_is_running(&handle).await,
            "should be running immediately after start"
        );

        // Wait for the service to complete naturally (no stop).
        wait_until_stopped(&handle, 2000).await;

        assert!(
            !send_is_running(&handle).await,
            "is_running should be false after natural completion"
        );
    }

    // ── AC10 (Step 3): Generation guard prevents stale cleanup ───────

    #[tokio::test]
    async fn generation_guard_prevents_stale_cleanup() {
        // First start with FailingInit (generation 1) — clears its own token.
        // Second start with a long-running BlockingService (generation 2) —
        // should reach AND stay Running because generation 1's stale cleanup
        // must not steal generation 2's freshly installed token.
        //
        // A long-running service (not ImmediateSuccess) is what makes this
        // assertion both meaningful and deterministic: it distinguishes
        // "gen-1 stole gen-2's token" (is_running would be false) from a
        // service that simply self-completed, and it prevents is_running from
        // flickering true→false out from under the assertion under load.
        let call_count = Arc::new(AtomicU8::new(0));
        let call_count_clone = call_count.clone();

        let handle = setup_manager_with_factory(Box::new(move || {
            let cc = call_count_clone.clone();
            // First call: FailingInit. Second call: BlockingService.
            // Use AtomicU8 to track which invocation this is.
            if cc.fetch_add(1, Ordering::AcqRel) == 0 {
                Box::new(FailingInitService) as Box<dyn BackgroundService<tauri::test::MockRuntime>>
            } else {
                Box::new(BlockingService)
            }
        }));
        let app = tauri::test::mock_app();

        // First start: init fails, token cleared by spawned task. Poll until
        // the generation-1 init failure has been recorded (last_error set)
        // instead of sleeping a fixed interval — this deterministically
        // establishes the stale-cleanup scenario before the second start.
        send_start(&handle, app.handle().clone()).await.unwrap();
        wait_until_error_recorded(&handle).await;

        // Second start: should succeed — generation guard prevented stale cleanup.
        let result = send_start(&handle, app.handle().clone()).await;
        assert!(
            result.is_ok(),
            "second start should succeed after init failure: {result:?}"
        );
        // BlockingService blocks in run(), so is_running is deterministically
        // true once Running is reached — no flicker race with self-completion.
        wait_until_running(&handle).await;
        assert!(
            send_is_running(&handle).await,
            "should be running after second start"
        );
    }

    // ── AC11 (Step 3): Callback captured at spawn time ───────────────

    #[tokio::test]
    async fn callback_captured_at_spawn_time() {
        let handle = setup_manager_with_factory(Box::new(|| Box::new(BlockingService)));
        let app = tauri::test::mock_app();

        // Set callback A, start, then set callback B.
        // When the service completes, A should fire (not B).
        let which = Arc::new(AtomicU8::new(0)); // 0=none, 1=A, 2=B
        let which_clone_a = which.clone();
        let which_clone_b = which.clone();

        send_set_on_complete(
            &handle,
            Box::new(move |_| {
                which_clone_a.store(1, Ordering::Release);
            }),
        )
        .await;

        send_start(&handle, app.handle().clone()).await.unwrap();

        // Service is blocking — set a NEW callback while it runs.
        send_set_on_complete(
            &handle,
            Box::new(move |_| {
                which_clone_b.store(2, Ordering::Release);
            }),
        )
        .await;

        // Stop the service — this triggers cleanup and callback.
        send_stop(&handle).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        assert_eq!(
            which.load(Ordering::Acquire),
            1,
            "callback A should fire, not B"
        );
    }

    // ── Mobile keepalive helpers ──────────────────────────────────────

    async fn send_set_mobile(
        handle: &ServiceManagerHandle<tauri::test::MockRuntime>,
        mobile: Arc<dyn MobileKeepalive>,
    ) {
        handle
            .cmd_tx
            .send(ManagerCommand::SetMobile { mobile })
            .await
            .unwrap();
    }

    // ── AC1 (Step 5): start_keepalive called on start ────────────────

    #[tokio::test]
    async fn start_keepalive_called_on_start() {
        let mock = MockMobile::new();
        let handle = setup_manager();
        let app = tauri::test::mock_app();

        send_set_mobile(&handle, mock.clone()).await;
        send_start(&handle, app.handle().clone()).await.unwrap();

        assert_eq!(
            mock.start_called.load(Ordering::Acquire),
            1,
            "start_keepalive should be called once"
        );
        assert_eq!(
            mock.last_label.lock().unwrap().as_deref(),
            Some("Service running"),
            "label should be forwarded"
        );
    }

    // ── AC2 (Step 5): start_keepalive failure rollback ───────────────

    #[tokio::test]
    async fn start_keepalive_failure_rollback() {
        let mock = MockMobile::new_failing();
        let handle = setup_manager();
        let app = tauri::test::mock_app();

        let callback_called = Arc::new(AtomicI8::new(-1));
        let cb_clone = callback_called.clone();
        send_set_on_complete(
            &handle,
            Box::new(move |success| {
                cb_clone.store(if success { 1 } else { 0 }, Ordering::Release);
            }),
        )
        .await;

        send_set_mobile(&handle, mock.clone()).await;

        let result = send_start(&handle, app.handle().clone()).await;
        assert!(
            matches!(result, Err(ServiceError::Platform(_))),
            "start should return Platform error on keepalive failure: {result:?}"
        );

        // Token should be cleared (not running).
        assert!(
            !send_is_running(&handle).await,
            "token should be rolled back after keepalive failure"
        );

        // Callback should be restored — can be set again.
        let callback_called2 = Arc::new(AtomicI8::new(-1));
        let cb_clone2 = callback_called2.clone();
        send_set_on_complete(
            &handle,
            Box::new(move |success| {
                cb_clone2.store(if success { 1 } else { 0 }, Ordering::Release);
            }),
        )
        .await;

        // Without the failing mobile, a start should succeed and callback should work.
        // Use a fresh manager without mobile to test callback restoration.
        let handle2 = setup_manager_with_factory(Box::new(|| Box::new(ImmediateSuccessService)));
        let callback_restored = Arc::new(AtomicI8::new(-1));
        let cb_r = callback_restored.clone();
        send_set_on_complete(
            &handle2,
            Box::new(move |success| {
                cb_r.store(if success { 1 } else { 0 }, Ordering::Release);
            }),
        )
        .await;
        send_start(&handle2, app.handle().clone()).await.unwrap();
        wait_until_stopped(&handle2, 1000).await;
        assert_eq!(
            callback_restored.load(Ordering::Acquire),
            1,
            "callback should fire after successful start (proves rollback restored it)"
        );
    }

    // ── AC1/AC2 (Step 11, H9): advisory scheduling failure is non-fatal ──
    //
    // On iOS the BGTask scheduler can be unavailable (Simulator / degraded
    // device). A `start_keepalive` failure there must NOT roll back the
    // in-process Core: the service still starts (`is_running` true) and the
    // status reports a distinct "scheduling degraded / foreground-only"
    // condition — distinguishable from a total start failure (which leaves the
    // service stopped, like the Android path in `start_keepalive_failure_rollback`).
    #[tokio::test]
    async fn advisory_scheduling_failure_starts_core_degraded() {
        let mock = MockMobile::new_failing_advisory();
        let handle = setup_manager();
        let app = tauri::test::mock_app();

        // Listen for the non-fatal degraded warning event.
        let event_received = Arc::new(AtomicBool::new(false));
        let event_received_clone = event_received.clone();
        let _listener = app
            .handle()
            .listen("background-service:state-degraded", move |_event| {
                event_received_clone.store(true, Ordering::Release);
            });

        send_set_mobile(&handle, mock.clone()).await;

        // Start must SUCCEED despite the scheduling failure (no rollback).
        send_start(&handle, app.handle().clone()).await.unwrap();
        wait_until_running(&handle).await;

        assert_eq!(
            mock.start_called.load(Ordering::Acquire),
            1,
            "start_keepalive should still be attempted once",
        );
        assert!(
            send_is_running(&handle).await,
            "Core must start despite advisory scheduling failure (no rollback)",
        );

        // Status reports the distinct degraded / foreground-only condition.
        let status = send_get_lifecycle_status(&handle).await;
        assert_eq!(
            status.degraded,
            Some(true),
            "advisory scheduling failure must report degraded",
        );
        assert_eq!(
            status.degraded_reason,
            Some("scheduling_degraded_foreground_only".into()),
            "degraded reason must name the foreground-only fallback",
        );

        // A non-fatal scheduling-degraded warning was emitted (not a fatal error).
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        assert!(
            event_received.load(Ordering::Acquire),
            "a non-fatal scheduling-degraded warning must be emitted",
        );
    }

    // ── AC3 (Step 5): stop_keepalive called on stop ──────────────────

    #[tokio::test]
    async fn stop_keepalive_called_on_stop() {
        let mock = MockMobile::new();
        let handle = setup_manager();
        let app = tauri::test::mock_app();

        send_set_mobile(&handle, mock.clone()).await;
        send_start(&handle, app.handle().clone()).await.unwrap();

        assert_eq!(
            mock.stop_called.load(Ordering::Acquire),
            0,
            "stop_keepalive should not be called yet"
        );

        send_stop(&handle).await.unwrap();

        assert_eq!(
            mock.stop_called.load(Ordering::Acquire),
            1,
            "stop_keepalive should be called once after stop"
        );
    }

    // ── stop_keepalive failure does not propagate ──────────────────────────

    /// Mock mobile where `stop_keepalive` always fails.
    struct MockMobileFailingStop;

    #[allow(clippy::too_many_arguments)]
    impl MobileKeepalive for MockMobileFailingStop {
        fn start_keepalive(
            &self,
            _label: &str,
            _foreground_service_type: &str,
            _ios_safety_timeout_secs: Option<f64>,
            _ios_processing_safety_timeout_secs: Option<f64>,
            _ios_earliest_refresh_begin_minutes: Option<f64>,
            _ios_earliest_processing_begin_minutes: Option<f64>,
            _ios_requires_external_power: Option<bool>,
            _ios_requires_network_connectivity: Option<bool>,
            _ios_processing_ceiling_multiplier: Option<f64>,
        ) -> Result<(), ServiceError> {
            Ok(())
        }

        fn stop_keepalive(&self) -> Result<(), ServiceError> {
            Err(ServiceError::Platform("mock stop failure".into()))
        }
    }

    #[tokio::test]
    async fn stop_keepalive_failure_does_not_propagate() {
        let handle = setup_manager();
        let app = tauri::test::mock_app();

        send_set_mobile(&handle, Arc::new(MockMobileFailingStop)).await;
        send_start(&handle, app.handle().clone()).await.unwrap();

        let result = send_stop(&handle).await;
        assert!(
            result.is_ok(),
            "stop should succeed even when stop_keepalive fails"
        );

        assert!(
            !send_is_running(&handle).await,
            "service should not be running after stop"
        );
    }

    // ── iOS safety timeout passed to mobile ──────────────────────────────

    #[tokio::test]
    async fn ios_safety_timeout_passed_to_mobile() {
        let mock = MockMobile::new();
        let (cmd_tx, cmd_rx) = mpsc::channel(16);
        let handle = ServiceManagerHandle::new(cmd_tx);
        let factory: ServiceFactory<tauri::test::MockRuntime> =
            Box::new(|| Box::new(BlockingService));
        // Use a custom timeout value (not default 28.0)
        tokio::spawn(manager_loop(
            cmd_rx,
            factory,
            15.0,
            0.0,
            15.0,
            15.0,
            false,
            false,
            4.0,
            None,
            vec!["remoteMessaging".into()],
            true,
            NotifierPolicy::default(),
            None,
            None,
            false,
        ));

        let app = tauri::test::mock_app();

        send_set_mobile(&handle, mock.clone()).await;
        send_start(&handle, app.handle().clone()).await.unwrap();

        // Verify the timeout was passed through to the mock
        let timeout = *mock.last_timeout_secs.lock().unwrap();
        assert_eq!(
            timeout,
            Some(15.0),
            "ios_safety_timeout_secs should be passed to mobile"
        );
    }

    // ── iOS processing timeout passed to mobile ──────────────────────────────

    #[tokio::test]
    async fn ios_processing_timeout_passed_to_mobile() {
        let mock = MockMobile::new();
        let (cmd_tx, cmd_rx) = mpsc::channel(16);
        let handle = ServiceManagerHandle::new(cmd_tx);
        let factory: ServiceFactory<tauri::test::MockRuntime> =
            Box::new(|| Box::new(BlockingService));
        // Use a custom processing timeout value
        tokio::spawn(manager_loop(
            cmd_rx,
            factory,
            28.0,
            60.0,
            15.0,
            15.0,
            false,
            false,
            4.0,
            None,
            vec!["remoteMessaging".into()],
            true,
            NotifierPolicy::default(),
            None,
            None,
            false,
        ));

        let app = tauri::test::mock_app();

        send_set_mobile(&handle, mock.clone()).await;
        send_start(&handle, app.handle().clone()).await.unwrap();

        // Verify the processing timeout was passed through to the mock
        let timeout = *mock.last_processing_timeout_secs.lock().unwrap();
        assert_eq!(
            timeout,
            Some(60.0),
            "ios_processing_safety_timeout_secs should be passed to mobile"
        );
    }

    // ── iOS processing ceiling multiplier passed to mobile (D2) ─────────

    #[tokio::test]
    async fn ios_processing_ceiling_multiplier_default_passed_to_mobile() {
        let mock = MockMobile::new();
        let (cmd_tx, cmd_rx) = mpsc::channel(16);
        let handle = ServiceManagerHandle::new(cmd_tx);
        let factory: ServiceFactory<tauri::test::MockRuntime> =
            Box::new(|| Box::new(BlockingService));
        // Default multiplier (4.0, as the named default fn returns)
        tokio::spawn(manager_loop(
            cmd_rx,
            factory,
            28.0,
            0.0,
            15.0,
            15.0,
            false,
            false,
            4.0,
            None,
            vec!["remoteMessaging".into()],
            true,
            NotifierPolicy::default(),
            None,
            None,
            false,
        ));

        let app = tauri::test::mock_app();

        send_set_mobile(&handle, mock.clone()).await;
        send_start(&handle, app.handle().clone()).await.unwrap();

        let multiplier = *mock.last_processing_ceiling_multiplier.lock().unwrap();
        assert_eq!(
            multiplier,
            Some(4.0),
            "default ios_processing_ceiling_multiplier should be passed to mobile"
        );
    }

    #[tokio::test]
    async fn ios_processing_ceiling_multiplier_override_passed_to_mobile() {
        let mock = MockMobile::new();
        let (cmd_tx, cmd_rx) = mpsc::channel(16);
        let handle = ServiceManagerHandle::new(cmd_tx);
        let factory: ServiceFactory<tauri::test::MockRuntime> =
            Box::new(|| Box::new(BlockingService));
        // Override multiplier (not default 4.0)
        tokio::spawn(manager_loop(
            cmd_rx,
            factory,
            28.0,
            0.0,
            15.0,
            15.0,
            false,
            false,
            6.0,
            None,
            vec!["remoteMessaging".into()],
            true,
            NotifierPolicy::default(),
            None,
            None,
            false,
        ));

        let app = tauri::test::mock_app();

        send_set_mobile(&handle, mock.clone()).await;
        send_start(&handle, app.handle().clone()).await.unwrap();

        let multiplier = *mock.last_processing_ceiling_multiplier.lock().unwrap();
        assert_eq!(
            multiplier,
            Some(6.0),
            "overridden ios_processing_ceiling_multiplier should be passed to mobile"
        );
    }

    // ── Service that captures ServiceContext fields for inspection ──────

    /// Service that captures `service_label` and `foreground_service_type`
    /// from the `ServiceContext` it receives in `init()`.
    /// Only compiled on mobile where those fields exist.
    #[cfg(mobile)]
    struct ContextCapturingService {
        captured_label: Arc<std::sync::Mutex<Option<String>>>,
        captured_fst: Arc<std::sync::Mutex<Option<String>>>,
    }

    #[cfg(mobile)]
    #[async_trait]
    impl BackgroundService<tauri::test::MockRuntime> for ContextCapturingService {
        async fn init(
            &mut self,
            ctx: &ServiceContext<tauri::test::MockRuntime>,
        ) -> Result<(), ServiceError> {
            *self.captured_label.lock().unwrap() = Some(ctx.service_label.clone());
            *self.captured_fst.lock().unwrap() = Some(ctx.foreground_service_type.clone());
            Ok(())
        }

        async fn run(
            &mut self,
            ctx: &ServiceContext<tauri::test::MockRuntime>,
        ) -> Result<(), ServiceError> {
            ctx.shutdown.cancelled().await;
            Ok(())
        }
    }

    // ── AC (Step 11): ServiceContext fields are populated on mobile ────

    #[cfg(mobile)]
    #[tokio::test]
    async fn service_context_fields_populated_on_mobile() {
        let captured_label: Arc<std::sync::Mutex<Option<String>>> =
            Arc::new(std::sync::Mutex::new(None));
        let captured_fst: Arc<std::sync::Mutex<Option<String>>> =
            Arc::new(std::sync::Mutex::new(None));
        let cl = captured_label.clone();
        let cf = captured_fst.clone();

        let handle = setup_manager_with_factory(Box::new(move || {
            let cl = cl.clone();
            let cf = cf.clone();
            Box::new(ContextCapturingService {
                captured_label: cl,
                captured_fst: cf,
            })
        }));
        let app = tauri::test::mock_app();

        let config = StartConfig {
            service_label: "Syncing".into(),
            foreground_service_type: "dataSync".into(),
        };

        send_start_with_config(&handle, config, app.handle().clone())
            .await
            .unwrap();

        // Give the spawned task time to run init() (which captures the values).
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        // On mobile, both fields should be populated as Strings
        assert_eq!(
            captured_label.lock().unwrap().as_deref(),
            Some("Syncing"),
            "service_label should be 'Syncing' on mobile"
        );
        assert_eq!(
            captured_fst.lock().unwrap().as_deref(),
            Some("dataSync"),
            "foreground_service_type should be 'dataSync' on mobile"
        );

        send_stop(&handle).await.unwrap();
    }

    // ── S1: handle_start accepts invalid foreground_service_type on desktop ──

    #[tokio::test]
    async fn handle_start_accepts_invalid_foreground_service_type_on_desktop() {
        // On desktop (cfg!(mobile) == false), the foreground_service_type
        // validation is skipped. Use validation disabled to bypass allowlist too.
        let handle = setup_manager_with_backend_and_allowlist(None, vec![], false);
        let app = tauri::test::mock_app();

        let config = StartConfig {
            service_label: "test".into(),
            foreground_service_type: "bogusType".into(),
        };

        let result = send_start_with_config(&handle, config, app.handle().clone()).await;
        assert!(
            result.is_ok(),
            "start with invalid fg type should succeed on desktop: {result:?}"
        );
        assert!(
            send_is_running(&handle).await,
            "service should be running after start with invalid type on desktop"
        );

        send_stop(&handle).await.unwrap();
    }

    // ── handle_start accepts all valid foreground_service_types ────────

    #[tokio::test]
    async fn handle_start_accepts_all_valid_foreground_service_types() {
        let all_types: Vec<String> = crate::models::VALID_FOREGROUND_SERVICE_TYPES
            .iter()
            .map(|s| (*s).to_string())
            .collect();
        for &valid_type in crate::models::VALID_FOREGROUND_SERVICE_TYPES {
            let handle = setup_manager_with_backend_and_allowlist(None, all_types.clone(), true);
            let app = tauri::test::mock_app();

            let config = StartConfig {
                service_label: "test".into(),
                foreground_service_type: valid_type.into(),
            };

            let result = send_start_with_config(&handle, config, app.handle().clone()).await;
            assert!(
                result.is_ok(),
                "start with valid type '{valid_type}' should succeed: {result:?}"
            );
            assert!(send_is_running(&handle).await);
            // Stop for cleanup
            send_stop(&handle).await.unwrap();
        }
    }

    // ── Allowlist enforcement tests ────────────────────────────────────

    #[tokio::test]
    async fn allowlist_rejected_type_returns_platform_error() {
        let handle =
            setup_manager_with_backend_and_allowlist(None, vec!["remoteMessaging".into()], true);
        let app = tauri::test::mock_app();

        let config = StartConfig {
            service_label: "test".into(),
            foreground_service_type: "specialUse".into(),
        };
        let result = send_start_with_config(&handle, config, app.handle().clone()).await;
        assert!(
            matches!(result, Err(ServiceError::Platform(ref msg)) if msg.contains("not allowed")),
            "disallowed type should return Platform error: {result:?}"
        );
        assert!(
            !send_is_running(&handle).await,
            "should not be running after allowlist rejection"
        );
    }

    #[tokio::test]
    async fn allowlist_allowed_type_succeeds() {
        let handle =
            setup_manager_with_backend_and_allowlist(None, vec!["remoteMessaging".into()], true);
        let app = tauri::test::mock_app();

        let config = StartConfig {
            service_label: "test".into(),
            foreground_service_type: "remoteMessaging".into(),
        };
        let result = send_start_with_config(&handle, config, app.handle().clone()).await;
        assert!(result.is_ok(), "allowed type should succeed: {result:?}");
        assert!(send_is_running(&handle).await);
        send_stop(&handle).await.unwrap();
    }

    // ── UpdateForegroundServiceType (spec 08 C6, Step 15) ────────────────
    //
    // The phoneCall FGS-type swap is gated by the same plugin-config allowlist
    // as start(). These pin the gate so a call answer cannot promote to a type
    // the app did not declare (tauri.conf.json.androidForegroundServiceTypes).

    #[tokio::test]
    async fn update_foreground_service_type_not_running_returns_not_running() {
        let handle = setup_manager_with_backend_and_allowlist(
            None,
            vec!["remoteMessaging".into(), "phoneCall".into()],
            true,
        );
        // No start → nothing to swap.
        let result = handle
            .update_foreground_service_type("phoneCall".into())
            .await;
        assert!(
            matches!(result, Err(ServiceError::NotRunning)),
            "update with no running service should be NotRunning: {result:?}"
        );
    }

    #[tokio::test]
    async fn update_foreground_service_type_allowlisted_phonecall_succeeds() {
        let handle = setup_manager_with_backend_and_allowlist(
            None,
            vec!["remoteMessaging".into(), "phoneCall".into()],
            true,
        );
        let app = tauri::test::mock_app();
        send_start_with_config(
            &handle,
            StartConfig {
                service_label: "call".into(),
                foreground_service_type: "remoteMessaging".into(),
            },
            app.handle().clone(),
        )
        .await
        .unwrap();

        let result = handle
            .update_foreground_service_type("phoneCall".into())
            .await;
        assert!(
            result.is_ok(),
            "allowlisted phoneCall update should succeed: {result:?}"
        );
        send_stop(&handle).await.unwrap();
    }

    #[tokio::test]
    async fn update_foreground_service_type_rejected_by_allowlist() {
        // App allowlist does NOT include phoneCall → update rejected even while
        // running. This is exactly why tauri.conf.json must add phoneCall.
        let handle =
            setup_manager_with_backend_and_allowlist(None, vec!["remoteMessaging".into()], true);
        let app = tauri::test::mock_app();
        send_start_with_config(
            &handle,
            StartConfig {
                service_label: "call".into(),
                foreground_service_type: "remoteMessaging".into(),
            },
            app.handle().clone(),
        )
        .await
        .unwrap();

        let result = handle
            .update_foreground_service_type("phoneCall".into())
            .await;
        assert!(
            matches!(result, Err(ServiceError::Platform(ref msg)) if msg.contains("not allowed")),
            "non-allowlisted phoneCall update should be rejected: {result:?}"
        );
        // A rejected update is a no-op on the token: the service keeps running.
        assert!(send_is_running(&handle).await);
        send_stop(&handle).await.unwrap();
    }

    // ── M5/M6: Android-only FGS-type gating (Step 14) ────────────────────
    //
    // The 14-type validation (M6) and the native `updateForegroundServiceType`
    // swap (M5) run only where the OS enforces foreground-service types — i.e.
    // Android (`enforces_foreground_service_type()` → true). iOS has no FGS-type
    // concept, so both are skipped there: calling them only produced
    // missing-native-method error noise. The mock simulates each platform.

    #[tokio::test]
    async fn ios_like_bridge_validates_no_fgs_type_on_start() {
        // iOS-like bridge (enforces → false) + allowlist disabled: a type that
        // is NOT one of the 14 valid Android types still starts cleanly — iOS
        // never runs the Android 14-type validation (M6).
        let handle = setup_manager_with_backend_and_allowlist(None, vec![], false);
        let mock = MockMobile::new(); // enforces_foreground_service_type() → false
        send_set_mobile(&handle, mock).await;
        let app = tauri::test::mock_app();

        let result = send_start_with_config(
            &handle,
            StartConfig {
                service_label: "call".into(),
                foreground_service_type: "iosBackgroundDelivery".into(),
            },
            app.handle().clone(),
        )
        .await;
        assert!(
            result.is_ok(),
            "iOS start with a non-Android FGS type should succeed (M6): {result:?}"
        );
        send_stop(&handle).await.unwrap();
    }

    #[tokio::test]
    async fn android_like_bridge_validates_fgs_type_on_start() {
        // Android-like bridge (enforces → true): an invalid 14-type is rejected
        // on start, exactly as before — the Android path is unchanged (M6).
        let handle = setup_manager_with_backend_and_allowlist(None, vec![], false);
        let mock = MockMobile::new_enforcing(); // enforces → true
        send_set_mobile(&handle, mock).await;
        let app = tauri::test::mock_app();

        let result = send_start_with_config(
            &handle,
            StartConfig {
                service_label: "call".into(),
                foreground_service_type: "notAValidType".into(),
            },
            app.handle().clone(),
        )
        .await;
        assert!(
            matches!(result, Err(ServiceError::Platform(ref m)) if m.contains("invalid foreground_service_type")),
            "Android start with an invalid FGS type should be rejected (M6): {result:?}"
        );
    }

    #[tokio::test]
    async fn ios_like_bridge_emits_zero_update_foreground_service_type() {
        // iOS-like bridge (enforces → false): swapping the call FGS type is a
        // success no-op that fires ZERO native `updateForegroundServiceType`
        // calls — the missing-native-method noise (M5) is gone.
        let handle = setup_manager_with_backend_and_allowlist(None, vec![], false);
        let mock = MockMobile::new(); // enforces → false
        send_set_mobile(&handle, mock.clone()).await;
        let app = tauri::test::mock_app();
        send_start_with_config(
            &handle,
            StartConfig {
                service_label: "call".into(),
                foreground_service_type: "remoteMessaging".into(),
            },
            app.handle().clone(),
        )
        .await
        .unwrap();

        // Call start (→ phoneCall) and call end (→ remoteMessaging).
        let answer = handle
            .update_foreground_service_type("phoneCall".into())
            .await;
        let end = handle
            .update_foreground_service_type("remoteMessaging".into())
            .await;
        assert!(
            answer.is_ok(),
            "iOS FGS swap should be a no-op Ok: {answer:?}"
        );
        assert!(end.is_ok(), "iOS FGS revert should be a no-op Ok: {end:?}");
        assert!(
            mock.update_type_calls().is_empty(),
            "iOS must fire zero updateForegroundServiceType calls (M5), got: {:?}",
            mock.update_type_calls()
        );
        send_stop(&handle).await.unwrap();
    }

    #[tokio::test]
    async fn android_like_bridge_swaps_fgs_type() {
        // Android-like bridge (enforces → true): the running service's type
        // swaps remoteMessaging → phoneCall → remoteMessaging via the native
        // handler — the Android swap behaviour is unchanged (M5).
        let handle = setup_manager_with_backend_and_allowlist(
            None,
            vec!["remoteMessaging".into(), "phoneCall".into()],
            true,
        );
        let mock = MockMobile::new_enforcing(); // enforces → true
        send_set_mobile(&handle, mock.clone()).await;
        let app = tauri::test::mock_app();
        send_start_with_config(
            &handle,
            StartConfig {
                service_label: "call".into(),
                foreground_service_type: "remoteMessaging".into(),
            },
            app.handle().clone(),
        )
        .await
        .unwrap();

        handle
            .update_foreground_service_type("phoneCall".into())
            .await
            .unwrap();
        handle
            .update_foreground_service_type("remoteMessaging".into())
            .await
            .unwrap();
        assert_eq!(
            mock.update_type_calls(),
            vec!["phoneCall".to_string(), "remoteMessaging".to_string()],
            "Android must swap the FGS type via the native handler (M5)"
        );
        send_stop(&handle).await.unwrap();
    }

    #[tokio::test]
    async fn allowlist_empty_type_rejected() {
        let handle = setup_manager_with_backend_and_allowlist(None, vec!["dataSync".into()], true);
        let app = tauri::test::mock_app();

        let config = StartConfig {
            service_label: "test".into(),
            foreground_service_type: "".into(),
        };
        let result = send_start_with_config(&handle, config, app.handle().clone()).await;
        assert!(
            matches!(result, Err(ServiceError::Platform(ref msg)) if msg.contains("must not be empty")),
            "empty type should be rejected: {result:?}"
        );
    }

    #[tokio::test]
    async fn allowlist_case_insensitive_match() {
        let handle =
            setup_manager_with_backend_and_allowlist(None, vec!["remoteMessaging".into()], true);
        let app = tauri::test::mock_app();

        let config = StartConfig {
            service_label: "test".into(),
            foreground_service_type: "RemoteMessaging".into(),
        };
        let result = send_start_with_config(&handle, config, app.handle().clone()).await;
        assert!(
            result.is_ok(),
            "case-insensitive match should succeed: {result:?}"
        );
        assert!(send_is_running(&handle).await);
        send_stop(&handle).await.unwrap();
    }

    #[tokio::test]
    async fn allowlist_validation_disabled_accepts_any_type() {
        let handle = setup_manager_with_backend_and_allowlist(None, vec!["dataSync".into()], false);
        let app = tauri::test::mock_app();

        let config = StartConfig {
            service_label: "test".into(),
            foreground_service_type: "specialUse".into(),
        };
        let result = send_start_with_config(&handle, config, app.handle().clone()).await;
        assert!(
            result.is_ok(),
            "validation disabled should accept any type: {result:?}"
        );
        assert!(send_is_running(&handle).await);
        send_stop(&handle).await.unwrap();
    }

    // ── State transition helpers ────────────────────────────────────────

    async fn send_get_state(
        handle: &ServiceManagerHandle<tauri::test::MockRuntime>,
    ) -> ServiceStatus {
        let (tx, rx) = oneshot::channel();
        handle
            .cmd_tx
            .send(ManagerCommand::GetState { reply: tx })
            .await
            .unwrap();
        rx.await.unwrap()
    }

    /// Poll the actor until it reports `Running` instead of sleeping a fixed
    /// duration. The service task transitions Initializing→Running on a
    /// separate runtime (`tauri::async_runtime::spawn`), so a fixed sleep
    /// races that transition under load; polling observes the real state and
    /// removes the flaky timing seam.
    async fn wait_until_running(handle: &ServiceManagerHandle<tauri::test::MockRuntime>) {
        for _ in 0..200 {
            if send_get_state(handle).await.state == ServiceLifecycle::Running {
                return;
            }
            tokio::time::sleep(std::time::Duration::from_millis(5)).await;
        }
        panic!("service did not reach Running within ~1s");
    }

    /// Poll until a service's init/run failure has been recorded (last_error
    /// set). Used to deterministically observe a generation's failure cleanup
    /// without relying on a fixed sleep.
    async fn wait_until_error_recorded(handle: &ServiceManagerHandle<tauri::test::MockRuntime>) {
        for _ in 0..200 {
            if send_get_state(handle).await.last_error.is_some() {
                return;
            }
            tokio::time::sleep(std::time::Duration::from_millis(5)).await;
        }
        panic!("service error was not recorded within ~1s");
    }

    // ── State transition: initial state is Idle ───────────────────────

    #[tokio::test]
    async fn get_state_returns_idle_initially() {
        let handle = setup_manager();
        let status = send_get_state(&handle).await;
        assert_eq!(status.state, ServiceLifecycle::Idle);
        assert_eq!(status.last_error, None);
    }

    // ── State transition: Idle → Initializing → Running → Stopped ─────

    #[tokio::test]
    async fn lifecycle_idle_to_running_to_stopped() {
        // Use BlockingService so we can reliably observe the Running state.
        let handle = setup_manager();
        let app = tauri::test::mock_app();

        // Idle initially
        let status = send_get_state(&handle).await;
        assert_eq!(status.state, ServiceLifecycle::Idle);

        // Start — transitions to Initializing, then Running after init()
        send_start(&handle, app.handle().clone()).await.unwrap();

        // Poll for Running (BlockingService stays Running) instead of a fixed
        // sleep, which races the actor's Initializing→Running transition under
        // parallel-suite load (mem-1781352466-ae2a).
        wait_until_running(&handle).await;
        let status = send_get_state(&handle).await;
        assert_eq!(status.state, ServiceLifecycle::Running);

        // Stop → Stopped
        send_stop(&handle).await.unwrap();
        let status = send_get_state(&handle).await;
        assert_eq!(status.state, ServiceLifecycle::Stopped);
        assert_eq!(status.last_error, None);
    }

    // ── State transition: Idle → Initializing → Stopped on init failure ─

    #[tokio::test]
    async fn lifecycle_init_failure_sets_stopped_with_error() {
        let handle = setup_manager_with_factory(Box::new(|| Box::new(FailingInitService)));
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();

        // Poll until the init failure is recorded instead of a fixed sleep,
        // which races the FailingInit cleanup under parallel-suite load
        // (mem-1781352466-ae2a). last_error set ⇒ the actor has reached Stopped.
        wait_until_error_recorded(&handle).await;

        let status = send_get_state(&handle).await;
        assert_eq!(status.state, ServiceLifecycle::Stopped);
        assert!(
            status.last_error.is_some(),
            "last_error should be set on init failure"
        );
        assert!(
            status.last_error.unwrap().contains("init error"),
            "error should mention init error"
        );
    }

    // ── State transition: explicit stop sets Stopped, clears last_error ─

    #[tokio::test]
    async fn lifecycle_explicit_stop_sets_stopped_clears_error() {
        let handle = setup_manager();
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        // Poll for Running instead of a fixed sleep, which races the
        // Initializing→Running transition under parallel-suite load
        // (mem-1781352466-ae2a).
        wait_until_running(&handle).await;

        let status = send_get_state(&handle).await;
        assert_eq!(status.state, ServiceLifecycle::Running);

        send_stop(&handle).await.unwrap();

        let status = send_get_state(&handle).await;
        assert_eq!(status.state, ServiceLifecycle::Stopped);
        assert_eq!(
            status.last_error, None,
            "explicit stop should clear last_error"
        );
    }

    // ── State transition: restart clears stale last_error ─────────────

    #[tokio::test]
    async fn restart_clears_stale_last_error() {
        // Step 1: start with a service whose init() fails → Stopped + last_error set
        let handle = setup_manager_with_factory(Box::new(|| Box::new(FailingInitService)));
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        wait_until_error_recorded(&handle).await;

        let status = send_get_state(&handle).await;
        assert_eq!(status.state, ServiceLifecycle::Stopped);
        assert!(
            status.last_error.is_some(),
            "should have error after init failure"
        );

        // Step 2: restart with a succeeding service — last_error must be cleared
        // We can't swap the factory, but we CAN verify the field is cleared
        // by starting again with the same failing service and checking that
        // handle_start resets last_error before the spawn.
        // Instead, use a two-phase factory: first fails, then succeeds.
        let call_count = Arc::new(AtomicUsize::new(0));
        let count_clone = call_count.clone();
        let handle2 = setup_manager_with_factory(Box::new(move || {
            let n = count_clone.fetch_add(1, Ordering::SeqCst);
            if n == 0 {
                Box::new(FailingInitService)
            } else {
                Box::new(ImmediateSuccessService)
            }
        }));
        let app2 = tauri::test::mock_app();

        // First start: init fails
        send_start(&handle2, app2.handle().clone()).await.unwrap();
        wait_until_error_recorded(&handle2).await;

        let status = send_get_state(&handle2).await;
        assert_eq!(status.state, ServiceLifecycle::Stopped);
        assert!(
            status.last_error.is_some(),
            "first run should set last_error"
        );

        // Second start: succeeds — last_error must be None.
        // handle_start clears last_error synchronously before send_start
        // returns; wait for the ImmediateSuccessService to reach its natural
        // Stopped completion so we observe the final state deterministically.
        send_start(&handle2, app2.handle().clone()).await.unwrap();
        wait_until_stopped(&handle2, 1000).await;

        let status = send_get_state(&handle2).await;
        // After successful init + run completion, state is Stopped (natural completion)
        // but last_error should be cleared by handle_start
        assert_eq!(
            status.last_error, None,
            "last_error must be cleared on restart, not stale from previous failure"
        );
    }

    // ── get_state via ServiceManagerHandle method ─────────────────────

    #[tokio::test]
    async fn get_state_handle_method_returns_idle() {
        let handle = setup_manager();
        let status = handle.get_state().await;
        assert_eq!(status.state, ServiceLifecycle::Idle);
        assert_eq!(status.last_error, None);
    }

    // ── stop_blocking sends Stop command and returns success from running ─

    #[tokio::test]
    async fn stop_blocking_returns_success_from_running() {
        let handle = Arc::new(setup_manager());
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        assert!(send_is_running(&handle).await);

        // Must call stop_blocking from outside the async runtime.
        let h = handle.clone();
        let result = tokio::task::spawn_blocking(move || h.stop_blocking())
            .await
            .expect("spawn_blocking panicked");
        assert!(
            result.is_ok(),
            "stop_blocking should succeed from running: {result:?}"
        );
        assert!(
            !send_is_running(&handle).await,
            "should not be running after stop_blocking"
        );
    }

    // ── stop_blocking returns NotRunning when idle ───────────────────────

    #[tokio::test]
    async fn stop_blocking_returns_not_running_when_idle() {
        let handle = Arc::new(setup_manager());

        let h = handle.clone();
        let result = tokio::task::spawn_blocking(move || h.stop_blocking())
            .await
            .expect("spawn_blocking panicked");
        assert!(
            matches!(result, Err(ServiceError::NotRunning)),
            "stop_blocking should return NotRunning when idle: {result:?}"
        );
    }

    #[tokio::test]
    async fn ios_processing_timeout_zero_passes_as_none() {
        let mock = MockMobile::new();
        let (cmd_tx, cmd_rx) = mpsc::channel(16);
        let handle = ServiceManagerHandle::new(cmd_tx);
        let factory: ServiceFactory<tauri::test::MockRuntime> =
            Box::new(|| Box::new(BlockingService));
        // Processing timeout = 0.0 (default, no cap)
        tokio::spawn(manager_loop(
            cmd_rx,
            factory,
            28.0,
            0.0,
            15.0,
            15.0,
            false,
            false,
            4.0,
            None,
            vec!["remoteMessaging".into()],
            true,
            NotifierPolicy::default(),
            None,
            None,
            false,
        ));

        let app = tauri::test::mock_app();

        send_set_mobile(&handle, mock.clone()).await;
        send_start(&handle, app.handle().clone()).await.unwrap();

        // Zero timeout should be passed as None
        let timeout = *mock.last_processing_timeout_secs.lock().unwrap();
        assert_eq!(
            timeout, None,
            "ios_processing_safety_timeout_secs of 0.0 should pass None to mobile"
        );
    }

    // ── Desired-state MockBackend ─────────────────────────────────────────

    /// Mock desired-state backend that records all saves in a Mutex<Vec>.
    struct MockDesiredStateBackend {
        saves: std::sync::Mutex<Vec<DesiredState>>,
    }

    impl MockDesiredStateBackend {
        fn new() -> Arc<Self> {
            Arc::new(Self {
                saves: std::sync::Mutex::new(Vec::new()),
            })
        }

        fn last_save(&self) -> Option<DesiredState> {
            self.saves.lock().unwrap().last().cloned()
        }

        #[allow(dead_code)]
        fn save_count(&self) -> usize {
            self.saves.lock().unwrap().len()
        }

        #[allow(dead_code)]
        fn saves(&self) -> std::sync::MutexGuard<'_, Vec<DesiredState>> {
            self.saves.lock().unwrap()
        }
    }

    impl DesiredStateBackend for MockDesiredStateBackend {
        fn load(&self) -> Result<DesiredState, String> {
            Ok(self
                .saves
                .lock()
                .unwrap()
                .last()
                .cloned()
                .unwrap_or_default())
        }

        fn save(&self, state: &DesiredState) -> Result<(), String> {
            self.saves.lock().unwrap().push(state.clone());
            Ok(())
        }

        fn clear(&self) -> Result<(), String> {
            self.saves.lock().unwrap().clear();
            Ok(())
        }
    }

    // ── BGS-05 Leg B: boot Start-replay from persisted desired-state ──────

    /// Poll `IsRunning` until true or `timeout_ms` elapses (boot replay fires
    /// when the manager_loop task is first scheduled).
    async fn poll_is_running(
        handle: &ServiceManagerHandle<tauri::test::MockRuntime>,
        timeout_ms: u64,
    ) -> bool {
        let start = std::time::Instant::now();
        loop {
            if send_is_running(handle).await {
                return true;
            }
            if start.elapsed().as_millis() >= timeout_ms as u128 {
                return false;
            }
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }
    }

    #[test]
    fn bgs05_should_replay_on_boot_decision() {
        // Pure decision fn (host-testable, no actor). `desired_running` is the
        // sole gate; the desktop lifecycle check + `handle_start` dispatch live
        // in `manager_loop`'s pre-loop block. NV-MUT (force false) REDs the
        // replay test; (force true) REDs the no-replay guards.
        let on = DesiredState {
            desired_running: true,
            ..Default::default()
        };
        let off = DesiredState {
            desired_running: false,
            ..Default::default()
        };
        assert!(should_replay_on_boot(&on), "desired_running=true ⇒ replay");
        assert!(
            !should_replay_on_boot(&off),
            "desired_running=false ⇒ no replay"
        );
    }

    #[tokio::test]
    async fn bgs05_replay_starts_on_boot_when_desired() {
        // Seed desired_running=true + a valid last_start_config. With boot_app
        // threaded, manager_loop replays a Start on entry (desktop lifecycle)
        // via handle_start — the SAME path a runtime Start takes. BlockingService
        // keeps is_running true. NV-MUT (should_replay_on_boot ⇒ false) REDs
        // ONLY this leg.
        let backend = MockDesiredStateBackend::new();
        backend
            .save(&DesiredState {
                desired_running: true,
                last_start_config: Some(
                    serde_json::to_value(StartConfig {
                        service_label: "App".into(),
                        foreground_service_type: "remoteMessaging".into(),
                    })
                    .unwrap(),
                ),
                ..Default::default()
            })
            .unwrap();
        let app = tauri::test::mock_app();
        let handle = setup_manager_with_factory_backend_and_boot_app(
            Box::new(|| Box::new(BlockingService)),
            Some(backend),
            Some(app.handle().clone()),
            true,
        );
        assert!(
            poll_is_running(&handle, 1000).await,
            "boot replay should start the service when desired_running=true"
        );
        let _ = send_stop(&handle).await;
    }

    #[tokio::test]
    async fn bgs05_no_replay_when_desired_false() {
        // desired_running=false ⇒ should_replay_on_boot is false ⇒ no Start on
        // boot even with boot_app + backend configured.
        let backend = MockDesiredStateBackend::new();
        backend
            .save(&DesiredState {
                desired_running: false,
                ..Default::default()
            })
            .unwrap();
        let app = tauri::test::mock_app();
        let handle = setup_manager_with_factory_backend_and_boot_app(
            Box::new(|| Box::new(BlockingService)),
            Some(backend),
            Some(app.handle().clone()),
            true,
        );
        // Give the loop a moment to (not) replay.
        tokio::time::sleep(std::time::Duration::from_millis(80)).await;
        assert!(
            !send_is_running(&handle).await,
            "no boot replay when desired_running=false"
        );
    }

    #[tokio::test]
    async fn bgs05_no_replay_without_backend() {
        // Regression guard: callers that pass backend=None see NO boot replay
        // (preserves the pre-Step-6 behavior; mirrors Step-5 unchanged-default
        // discipline). boot_app is Some here to prove the backend gate binds.
        let app = tauri::test::mock_app();
        let handle = setup_manager_with_factory_backend_and_boot_app(
            Box::new(|| Box::new(BlockingService)),
            None,
            Some(app.handle().clone()),
            true,
        );
        tokio::time::sleep(std::time::Duration::from_millis(80)).await;
        assert!(
            !send_is_running(&handle).await,
            "no boot replay without a desired-state backend"
        );
    }

    #[tokio::test]
    async fn bgs05_no_replay_when_consent_allows_auto_unlock_false() {
        // BGS-05 re-fix HEADLINE LEG-B PIN (Critic Blocker 2 — F2 load-bearing
        // wiring pin). The persisted desired-state says `desired_running=true`
        // with a valid `last_start_config`, AND `boot_app` is `Some` — every
        // OTHER replay gate is satisfied — but `consent_allows_auto_unlock=false`
        // ⇒ the replay guard must SHORT-CIRCUIT ⇒ no `handle_start` ⇒ the
        // service never reaches `is_running`. This is the consent half of the
        // Leg A/Leg B coordination: consent OFF suppresses the boot Start-replay
        // regardless of desired-state. NV-MUT (drop the `&&
        // consent_allows_auto_unlock` conjunct from the replay guard, OR pass
        // `true` here) ⇒ the replay fires ⇒ `BlockingService` sets is_running ⇒
        // the `!send_is_running` assert flips ⇒ RED. Pairs with the F3 builder
        // pin (`bgs05_start_headless_core_consent_off_stays_locked_despite_credential`
        // in the host crate): F2 gates the replay dispatch, F3 gates the builder
        // itself — together they close every boot-reachable auto-unlock path.
        let backend = MockDesiredStateBackend::new();
        backend
            .save(&DesiredState {
                desired_running: true,
                last_start_config: Some(
                    serde_json::to_value(StartConfig {
                        service_label: "App".into(),
                        foreground_service_type: "remoteMessaging".into(),
                    })
                    .unwrap(),
                ),
                ..Default::default()
            })
            .unwrap();
        let app = tauri::test::mock_app();
        let handle = setup_manager_with_factory_backend_and_boot_app(
            Box::new(|| Box::new(BlockingService)),
            Some(backend),
            Some(app.handle().clone()),
            false,
        );
        // Give the loop a moment to (not) replay.
        tokio::time::sleep(std::time::Duration::from_millis(80)).await;
        assert!(
            !send_is_running(&handle).await,
            "consent_allows_auto_unlock=false ⇒ no boot replay even with desired_running=true"
        );
    }

    // ── Desired-state actor integration tests ─────────────────────────────

    async fn send_set_desired_running(
        handle: &ServiceManagerHandle<tauri::test::MockRuntime>,
        desired: bool,
        config: Option<StartConfig>,
    ) -> Result<(), ServiceError> {
        let (tx, rx) = oneshot::channel();
        handle
            .cmd_tx
            .send(ManagerCommand::SetDesiredRunning {
                desired,
                config,
                reply: tx,
            })
            .await
            .unwrap();
        rx.await.unwrap()
    }

    #[tokio::test]
    async fn start_saves_desired_running_true() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_factory_and_backend(
            Box::new(|| Box::new(BlockingService)),
            Some(backend.clone()),
        );
        let app = tauri::test::mock_app();

        let config = StartConfig {
            service_label: "Syncing".into(),
            ..Default::default()
        };
        send_start_with_config(&handle, config, app.handle().clone())
            .await
            .unwrap();

        // Give the actor a moment to process the save (it happens after spawn).
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let last = backend
            .last_save()
            .expect("should have saved desired state");
        assert!(
            last.desired_running,
            "desired_running should be true after start"
        );
        assert!(
            last.last_start_config.is_some(),
            "last_start_config should be set"
        );
        assert!(
            last.last_start_epoch_ms.is_some(),
            "last_start_epoch_ms should be set"
        );
    }

    #[tokio::test]
    async fn stop_saves_desired_running_false_with_cleared_recovery() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_factory_and_backend(
            Box::new(|| Box::new(BlockingService)),
            Some(backend.clone()),
        );
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();

        // Simulate some recovery state that should be cleared on stop.
        {
            let mut saves = backend.saves.lock().unwrap();
            let last = saves.last_mut().unwrap();
            last.recovery_pending = true;
            last.recovery_reason = Some("boot".into());
            last.restart_attempt = 3;
        }

        send_stop(&handle).await.unwrap();

        let last = backend.last_save().expect("should have saved on stop");
        assert!(
            !last.desired_running,
            "desired_running should be false after stop"
        );
        assert!(
            last.last_start_config.is_none(),
            "last_start_config should be cleared"
        );
        assert!(
            last.last_start_epoch_ms.is_none(),
            "last_start_epoch_ms should be cleared"
        );
        assert!(!last.recovery_pending, "recovery_pending should be cleared");
        assert_eq!(
            last.recovery_reason, None,
            "recovery_reason should be cleared"
        );
        assert_eq!(last.restart_attempt, 0, "restart_attempt should be cleared");
    }

    #[tokio::test]
    async fn set_desired_running_saves_without_affecting_is_running() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_backend(Some(backend.clone()));

        // Not running initially
        assert!(!send_is_running(&handle).await);

        // Set desired_running=true WITHOUT starting
        let config = StartConfig {
            service_label: "AutoRestart".into(),
            ..Default::default()
        };
        send_set_desired_running(&handle, true, Some(config.clone()))
            .await
            .unwrap();

        // Should NOT be running
        assert!(
            !send_is_running(&handle).await,
            "SetDesiredRunning should not affect is_running"
        );

        // But desired state should be saved
        let last = backend.last_save().expect("should have saved");
        assert!(last.desired_running);
        assert!(last.last_start_config.is_some());

        // Now set desired_running=false
        send_set_desired_running(&handle, false, None)
            .await
            .unwrap();

        assert!(!send_is_running(&handle).await);

        let last = backend.last_save().expect("should have saved");
        assert!(!last.desired_running);
    }

    #[tokio::test]
    async fn no_backend_means_no_panic() {
        // No backend — should work fine without panicking.
        let handle = setup_manager();
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        send_stop(&handle).await.unwrap();

        send_set_desired_running(&handle, true, None).await.unwrap();
        // If we got here, no panic occurred.
    }

    #[tokio::test]
    async fn start_config_serialized_in_desired_state() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_backend_and_allowlist(
            Some(backend.clone()),
            vec!["specialUse".into()],
            true,
        );
        let app = tauri::test::mock_app();

        let config = StartConfig {
            service_label: "CustomLabel".into(),
            foreground_service_type: "specialUse".into(),
        };
        send_start_with_config(&handle, config, app.handle().clone())
            .await
            .unwrap();

        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let last = backend.last_save().expect("should have saved");
        let saved_config = last.last_start_config.expect("config should be set");
        assert_eq!(saved_config["serviceLabel"], "CustomLabel");
        assert_eq!(saved_config["foregroundServiceType"], "specialUse");
    }

    // ── GetState population from desired-state backend (Step 4, task 1c5e) ──

    #[tokio::test]
    async fn get_state_returns_desired_running_true_after_start() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_factory_and_backend(
            Box::new(|| Box::new(BlockingService)),
            Some(backend.clone()),
        );
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let status = send_get_state(&handle).await;
        assert_eq!(
            status.desired_running,
            Some(true),
            "desired_running should be Some(true) after start with backend"
        );
    }

    #[tokio::test]
    async fn get_state_returns_desired_running_false_after_stop() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_factory_and_backend(
            Box::new(|| Box::new(BlockingService)),
            Some(backend.clone()),
        );
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        send_stop(&handle).await.unwrap();

        let status = send_get_state(&handle).await;
        assert_eq!(
            status.desired_running,
            Some(false),
            "desired_running should be Some(false) after stop with backend"
        );
    }

    #[tokio::test]
    async fn get_state_returns_none_fields_when_no_backend() {
        let handle = setup_manager();
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let status = send_get_state(&handle).await;
        assert_eq!(status.desired_running, None);
        assert_eq!(status.native_state, None);
        assert_eq!(status.last_start_config, None);
        assert_eq!(status.last_heartbeat_at, None);
        assert_eq!(status.restart_attempt, None);
        assert_eq!(status.recovery_reason, None);
        assert_eq!(status.platform_error, None);
    }

    #[tokio::test]
    async fn get_state_returns_last_start_config_from_backend() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_backend_and_allowlist(
            Some(backend.clone()),
            vec!["specialUse".into()],
            true,
        );
        let app = tauri::test::mock_app();

        let config = StartConfig {
            service_label: "TestService".into(),
            foreground_service_type: "specialUse".into(),
        };
        send_start_with_config(&handle, config, app.handle().clone())
            .await
            .unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let status = send_get_state(&handle).await;
        let cfg = status
            .last_start_config
            .expect("last_start_config should be populated from backend");
        assert_eq!(cfg.service_label, "TestService");
        assert_eq!(cfg.foreground_service_type, "specialUse");
    }

    #[tokio::test]
    async fn get_state_populates_all_desired_state_fields() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_factory_and_backend(
            Box::new(|| Box::new(BlockingService)),
            Some(backend.clone()),
        );
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        // Mutate the backend state to simulate recovery fields being set.
        {
            let mut saves = backend.saves.lock().unwrap();
            let last = saves.last_mut().unwrap();
            last.last_native_state = Some("timeout".into());
            last.last_platform_error = Some("FGS timed out".into());
            last.restart_attempt = 3;
            last.recovery_reason = Some("boot recovery".into());
            last.last_heartbeat_epoch_ms = Some(1700000005000);
        }

        let status = send_get_state(&handle).await;
        assert_eq!(status.desired_running, Some(true));
        assert_eq!(status.native_state, Some(NativeState::Timeout));
        assert_eq!(status.platform_error, Some("FGS timed out".into()));
        assert_eq!(status.restart_attempt, Some(3));
        assert_eq!(status.recovery_reason, Some("boot recovery".into()));
        assert_eq!(status.last_heartbeat_at, Some(1700000005000));
    }

    #[tokio::test]
    async fn get_state_returns_platform_mode() {
        let handle = setup_manager();

        let status = send_get_state(&handle).await;
        // On desktop (Linux test runner), should be DesktopInProcess.
        assert_eq!(
            status.platform_mode,
            Some(LifecycleMode::DesktopInProcess),
            "platform_mode should be populated even without backend"
        );
    }

    // ── Step 13: EnableAutoRestart / DisableAutoRestart / GetDesiredState tests ──

    async fn send_enable_auto_restart(
        handle: &ServiceManagerHandle<tauri::test::MockRuntime>,
        config: Option<StartConfig>,
    ) -> Result<(), ServiceError> {
        let (tx, rx) = oneshot::channel();
        handle
            .cmd_tx
            .send(ManagerCommand::EnableAutoRestart { config, reply: tx })
            .await
            .unwrap();
        rx.await.unwrap()
    }

    async fn send_disable_auto_restart(
        handle: &ServiceManagerHandle<tauri::test::MockRuntime>,
    ) -> Result<(), ServiceError> {
        let (tx, rx) = oneshot::channel();
        handle
            .cmd_tx
            .send(ManagerCommand::DisableAutoRestart { reply: tx })
            .await
            .unwrap();
        rx.await.unwrap()
    }

    async fn send_get_desired_state(
        handle: &ServiceManagerHandle<tauri::test::MockRuntime>,
    ) -> Option<DesiredState> {
        let (tx, rx) = oneshot::channel();
        handle
            .cmd_tx
            .send(ManagerCommand::GetDesiredState { reply: tx })
            .await
            .unwrap();
        rx.await.unwrap()
    }

    #[tokio::test]
    async fn enable_auto_restart_saves_true_without_starting() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_backend(Some(backend.clone()));

        assert!(!send_is_running(&handle).await);

        send_enable_auto_restart(&handle, None).await.unwrap();

        // Should NOT start the service
        assert!(
            !send_is_running(&handle).await,
            "enableAutoRestart should not start the service"
        );

        // But desired state should be saved as true
        let ds = backend.last_save().expect("should have saved");
        assert!(ds.desired_running, "desired_running should be true");
    }

    #[tokio::test]
    async fn disable_auto_restart_saves_false_without_stopping() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_factory_and_backend(
            Box::new(|| Box::new(BlockingService)),
            Some(backend.clone()),
        );
        let app = tauri::test::mock_app();

        // Start the service first
        send_start(&handle, app.handle().clone()).await.unwrap();
        assert!(send_is_running(&handle).await);

        // Disable auto restart
        send_disable_auto_restart(&handle).await.unwrap();

        // Should NOT stop the service
        assert!(
            send_is_running(&handle).await,
            "disableAutoRestart should not stop the service"
        );

        // But desired state should be saved as false
        let ds = backend.last_save().expect("should have saved");
        assert!(!ds.desired_running, "desired_running should be false");
    }

    #[tokio::test]
    async fn enable_auto_restart_with_config_stores_config() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_backend(Some(backend.clone()));

        let config = StartConfig {
            service_label: "MyService".into(),
            foreground_service_type: "specialUse".into(),
        };
        send_enable_auto_restart(&handle, Some(config.clone()))
            .await
            .unwrap();

        let ds = backend.last_save().expect("should have saved");
        assert!(ds.desired_running);
        let saved_config = ds.last_start_config.expect("config should be stored");
        assert_eq!(saved_config["serviceLabel"], "MyService");
        assert_eq!(saved_config["foregroundServiceType"], "specialUse");
        assert!(
            ds.last_start_epoch_ms.is_some(),
            "should set last_start_epoch_ms"
        );
    }

    #[tokio::test]
    async fn disable_auto_restart_clears_recovery_fields() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_backend(Some(backend.clone()));

        // Enable with some recovery state
        send_enable_auto_restart(&handle, None).await.unwrap();
        {
            let mut saves = backend.saves.lock().unwrap();
            let last = saves.last_mut().unwrap();
            last.recovery_pending = true;
            last.recovery_reason = Some("boot".into());
            last.restart_attempt = 5;
        }

        // Disable should clear recovery
        send_disable_auto_restart(&handle).await.unwrap();

        let ds = backend.last_save().expect("should have saved");
        assert!(!ds.desired_running);
        assert!(!ds.recovery_pending, "recovery_pending should be cleared");
        assert_eq!(
            ds.recovery_reason, None,
            "recovery_reason should be cleared"
        );
        assert_eq!(ds.restart_attempt, 0, "restart_attempt should be cleared");
    }

    // ── Step 5 (H4): recovery commands mirror desired state to native ──────

    #[tokio::test]
    async fn enable_auto_restart_mirrors_desired_state_to_native() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_backend(Some(backend.clone()));
        let mock = MockMobile::new();
        send_set_mobile(&handle, mock.clone()).await;

        let config = StartConfig {
            service_label: "Mirror".into(),
            foreground_service_type: "specialUse".into(),
        };
        send_enable_auto_restart(&handle, Some(config.clone()))
            .await
            .unwrap();

        let mirrors = mock.mirror_calls.lock().unwrap();
        assert_eq!(
            mirrors.len(),
            1,
            "enableAutoRestart must mirror exactly once to native (H4), got {mirrors:?}"
        );
        let (desired, cfg) = &mirrors[0];
        assert!(*desired, "mirror should request desired_running=true");
        let cfg = cfg.as_ref().expect("config should be mirrored to native");
        assert_eq!(cfg["serviceLabel"], "Mirror");
        assert_eq!(cfg["foregroundServiceType"], "specialUse");
    }

    #[tokio::test]
    async fn disable_auto_restart_mirrors_false_to_native() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_backend(Some(backend.clone()));
        let mock = MockMobile::new();
        send_set_mobile(&handle, mock.clone()).await;

        send_disable_auto_restart(&handle).await.unwrap();

        let mirrors = mock.mirror_calls.lock().unwrap();
        assert_eq!(
            mirrors.len(),
            1,
            "disableAutoRestart must mirror exactly once to native (H4)"
        );
        let (desired, cfg) = &mirrors[0];
        assert!(!*desired, "mirror should request desired_running=false");
        assert!(cfg.is_none(), "disable must not mirror a start config");
    }

    #[tokio::test]
    async fn set_desired_running_mirrors_to_native() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_backend(Some(backend.clone()));
        let mock = MockMobile::new();
        send_set_mobile(&handle, mock.clone()).await;

        send_set_desired_running(&handle, true, None).await.unwrap();

        let mirrors = mock.mirror_calls.lock().unwrap();
        assert_eq!(
            mirrors.len(),
            1,
            "setDesiredRunning must mirror exactly once to native (H4)"
        );
        assert!(mirrors[0].0, "mirror should request desired_running=true");
    }

    #[tokio::test]
    async fn enable_auto_restart_without_mobile_does_not_panic() {
        // Desktop path: no mobile bridge — mirror is a no-op, command still
        // saves desired state (regression guard for the H4 mirror seam).
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_backend(Some(backend.clone()));

        send_enable_auto_restart(&handle, None).await.unwrap();

        let ds = backend
            .last_save()
            .expect("should still save without mobile");
        assert!(ds.desired_running);
    }

    #[tokio::test]
    async fn get_desired_state_returns_current_state() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_backend(Some(backend.clone()));

        // Initially returns default
        let ds = send_get_desired_state(&handle).await;
        assert!(ds.is_some());
        assert!(!ds.unwrap().desired_running);

        // After enable, returns updated state
        let config = StartConfig {
            service_label: "Test".into(),
            ..Default::default()
        };
        send_enable_auto_restart(&handle, Some(config))
            .await
            .unwrap();

        let ds = send_get_desired_state(&handle)
            .await
            .expect("should return state");
        assert!(ds.desired_running);
        assert!(ds.last_start_config.is_some());
    }

    #[tokio::test]
    async fn get_desired_state_returns_none_without_backend() {
        let handle = setup_manager();
        let ds = send_get_desired_state(&handle).await;
        assert!(
            ds.is_none(),
            "GetDesiredState should return None without a backend"
        );
    }

    #[tokio::test]
    async fn enable_disable_no_backend_no_panic() {
        let handle = setup_manager();

        // These should succeed (no-op) without a backend
        send_enable_auto_restart(&handle, None).await.unwrap();
        send_disable_auto_restart(&handle).await.unwrap();
    }

    #[tokio::test]
    async fn get_state_stop_clears_start_config_and_recovery() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_factory_and_backend(
            Box::new(|| Box::new(BlockingService)),
            Some(backend.clone()),
        );
        let app = tauri::test::mock_app();

        let config = StartConfig {
            service_label: "Syncing".into(),
            ..Default::default()
        };
        send_start_with_config(&handle, config, app.handle().clone())
            .await
            .unwrap();
        send_stop(&handle).await.unwrap();

        let status = send_get_state(&handle).await;
        assert_eq!(status.desired_running, Some(false));
        assert_eq!(
            status.last_start_config, None,
            "last_start_config should be None after stop"
        );
        assert_eq!(
            status.restart_attempt, None,
            "restart_attempt should be None after stop"
        );
        assert_eq!(
            status.recovery_reason, None,
            "recovery_reason should be None after stop"
        );
    }

    // ── Step 5 (task 8763): Desktop persistence integration tests ──────────

    use crate::desired_state::FileDesiredStateBackend;
    use std::path::PathBuf;

    fn temp_state_dir() -> PathBuf {
        tempfile::tempdir().unwrap().keep()
    }

    fn file_backend(dir: PathBuf) -> Arc<dyn DesiredStateBackend> {
        Arc::new(FileDesiredStateBackend::new(dir))
    }

    #[tokio::test]
    async fn enable_auto_restart_persists_desired_running_true_to_file() {
        let dir = temp_state_dir();
        let backend = file_backend(dir.clone());
        let handle = setup_manager_with_backend(Some(backend));

        send_enable_auto_restart(&handle, None).await.unwrap();

        // Verify the file was written with desired_running=true
        let file_backend = FileDesiredStateBackend::new(dir);
        let state = file_backend.load().unwrap();
        assert!(
            state.desired_running,
            "file should contain desired_running=true after enable_auto_restart"
        );
    }

    #[tokio::test]
    async fn simulated_process_restart_loads_persisted_state() {
        let dir = temp_state_dir();
        let backend = file_backend(dir.clone());
        let config = StartConfig {
            service_label: "PersistentSvc".into(),
            foreground_service_type: "dataSync".into(),
        };

        // Simulate first process: enable auto-restart with config
        let handle1 = setup_manager_with_backend(Some(backend));
        send_enable_auto_restart(&handle1, Some(config.clone()))
            .await
            .unwrap();

        // Drop the first manager (simulates process death)
        drop(handle1);
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        // Simulate second process: fresh manager with same backend dir
        let backend2 = file_backend(dir.clone());
        let handle2 = setup_manager_with_backend(Some(backend2));

        // The fresh manager should be able to load the persisted state
        let ds = send_get_desired_state(&handle2)
            .await
            .expect("should return persisted state");
        assert!(
            ds.desired_running,
            "persisted desired_running should be true after simulated restart"
        );
        let saved_config = ds
            .last_start_config
            .expect("config should be persisted across restart");
        assert_eq!(saved_config["serviceLabel"], "PersistentSvc");
    }

    #[tokio::test]
    async fn disable_auto_restart_clears_file_backed_state() {
        let dir = temp_state_dir();
        let backend = file_backend(dir.clone());
        let handle = setup_manager_with_backend(Some(backend));

        // First enable
        send_enable_auto_restart(&handle, None).await.unwrap();
        let ds = send_get_desired_state(&handle)
            .await
            .expect("should return state");
        assert!(ds.desired_running, "should be true after enable");

        // Now disable
        send_disable_auto_restart(&handle).await.unwrap();

        // Verify file-backed state is now false with cleared fields
        let file_backend = FileDesiredStateBackend::new(dir);
        let state = file_backend.load().unwrap();
        assert!(
            !state.desired_running,
            "file should contain desired_running=false after disable"
        );
        assert!(
            state.last_start_config.is_none(),
            "config should be cleared"
        );
        assert!(
            state.last_start_epoch_ms.is_none(),
            "epoch should be cleared"
        );
        assert!(!state.recovery_pending, "recovery should be cleared");
        assert_eq!(state.restart_attempt, 0, "restart_attempt should be 0");
    }

    #[tokio::test]
    async fn file_backend_get_desired_state_returns_none_without_backend() {
        let handle = setup_manager();

        let ds = send_get_desired_state(&handle).await;
        assert!(
            ds.is_none(),
            "get_desired_state should return None without backend (existing behavior preserved)"
        );
    }

    // ── Step 6 (task d820): StopWithReason command and handler tests ──────────

    async fn send_stop_with_reason(
        handle: &ServiceManagerHandle<tauri::test::MockRuntime>,
        reason: StopReason,
    ) -> Result<(), ServiceError> {
        let (tx, rx) = oneshot::channel();
        handle
            .cmd_tx
            .send(ManagerCommand::StopWithReason { reason, reply: tx })
            .await
            .unwrap();
        rx.await.unwrap()
    }

    #[tokio::test]
    async fn stop_with_reason_user_stop_clears_desired_state() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_factory_and_backend(
            Box::new(|| Box::new(BlockingService)),
            Some(backend.clone()),
        );
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let saves_before = backend.saves.lock().unwrap().len();

        send_stop_with_reason(&handle, StopReason::UserStop)
            .await
            .unwrap();

        // UserStop should save desired_running=false
        let saves = backend.saves.lock().unwrap();
        assert_eq!(
            saves.len(),
            saves_before + 1,
            "UserStop should save a new desired state"
        );
        let last = saves.last().unwrap();
        assert!(
            !last.desired_running,
            "UserStop should clear desired_running"
        );
        assert!(last.last_start_config.is_none(), "config should be cleared");
    }

    #[tokio::test]
    async fn stop_with_reason_app_stop_clears_desired_state() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_factory_and_backend(
            Box::new(|| Box::new(BlockingService)),
            Some(backend.clone()),
        );
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let saves_before = backend.saves.lock().unwrap().len();

        send_stop_with_reason(&handle, StopReason::AppStop)
            .await
            .unwrap();

        let saves = backend.saves.lock().unwrap();
        assert_eq!(saves.len(), saves_before + 1);
        assert!(
            !saves.last().unwrap().desired_running,
            "AppStop should clear desired_running"
        );
    }

    // ── D1 NotifySink seam tests (Step 2: wiring only, no fire points) ──

    #[tokio::test]
    async fn recording_sink_records_notify_calls() {
        let sink = RecordingSink::new();
        sink.notify("bg-timeout", "title", "body");
        assert_eq!(
            sink.calls(),
            vec![("bg-timeout".into(), "title".into(), "body".into())]
        );
    }

    // ── D1 fire-point tests (Step 3) ──────────────────────────────────

    #[tokio::test]
    async fn timeout_stop_with_default_policy_fires_nothing() {
        // Default policy (everything off) must keep stops silent even with
        // a live sink installed.
        let sink = RecordingSink::new();
        let handle = setup_manager_with_sink(NotifierPolicy::default(), sink.clone());
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        wait_until_running(&handle).await;
        send_stop_with_reason(&handle, StopReason::PlatformTimeout)
            .await
            .unwrap();

        assert!(
            sink.calls().is_empty(),
            "default policy must not notify on PlatformTimeout"
        );
    }

    #[tokio::test]
    async fn timeout_stop_fires_bg_timeout_when_policy_on() {
        let sink = RecordingSink::new();
        let policy = NotifierPolicy {
            on_timeout: true,
            on_recovery: false,
        };
        let handle = setup_manager_with_sink(policy, sink.clone());
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        wait_until_running(&handle).await;
        send_stop_with_reason(&handle, StopReason::PlatformTimeout)
            .await
            .unwrap();

        let calls = sink.calls();
        assert_eq!(
            calls.len(),
            1,
            "exactly one notification on PlatformTimeout"
        );
        assert_eq!(calls[0].0, "bg-timeout", "stable id so repeats replace");

        // PlatformExpiration is the other platform-pause reason and must use
        // the SAME stable id so notices replace rather than stack.
        send_start(&handle, app.handle().clone()).await.unwrap();
        wait_until_running(&handle).await;
        send_stop_with_reason(&handle, StopReason::PlatformExpiration)
            .await
            .unwrap();

        let calls = sink.calls();
        assert_eq!(calls.len(), 2, "PlatformExpiration also notifies");
        assert_eq!(calls[1].0, "bg-timeout");
    }

    #[tokio::test]
    async fn user_stop_fires_nothing_even_with_timeout_policy_on() {
        let sink = RecordingSink::new();
        let policy = NotifierPolicy {
            on_timeout: true,
            on_recovery: true,
        };
        let handle = setup_manager_with_sink(policy, sink.clone());
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        wait_until_running(&handle).await;
        send_stop_with_reason(&handle, StopReason::UserStop)
            .await
            .unwrap();

        assert!(
            sink.calls().is_empty(),
            "intentional user stop must never notify"
        );
    }

    #[tokio::test]
    async fn recovery_acceptance_fires_bg_recovery_not_the_stop_path() {
        let sink = RecordingSink::new();
        let policy = NotifierPolicy {
            on_timeout: false,
            on_recovery: true,
        };
        let handle = setup_manager_with_sink(policy, sink.clone());
        let app = tauri::test::mock_app();

        // A STOP with reason OsRestart is not recovery acceptance and must
        // not notify (Design Critic concern #1).
        send_start(&handle, app.handle().clone()).await.unwrap();
        wait_until_running(&handle).await;
        send_stop_with_reason(&handle, StopReason::OsRestart)
            .await
            .unwrap();
        assert!(
            sink.calls().is_empty(),
            "stop with reason OsRestart is not recovery acceptance"
        );

        // The ACCEPTANCE event fires exactly one bg-recovery, without any
        // service-running precondition (the native layer owns the restart).
        send_native_event(&handle, NativeLifecycleEvent::AndroidOsRestartAccepted)
            .await
            .unwrap();
        let calls = sink.calls();
        assert_eq!(calls.len(), 1, "exactly one notification on acceptance");
        assert_eq!(calls[0].0, "bg-recovery", "stable id so repeats replace");

        // Boot-recovery acceptance uses the SAME stable id.
        send_native_event(&handle, NativeLifecycleEvent::AndroidBootRecoveryAccepted)
            .await
            .unwrap();
        let calls = sink.calls();
        assert_eq!(calls.len(), 2, "boot-recovery acceptance also notifies");
        assert_eq!(calls[1].0, "bg-recovery");
    }

    #[tokio::test]
    async fn fire_points_with_no_sink_installed_do_not_panic() {
        // All-on policy but no sink (headless daemon): both fire points must
        // be safe no-ops.
        let policy = NotifierPolicy {
            on_timeout: true,
            on_recovery: true,
        };
        let handle = setup_manager_with_policy_and_sink(policy, None);
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        wait_until_running(&handle).await;
        send_stop_with_reason(&handle, StopReason::PlatformTimeout)
            .await
            .unwrap();
        send_native_event(&handle, NativeLifecycleEvent::AndroidOsRestartAccepted)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn android_derived_policy_suppresses_both_fire_points() {
        // DEC-002: on Android with androidOnTimeout=notifyUser the Kotlin
        // layer already posts native notifications — the derived policy must
        // suppress both plugin-side fire points even with both keys true.
        let config = crate::models::PluginConfig {
            notify_on_timeout: true,
            notify_on_recovery: true,
            android_on_timeout: "notifyUser".into(),
            ..Default::default()
        };
        let policy = NotifierPolicy::derive(&config, true);

        let sink = RecordingSink::new();
        let handle = setup_manager_with_sink(policy, sink.clone());
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        wait_until_running(&handle).await;
        send_stop_with_reason(&handle, StopReason::PlatformTimeout)
            .await
            .unwrap();
        send_native_event(&handle, NativeLifecycleEvent::AndroidOsRestartAccepted)
            .await
            .unwrap();

        assert!(
            sink.calls().is_empty(),
            "android-derived policy must suppress both fire points (DEC-002)"
        );
    }

    #[tokio::test]
    async fn stop_with_reason_native_notification_stop_clears_desired_state() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_factory_and_backend(
            Box::new(|| Box::new(BlockingService)),
            Some(backend.clone()),
        );
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let saves_before = backend.saves.lock().unwrap().len();

        send_stop_with_reason(&handle, StopReason::NativeNotificationStop)
            .await
            .unwrap();

        let saves = backend.saves.lock().unwrap();
        assert_eq!(saves.len(), saves_before + 1);
        assert!(
            !saves.last().unwrap().desired_running,
            "NativeNotificationStop should clear desired_running"
        );
    }

    #[tokio::test]
    async fn stop_with_reason_task_completed_clears_desired_state() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_factory_and_backend(
            Box::new(|| Box::new(BlockingService)),
            Some(backend.clone()),
        );
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let saves_before = backend.saves.lock().unwrap().len();

        send_stop_with_reason(&handle, StopReason::TaskCompleted)
            .await
            .unwrap();

        let saves = backend.saves.lock().unwrap();
        assert_eq!(saves.len(), saves_before + 1);
        assert!(
            !saves.last().unwrap().desired_running,
            "TaskCompleted should clear desired_running"
        );
    }

    #[tokio::test]
    async fn stop_with_reason_platform_expiration_preserves_desired_state() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_factory_and_backend(
            Box::new(|| Box::new(BlockingService)),
            Some(backend.clone()),
        );
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let saves_before = backend.saves.lock().unwrap().len();

        send_stop_with_reason(&handle, StopReason::PlatformExpiration)
            .await
            .unwrap();

        let saves = backend.saves.lock().unwrap();
        assert_eq!(
            saves.len(),
            saves_before,
            "PlatformExpiration should not save new desired state"
        );
        assert!(
            saves.last().unwrap().desired_running,
            "desired_running should remain true"
        );
    }

    #[tokio::test]
    async fn stop_with_reason_platform_timeout_preserves_desired_state() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_factory_and_backend(
            Box::new(|| Box::new(BlockingService)),
            Some(backend.clone()),
        );
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let saves_before = backend.saves.lock().unwrap().len();

        send_stop_with_reason(&handle, StopReason::PlatformTimeout)
            .await
            .unwrap();

        let saves = backend.saves.lock().unwrap();
        assert_eq!(
            saves.len(),
            saves_before,
            "PlatformTimeout should not save new desired state"
        );
        assert!(
            saves.last().unwrap().desired_running,
            "desired_running should remain true"
        );
    }

    #[tokio::test]
    async fn stop_with_reason_error_preserves_desired_state() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_factory_and_backend(
            Box::new(|| Box::new(BlockingService)),
            Some(backend.clone()),
        );
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let saves_before = backend.saves.lock().unwrap().len();

        send_stop_with_reason(&handle, StopReason::Error)
            .await
            .unwrap();

        let saves = backend.saves.lock().unwrap();
        assert_eq!(
            saves.len(),
            saves_before,
            "Error should not save new desired state"
        );
        assert!(
            saves.last().unwrap().desired_running,
            "desired_running should remain true"
        );
    }

    #[tokio::test]
    async fn stop_with_reason_not_running_returns_not_running() {
        let handle = setup_manager();

        let result = send_stop_with_reason(&handle, StopReason::UserStop).await;
        assert!(
            matches!(result, Err(ServiceError::NotRunning)),
            "StopWithReason should return NotRunning when idle"
        );
    }

    #[tokio::test]
    async fn stop_with_reason_cancels_service() {
        let handle = setup_manager();
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        assert!(send_is_running(&handle).await);

        send_stop_with_reason(&handle, StopReason::UserStop)
            .await
            .unwrap();

        assert!(
            !send_is_running(&handle).await,
            "service should be stopped after StopWithReason"
        );
    }

    #[tokio::test]
    async fn stop_with_reason_stops_mobile_keepalive() {
        let mock = MockMobile::new();
        let handle = setup_manager();
        let app = tauri::test::mock_app();

        send_set_mobile(&handle, mock.clone()).await;
        send_start(&handle, app.handle().clone()).await.unwrap();

        assert_eq!(mock.stop_called.load(Ordering::Acquire), 0);

        send_stop_with_reason(&handle, StopReason::UserStop)
            .await
            .unwrap();

        assert_eq!(
            mock.stop_called.load(Ordering::Acquire),
            1,
            "stop_keepalive should be called once after StopWithReason"
        );
    }

    // ── Step 6 (task fee4): handle_stop delegates to handle_stop_with_reason ──

    #[tokio::test]
    async fn stop_delegates_to_stop_with_reason_user_stop_clears_desired() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_factory_and_backend(
            Box::new(|| Box::new(BlockingService)),
            Some(backend.clone()),
        );
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let saves_before = backend.saves.lock().unwrap().len();

        // Plain Stop should behave like StopWithReason(UserStop) — clear desired state
        send_stop(&handle).await.unwrap();

        let saves = backend.saves.lock().unwrap();
        assert_eq!(
            saves.len(),
            saves_before + 1,
            "Stop should save desired state (delegates to StopWithReason(UserStop))"
        );
        assert!(
            !saves.last().unwrap().desired_running,
            "Stop should clear desired_running"
        );
    }

    // ── Step 6 (task fee4): ServiceManagerHandle::stop_with_reason ──────────

    #[tokio::test]
    async fn stop_with_reason_handle_method_stops_service() {
        let handle = setup_manager();
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        assert!(send_is_running(&handle).await);

        handle.stop_with_reason(StopReason::UserStop).await.unwrap();

        assert!(
            !send_is_running(&handle).await,
            "service should be stopped after stop_with_reason"
        );
    }

    #[tokio::test]
    async fn stop_with_reason_handle_method_preserves_desired_for_platform_timeout() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_factory_and_backend(
            Box::new(|| Box::new(BlockingService)),
            Some(backend.clone()),
        );
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let saves_before = backend.saves.lock().unwrap().len();

        handle
            .stop_with_reason(StopReason::PlatformTimeout)
            .await
            .unwrap();

        let saves = backend.saves.lock().unwrap();
        assert_eq!(
            saves.len(),
            saves_before,
            "PlatformTimeout should not save new desired state"
        );
        assert!(
            saves.last().unwrap().desired_running,
            "desired_running should remain true"
        );
    }

    #[tokio::test]
    async fn stop_with_reason_handle_method_returns_not_running_when_idle() {
        let handle = setup_manager();

        let result = handle.stop_with_reason(StopReason::UserStop).await;
        assert!(
            matches!(result, Err(ServiceError::NotRunning)),
            "stop_with_reason should return NotRunning when idle"
        );
    }

    // ── Step 6 (task fee4): ServiceManagerHandle::stop_blocking_with_reason ──

    #[tokio::test]
    async fn stop_blocking_with_reason_stops_service() {
        let handle = Arc::new(setup_manager());
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        assert!(send_is_running(&handle).await);

        let h = handle.clone();
        let result =
            tokio::task::spawn_blocking(move || h.stop_blocking_with_reason(StopReason::AppStop))
                .await
                .expect("spawn_blocking panicked");

        assert!(
            result.is_ok(),
            "stop_blocking_with_reason should succeed: {result:?}"
        );
        assert!(
            !send_is_running(&handle).await,
            "service should be stopped after stop_blocking_with_reason"
        );
    }

    #[tokio::test]
    async fn stop_blocking_with_reason_returns_not_running_when_idle() {
        let handle = Arc::new(setup_manager());

        let h = handle.clone();
        let result =
            tokio::task::spawn_blocking(move || h.stop_blocking_with_reason(StopReason::UserStop))
                .await
                .expect("spawn_blocking panicked");

        assert!(
            matches!(result, Err(ServiceError::NotRunning)),
            "stop_blocking_with_reason should return NotRunning when idle: {result:?}"
        );
    }

    // ── Step 6 (task d336): Idempotent stop and PlatformExpiration keepalive ──

    #[tokio::test]
    async fn stop_with_reason_idempotent_second_returns_not_running() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_factory_and_backend(
            Box::new(|| Box::new(BlockingService)),
            Some(backend.clone()),
        );
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        // First stop succeeds
        send_stop_with_reason(&handle, StopReason::UserStop)
            .await
            .unwrap();

        let saves_after_first = backend.saves.lock().unwrap().len();

        // Second stop returns NotRunning with no additional side effects
        let result = send_stop_with_reason(&handle, StopReason::UserStop).await;
        assert!(
            matches!(result, Err(ServiceError::NotRunning)),
            "second StopWithReason should return NotRunning: {result:?}"
        );

        let saves_after_second = backend.saves.lock().unwrap().len();
        assert_eq!(
            saves_after_first, saves_after_second,
            "second StopWithReason should not produce additional desired-state saves"
        );
    }

    #[tokio::test]
    async fn stop_with_reason_platform_expiration_skips_stop_keepalive() {
        let mock = MockMobile::new();
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_factory_and_backend(
            Box::new(|| Box::new(BlockingService)),
            Some(backend.clone()),
        );
        let app = tauri::test::mock_app();

        send_set_mobile(&handle, mock.clone()).await;
        send_start(&handle, app.handle().clone()).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        assert_eq!(
            mock.stop_called.load(Ordering::Acquire),
            0,
            "stop_keepalive should not be called yet"
        );

        let saves_before = backend.saves.lock().unwrap().len();

        send_stop_with_reason(&handle, StopReason::PlatformExpiration)
            .await
            .unwrap();

        assert!(!send_is_running(&handle).await, "service should be stopped");
        assert_eq!(
            mock.stop_called.load(Ordering::Acquire),
            0,
            "PlatformExpiration should NOT call stop_keepalive"
        );

        // Desired state should be preserved (not cleared)
        let saves = backend.saves.lock().unwrap();
        assert_eq!(
            saves.len(),
            saves_before,
            "PlatformExpiration should not save new desired state"
        );
        assert!(
            saves.last().unwrap().desired_running,
            "desired_running should remain true"
        );
    }

    // ── Step 8 (H2/M13): stop-reason matrix per design §5.4 ─────────────────

    /// Every `StopReason` maps to the expected `should_stop_keepalive` /
    /// `should_clear_desired_state` policy per design §5.4. `clear_desired`
    /// gates the Swift `UserDefaults` `desired=false` write, so it doubles as
    /// the "write UD desired=false?" column. `PlatformTimeout` and `ProcessExit`
    /// preserve desired state and skip keepalive teardown (M13/H2).
    #[test]
    fn stop_reason_matrix_matches_design_5_4() {
        // (reason, should_stop_keepalive, should_clear_desired_state)
        let matrix = [
            (StopReason::UserStop, true, true),
            (StopReason::AppStop, true, true),
            (StopReason::NativeNotificationStop, true, true),
            (StopReason::TaskCompleted, true, true),
            (StopReason::OsRestart, true, false),
            (StopReason::BootRecovery, true, false),
            (StopReason::Error, true, false),
            (StopReason::PlatformExpiration, false, false),
            // M13: cancel-listener timeout preserves desired + skips keepalive.
            (StopReason::PlatformTimeout, false, false),
            // H2: OS-driven exit preserves desired + skips keepalive.
            (StopReason::ProcessExit, false, false),
        ];
        for (reason, expect_stop_keepalive, expect_clear_desired) in matrix {
            assert_eq!(
                should_stop_keepalive(reason),
                expect_stop_keepalive,
                "should_stop_keepalive mismatch for {reason:?}"
            );
            assert_eq!(
                should_clear_desired_state(reason),
                expect_clear_desired,
                "should_clear_desired_state mismatch for {reason:?}"
            );
        }
    }

    /// H2: an OS-driven `ProcessExit` (the iOS `RunEvent::Exit` path) stops the
    /// service but preserves desired state and leaves the keepalive / BGTask
    /// schedule intact — it must not masquerade as a `UserStop` that erases
    /// recovery intent. A genuine user stop is covered by the UserStop tests.
    #[tokio::test]
    async fn process_exit_preserves_desired_and_keepalive() {
        let mock = MockMobile::new();
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_factory_and_backend(
            Box::new(|| Box::new(BlockingService)),
            Some(backend.clone()),
        );
        let app = tauri::test::mock_app();

        send_set_mobile(&handle, mock.clone()).await;
        send_start(&handle, app.handle().clone()).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let saves_before = backend.saves.lock().unwrap().len();

        send_stop_with_reason(&handle, StopReason::ProcessExit)
            .await
            .unwrap();

        assert!(!send_is_running(&handle).await, "service should be stopped");

        // H2: keepalive (BGTask schedule) must survive an OS-driven exit.
        assert_eq!(
            mock.stop_called.load(Ordering::Acquire),
            0,
            "ProcessExit should NOT call stop_keepalive (H2)"
        );

        // Desired state must be preserved so recovery can resume delivery.
        let saves = backend.saves.lock().unwrap();
        assert_eq!(
            saves.len(),
            saves_before,
            "ProcessExit should not save new desired state"
        );
        assert!(
            saves.last().unwrap().desired_running,
            "ProcessExit must preserve desired_running=true"
        );
    }

    // ── CORE-01: terminal-reason slot contract ─────────────────────────────
    //
    // The actor emits a single terminal PluginEvent per generation. An
    // explicit stop reason (set by `handle_stop_with_reason` before cancel)
    // wins over the inline Ok/Err classification; natural completion emits
    // `TaskCompleted`; unprompted error emits `Error`. Natural completion
    // also clears persisted desired intent; unprompted error preserves it.
    /// Capture every `background-service://event` payload JSON string into a
    /// `Vec<String>` so terminal-event tests can assert on the exact emitted
    /// reason/type. Returns `(captured, listener_id)` so the caller keeps the
    /// listener alive for the test's lifetime.
    fn capture_plugin_events<R: tauri::Runtime>(
        app: &tauri::AppHandle<R>,
    ) -> (Arc<std::sync::Mutex<Vec<String>>>, tauri::EventId) {
        let captured = Arc::new(std::sync::Mutex::new(Vec::new()));
        let captured_clone = captured.clone();
        let id = app.listen("background-service://event", move |event: tauri::Event| {
            // `payload()` returns `&str` in Tauri 2 (the JSON-serialized
            // PluginEvent). Clone into the capture buffer.
            captured_clone
                .lock()
                .unwrap()
                .push(event.payload().to_string());
        });
        (captured, id)
    }

    /// YieldingOkService: init ok, run sleeps briefly then returns Ok.
    struct YieldingOkService;
    #[async_trait]
    impl BackgroundService<tauri::test::MockRuntime> for YieldingOkService {
        async fn init(
            &mut self,
            _ctx: &ServiceContext<tauri::test::MockRuntime>,
        ) -> Result<(), ServiceError> {
            Ok(())
        }
        async fn run(
            &mut self,
            _ctx: &ServiceContext<tauri::test::MockRuntime>,
        ) -> Result<(), ServiceError> {
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
            Ok(())
        }
    }

    /// BlockingOkService: init ok, run blocks until the shutdown token fires,
    /// then returns Ok. Models a cooperative cancellation that returns Ok.
    struct BlockingOkService;
    #[async_trait]
    impl BackgroundService<tauri::test::MockRuntime> for BlockingOkService {
        async fn init(
            &mut self,
            _ctx: &ServiceContext<tauri::test::MockRuntime>,
        ) -> Result<(), ServiceError> {
            Ok(())
        }
        async fn run(
            &mut self,
            ctx: &ServiceContext<tauri::test::MockRuntime>,
        ) -> Result<(), ServiceError> {
            // Block until cancelled, then return Ok.
            let _ = ctx.shutdown.cancelled().await;
            Ok(())
        }
    }

    #[tokio::test]
    async fn core01_natural_completion_emits_task_completed_exactly_once() {
        let handle = setup_manager_with_factory(Box::new(|| Box::new(YieldingOkService)));
        let app = tauri::test::mock_app();
        let (captured, _guard) = capture_plugin_events(app.handle());

        send_start(&handle, app.handle().clone()).await.unwrap();
        wait_until_stopped(&handle, 2000).await;
        // Give the emit + listener a beat to land.
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let events = captured.lock().unwrap();
        // Expect exactly: Started, Stopped{taskCompleted}.
        assert!(
            events.iter().any(|e| e.contains("\"type\":\"started\"")),
            "expected a Started event, got: {events:?}"
        );
        let stopped: Vec<_> = events
            .iter()
            .filter(|e| e.contains("\"type\":\"stopped\""))
            .collect();
        assert_eq!(
            stopped.len(),
            1,
            "exactly one terminal Stopped event, got: {stopped:?}"
        );
        assert!(
            stopped[0].contains("\"reason\":\"taskCompleted\""),
            "natural Ok must emit taskCompleted, got: {}",
            stopped[0]
        );
    }

    #[tokio::test]
    async fn core01_user_stop_emits_explicit_reason_over_cooperative_ok() {
        // The service returns Ok after cancellation. The terminal event MUST
        // be Stopped{userStop}, not Stopped{taskCompleted} — the explicit
        // stop reason wins.
        let handle = setup_manager_with_factory(Box::new(|| Box::new(BlockingOkService)));
        let app = tauri::test::mock_app();
        let (captured, _guard) = capture_plugin_events(app.handle());

        send_start(&handle, app.handle().clone()).await.unwrap();
        wait_until_running(&handle).await;
        send_stop(&handle).await.unwrap();
        wait_until_stopped(&handle, 2000).await;
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let events = captured.lock().unwrap();
        let stopped: Vec<_> = events
            .iter()
            .filter(|e| e.contains("\"type\":\"stopped\""))
            .collect();
        assert_eq!(stopped.len(), 1, "exactly one Stopped: {stopped:?}");
        assert!(
            stopped[0].contains("\"reason\":\"userStop\""),
            "explicit user stop must win over cooperative Ok, got: {}",
            stopped[0]
        );
    }

    #[tokio::test]
    async fn core01_platform_timeout_emits_platform_timeout_reason() {
        let handle = setup_manager_with_factory(Box::new(|| Box::new(BlockingOkService)));
        let app = tauri::test::mock_app();
        let (captured, _guard) = capture_plugin_events(app.handle());

        send_start(&handle, app.handle().clone()).await.unwrap();
        wait_until_running(&handle).await;
        send_stop_with_reason(&handle, StopReason::PlatformTimeout)
            .await
            .unwrap();
        wait_until_stopped(&handle, 2000).await;
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let events = captured.lock().unwrap();
        let stopped: Vec<_> = events
            .iter()
            .filter(|e| e.contains("\"type\":\"stopped\""))
            .collect();
        assert_eq!(stopped.len(), 1);
        assert!(
            stopped[0].contains("\"reason\":\"platformTimeout\""),
            "got: {}",
            stopped[0]
        );
    }

    #[tokio::test]
    async fn core01_unprompted_error_emits_error_event() {
        // ImmediateErrorService returns Err from run() WITHOUT an explicit
        // stop. The terminal event MUST be Error (no explicit reason set).
        let handle = setup_manager_with_factory(Box::new(|| Box::new(ImmediateErrorService)));
        let app = tauri::test::mock_app();
        let (captured, _guard) = capture_plugin_events(app.handle());

        send_start(&handle, app.handle().clone()).await.unwrap();
        wait_until_stopped(&handle, 2000).await;
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let events = captured.lock().unwrap();
        assert!(
            events.iter().any(|e| e.contains("\"type\":\"error\"")),
            "unprompted Err must emit Error, got: {events:?}"
        );
        // And it must NOT also emit a Stopped event for the same generation.
        let stopped = events
            .iter()
            .filter(|e| e.contains("\"type\":\"stopped\""))
            .count();
        assert_eq!(stopped, 0, "Error path must not double-emit Stopped");
    }

    #[tokio::test]
    async fn core01_natural_completion_clears_desired_running() {
        // Natural Ok must clear persisted desired_running — the task is done.
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_factory_and_backend(
            Box::new(|| Box::new(YieldingOkService)),
            Some(backend.clone()),
        );
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        wait_until_stopped(&handle, 2000).await;
        // Give the post-completion save a beat to land.
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let saves = backend.saves.lock().unwrap();
        // The last save after natural completion must set desired_running=false.
        let last = saves.last().expect("expected at least one save");
        assert!(
            !last.desired_running,
            "natural completion must clear desired_running; last save = {last:?}"
        );
    }

    #[tokio::test]
    async fn core01_unprompted_error_preserves_desired_running() {
        // Unprompted Err must NOT clear desired_running — recovery may resume.
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_factory_and_backend(
            Box::new(|| Box::new(ImmediateErrorService)),
            Some(backend.clone()),
        );
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        wait_until_stopped(&handle, 2000).await;
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        // The last save is `desired_running=true` from `handle_start`'s
        // post-spawn save; no additional `false` save should land.
        let saves = backend.saves.lock().unwrap();
        let last = saves.last().expect("expected at least one save");
        assert!(
            last.desired_running,
            "unprompted error must preserve desired_running=true; last save = {last:?}"
        );
    }

    #[tokio::test]
    async fn core01_restart_after_user_stop_succeeds_with_correct_reason() {
        // Regression: a stop-then-start cycle must emit the NEW generation's
        // reason, not leak the previous generation's terminal_reason.
        let handle = setup_manager_with_factory(Box::new(|| Box::new(BlockingOkService)));
        let app = tauri::test::mock_app();
        let (captured, _guard) = capture_plugin_events(app.handle());

        send_start(&handle, app.handle().clone()).await.unwrap();
        wait_until_running(&handle).await;
        send_stop(&handle).await.unwrap();
        wait_until_stopped(&handle, 2000).await;

        // Second generation — natural completion.
        send_start(&handle, app.handle().clone()).await.unwrap();
        // Replace the service so the second run returns immediately... but we
        // cannot change factory. Use BlockingOkService and stop instead:
        wait_until_running(&handle).await;
        send_stop_with_reason(&handle, StopReason::PlatformExpiration)
            .await
            .unwrap();
        wait_until_stopped(&handle, 2000).await;
        // Poll for the second Stopped event to land instead of a fixed sleep
        // — under parallel test load the emit + listener dispatch can race.
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
        loop {
            let n = captured
                .lock()
                .unwrap()
                .iter()
                .filter(|e| e.contains("\"type\":\"stopped\""))
                .count();
            if n >= 2 || std::time::Instant::now() >= deadline {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }

        let events = captured.lock().unwrap();
        let stopped: Vec<_> = events
            .iter()
            .filter(|e| e.contains("\"type\":\"stopped\""))
            .collect();
        assert_eq!(
            stopped.len(),
            2,
            "expected one Stopped per generation, got: {stopped:?}"
        );
        assert!(
            stopped[0].contains("\"reason\":\"userStop\""),
            "first stop reason: {}",
            stopped[0]
        );
        assert!(
            stopped[1].contains("\"reason\":\"platformExpiration\""),
            "second stop reason must be the new generation's, got: {}",
            stopped[1]
        );
    }

    // ── CORE-02: native reconcile must release the token ───────────────────
    //
    // When the native authority reports stopped while the actor believes the
    // service is running, the reconcile path MUST take/cancel the Rust-side
    // token — not just flip `is_running`. Previously the token was left
    // `Some`, so the next Start returned `AlreadyRunning` and restart was
    // permanently blocked until process restart.

    #[tokio::test]
    async fn core02_reconcile_native_stopped_then_restart_succeeds() {
        let mock = MockNativeState::new();
        let handle =
            setup_manager_with_factory_and_backend(Box::new(|| Box::new(BlockingService)), None);
        let app = tauri::test::mock_app();

        send_set_mobile(&handle, mock.clone()).await;
        send_start(&handle, app.handle().clone()).await.unwrap();
        wait_until_running(&handle).await;

        // Native authority reports STOPPED while Rust believes running —
        // the split-brain trigger that fires `reconcile_running_with_native`.
        mock.set_native_state(native_state(false));

        // Reconcile converges: is_running now reports false.
        assert!(
            !send_is_running(&handle).await,
            "reconcile must converge is_running to false"
        );

        // CORE-02 headline: restart MUST NOT return AlreadyRunning. Before
        // the fix, the token was left Some after the reconcile, so this
        // returned AlreadyRunning permanently.
        let result = send_start(&handle, app.handle().clone()).await;
        assert!(
            result.is_ok(),
            "restart after native-stopped reconcile must succeed (CORE-02): {result:?}"
        );

        // Before checking is_running, flip native back to running — otherwise
        // the next `is_running` query would reconcile-again to false (native
        // authority really did report stopped; reconcile is correct, not a
        // bug). The point of CORE-02 is the TOKEN release, not the reconcile
        // behavior itself.
        mock.set_native_state(native_state(true));
        assert!(
            send_is_running(&handle).await,
            "service must be observable as running after restart + native agreement"
        );
    }

    //
    // A malformed persisted `last_start_config` previously hit `.ok()` and
    // was silently discarded. The fix surfaces a diagnostic log AND keeps
    // the system in a clean state (no half-replayed Start). The observable
    // contract tested here: malformed config does NOT cause a panic, does
    // NOT start the service, and a subsequent explicit Start still works.

    #[tokio::test]
    async fn core05_malformed_boot_replay_is_skipped_cleanly_and_restart_works() {
        let backend = MockDesiredStateBackend::new();
        // Plant a desired-state that says "user wanted service running" but
        // carries a MALFORMED last_start_config (not a valid StartConfig).
        backend
            .save(&crate::desired_state::DesiredState {
                desired_running: true,
                last_start_config: Some(serde_json::json!({"serviceLabel": 12345})),
                ..Default::default()
            })
            .unwrap();
        let app = tauri::test::mock_app();
        let handle = setup_manager_with_factory_backend_and_boot_app(
            Box::new(|| Box::new(BlockingService)),
            Some(backend.clone()),
            Some(app.handle().clone()),
            true,
        );

        // Give the loop a moment to attempt (and skip) the malformed replay.
        tokio::time::sleep(std::time::Duration::from_millis(120)).await;

        // CORE-05 contract: malformed replay must NOT have started the service.
        assert!(
            !send_is_running(&handle).await,
            "malformed boot replay must not start the service"
        );

        // And the system must remain restartable from an explicit Start.
        send_start(&handle, app.handle().clone()).await.unwrap();
        assert!(
            send_is_running(&handle).await,
            "explicit start after malformed-replay skip must succeed"
        );
    }

    // ── Cancel-listener actor-level integration tests ────────────────────────
    //
    // These tests exercise the full cmd_tx → manager_loop path that
    // run_cancel_listener (in lib.rs) uses to send StopWithReason commands.
    // They verify desired-state and keepalive behaviour with both
    // MockDesiredStateBackend and MockMobile wired into the actor.

    #[tokio::test]
    async fn cancel_listener_platform_timeout_preserves_desired_and_resubmits() {
        let mock = MockMobile::new();
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_factory_and_backend(
            Box::new(|| Box::new(BlockingService)),
            Some(backend.clone()),
        );
        let app = tauri::test::mock_app();

        send_set_mobile(&handle, mock.clone()).await;
        send_start(&handle, app.handle().clone()).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let saves_before = backend.saves.lock().unwrap().len();
        let mirror_before = mock.mirror_calls.lock().unwrap().len();

        // Simulate what run_cancel_listener sends on timeout
        send_stop_with_reason(&handle, StopReason::PlatformTimeout)
            .await
            .unwrap();

        assert!(!send_is_running(&handle).await, "service should be stopped");

        // M13: PlatformTimeout must NOT tear down keepalive — treat it like
        // PlatformExpiration (the OS already paused the background window).
        assert_eq!(
            mock.stop_called.load(Ordering::Acquire),
            0,
            "PlatformTimeout should NOT call stop_keepalive (M13)"
        );

        // Desired state should be preserved (no desired=false write).
        let saves = backend.saves.lock().unwrap();
        assert_eq!(
            saves.len(),
            saves_before,
            "PlatformTimeout should not save new desired state"
        );
        assert!(
            saves.last().unwrap().desired_running,
            "desired_running should remain true"
        );

        // M13 reconcile: desired stays true, so re-submit native scheduling
        // (mirror) so a future BGTask resumes delivery instead of silently dying.
        let mirror = mock.mirror_calls.lock().unwrap();
        assert_eq!(
            mirror.len(),
            mirror_before + 1,
            "PlatformTimeout should re-submit native scheduling exactly once"
        );
        assert!(
            mirror.last().unwrap().0,
            "reconcile must mirror desired_running=true (never false)"
        );
    }

    #[tokio::test]
    async fn cancel_listener_user_stop_clears_desired_and_stops_keepalive() {
        let mock = MockMobile::new();
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_factory_and_backend(
            Box::new(|| Box::new(BlockingService)),
            Some(backend.clone()),
        );
        let app = tauri::test::mock_app();

        send_set_mobile(&handle, mock.clone()).await;
        send_start(&handle, app.handle().clone()).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        // UserStop via plain Stop command (delegates to StopWithReason(UserStop))
        send_stop(&handle).await.unwrap();

        assert!(!send_is_running(&handle).await, "service should be stopped");

        // UserStop should call stop_keepalive
        assert_eq!(
            mock.stop_called.load(Ordering::Acquire),
            1,
            "UserStop should call stop_keepalive"
        );

        // Desired state should be cleared
        let last = backend
            .last_save()
            .expect("should have saved desired state");
        assert!(
            !last.desired_running,
            "UserStop should clear desired_running to false"
        );
    }

    // ── Step 10 (task 3f1f): NativeLifecycleEvent command and handler tests ──

    async fn send_native_event(
        handle: &ServiceManagerHandle<tauri::test::MockRuntime>,
        event: NativeLifecycleEvent,
    ) -> Result<(), ServiceError> {
        let (tx, rx) = oneshot::channel();
        handle
            .cmd_tx
            .send(ManagerCommand::NativeLifecycleEvent { event, reply: tx })
            .await
            .unwrap();
        rx.await.unwrap()
    }

    #[tokio::test]
    async fn native_lifecycle_notification_stop_clears_desired_state() {
        let mock = MockMobile::new();
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_factory_and_backend(
            Box::new(|| Box::new(BlockingService)),
            Some(backend.clone()),
        );
        let app = tauri::test::mock_app();

        send_set_mobile(&handle, mock.clone()).await;
        send_start(&handle, app.handle().clone()).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let saves_before = backend.saves.lock().unwrap().len();

        send_native_event(&handle, NativeLifecycleEvent::AndroidNotificationStop)
            .await
            .unwrap();

        assert!(!send_is_running(&handle).await, "service should be stopped");

        // NativeNotificationStop clears desired state
        let saves = backend.saves.lock().unwrap();
        assert_eq!(saves.len(), saves_before + 1);
        assert!(
            !saves.last().unwrap().desired_running,
            "AndroidNotificationStop should clear desired_running"
        );

        // stop_keepalive should have been called
        assert_eq!(
            mock.stop_called.load(Ordering::Acquire),
            1,
            "AndroidNotificationStop should call stop_keepalive"
        );
    }

    #[tokio::test]
    async fn native_lifecycle_timeout_preserves_desired_state() {
        let mock = MockMobile::new();
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_factory_and_backend(
            Box::new(|| Box::new(BlockingService)),
            Some(backend.clone()),
        );
        let app = tauri::test::mock_app();

        send_set_mobile(&handle, mock.clone()).await;
        send_start(&handle, app.handle().clone()).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let saves_before = backend.saves.lock().unwrap().len();

        send_native_event(
            &handle,
            NativeLifecycleEvent::AndroidTimeout {
                fgs_type: Some("dataSync".into()),
            },
        )
        .await
        .unwrap();

        assert!(!send_is_running(&handle).await, "service should be stopped");

        // PlatformTimeout preserves desired state
        let saves = backend.saves.lock().unwrap();
        assert_eq!(
            saves.len(),
            saves_before,
            "AndroidTimeout should not save new desired state"
        );
        assert!(
            saves.last().unwrap().desired_running,
            "desired_running should remain true"
        );

        // M13: AndroidTimeout maps to PlatformTimeout, which now preserves the
        // keepalive (the OS already timed out the FGS window).
        assert_eq!(
            mock.stop_called.load(Ordering::Acquire),
            0,
            "AndroidTimeout (PlatformTimeout) should NOT call stop_keepalive (M13)"
        );
    }

    #[tokio::test]
    async fn native_lifecycle_event_idempotent_when_already_stopped() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_factory_and_backend(
            Box::new(|| Box::new(BlockingService)),
            Some(backend.clone()),
        );
        let app = tauri::test::mock_app();

        send_start(&handle, app.handle().clone()).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        // Stop first
        send_stop(&handle).await.unwrap();
        assert!(!send_is_running(&handle).await);

        let saves_before = backend.saves.lock().unwrap().len();

        // Send native event while already stopped — should be a no-op (NotRunning)
        let result =
            send_native_event(&handle, NativeLifecycleEvent::AndroidNotificationStop).await;
        assert!(
            matches!(result, Err(ServiceError::NotRunning)),
            "native event while stopped should return NotRunning: {result:?}"
        );

        // No additional desired-state saves
        {
            let saves = backend.saves.lock().unwrap();
            assert_eq!(
                saves.len(),
                saves_before,
                "no additional saves when already stopped"
            );
        }

        // Same for timeout variant
        let result = send_native_event(
            &handle,
            NativeLifecycleEvent::AndroidTimeout { fgs_type: None },
        )
        .await;
        assert!(
            matches!(result, Err(ServiceError::NotRunning)),
            "timeout while stopped should return NotRunning: {result:?}"
        );
    }

    // ── Step 13: GetLifecycleStatus command tests ────────────────────────────

    /// Helper: send GetLifecycleStatus and return the result.
    async fn send_get_lifecycle_status(
        handle: &ServiceManagerHandle<tauri::test::MockRuntime>,
    ) -> LifecycleStatus {
        let (reply, rx) = oneshot::channel();
        handle
            .cmd_tx
            .send(ManagerCommand::GetLifecycleStatus {
                desktop_mode: None,
                reply,
            })
            .await
            .expect("send GetLifecycleStatus");
        rx.await.expect("receive LifecycleStatus")
    }

    #[tokio::test]
    async fn get_lifecycle_status_returns_idle_initially() {
        let handle = setup_manager();
        let status = send_get_lifecycle_status(&handle).await;
        assert!(
            matches!(status.state, LifecycleState::Idle),
            "expected Idle, got {:?}",
            status.state
        );
        assert!(!status.desired_running);
        assert!(!status.recovery_enabled);
        assert!(!status.recovery_pending);
        assert!(status.last_error.is_none());
        assert!(status.last_start_config.is_none());
    }

    #[tokio::test]
    async fn get_lifecycle_status_returns_running_after_start() {
        let handle =
            setup_manager_with_factory_and_backend(Box::new(|| Box::new(BlockingService)), None);
        let app = tauri::test::mock_app();
        send_start(&handle, app.handle().clone()).await.unwrap();
        // Poll for Running instead of a fixed sleep, which races the
        // Initializing→Running transition under parallel-suite load
        // (mem-1781352466-ae2a).
        wait_until_running(&handle).await;

        let status = send_get_lifecycle_status(&handle).await;
        assert!(
            matches!(status.state, LifecycleState::Running),
            "expected Running, got {:?}",
            status.state
        );
    }

    #[tokio::test]
    async fn get_lifecycle_status_reflects_desired_state() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_factory_and_backend(
            Box::new(|| Box::new(BlockingService)),
            Some(backend.clone()),
        );

        // Enable auto-restart (sets desired_running=true)
        send_enable_auto_restart(&handle, None).await.unwrap();

        let status = send_get_lifecycle_status(&handle).await;
        assert!(
            status.desired_running,
            "expected desired_running=true after enable_auto_restart"
        );
        assert!(
            status.recovery_enabled,
            "expected recovery_enabled=true when desired_running=true"
        );
    }

    #[tokio::test]
    async fn get_lifecycle_status_clears_after_disable_recovery() {
        let backend = MockDesiredStateBackend::new();
        let handle = setup_manager_with_factory_and_backend(
            Box::new(|| Box::new(BlockingService)),
            Some(backend.clone()),
        );

        // Enable then disable
        send_enable_auto_restart(&handle, None).await.unwrap();
        send_disable_auto_restart(&handle).await.unwrap();

        let status = send_get_lifecycle_status(&handle).await;
        assert!(
            !status.desired_running,
            "expected desired_running=false after disable"
        );
        assert!(
            !status.recovery_enabled,
            "expected recovery_enabled=false after disable"
        );
    }

    #[tokio::test]
    async fn get_lifecycle_status_includes_platform_and_capabilities() {
        let handle = setup_manager();
        let status = send_get_lifecycle_status(&handle).await;

        // On the test machine (Linux desktop), platform should be Linux
        #[cfg(target_os = "linux")]
        assert!(
            matches!(status.platform, crate::models::Platform::Linux),
            "expected Linux platform, got {:?}",
            status.platform
        );
        // Capabilities should be populated
        assert!(
            !status.capabilities.limitations.is_empty()
                || !status.capabilities.required_setup.is_empty(),
            "capabilities should have some content"
        );
    }

    #[tokio::test]
    async fn get_lifecycle_status_returns_stopped_after_stop() {
        let handle =
            setup_manager_with_factory_and_backend(Box::new(|| Box::new(BlockingService)), None);
        let app = tauri::test::mock_app();
        send_start(&handle, app.handle().clone()).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        send_stop(&handle).await.unwrap();

        let status = send_get_lifecycle_status(&handle).await;
        assert!(
            matches!(status.state, LifecycleState::Stopped),
            "expected Stopped, got {:?}",
            status.state
        );
    }

    // ── Step 3: State merge / degraded detection tests ────────────────────

    /// Mock mobile that returns a configurable [`AndroidServiceState`].
    ///
    /// `start_keepalive` / `stop_keepalive` are no-ops (always succeed).
    /// `get_android_service_state` returns the value set via
    /// [`Self::set_native_state`], or `Ok(None)` if unset.
    struct MockNativeState {
        native_state: std::sync::Mutex<Option<crate::models::AndroidServiceState>>,
        android_calls: AtomicUsize,
    }

    impl MockNativeState {
        fn new() -> Arc<Self> {
            Arc::new(Self {
                native_state: std::sync::Mutex::new(None),
                android_calls: AtomicUsize::new(0),
            })
        }

        fn set_native_state(&self, state: crate::models::AndroidServiceState) {
            *self.native_state.lock().unwrap() = Some(state);
        }

        fn android_call_count(&self) -> usize {
            self.android_calls.load(Ordering::Acquire)
        }
    }

    impl MobileKeepalive for MockNativeState {
        #[allow(clippy::too_many_arguments)]
        fn start_keepalive(
            &self,
            _label: &str,
            _foreground_service_type: &str,
            _ios_safety_timeout_secs: Option<f64>,
            _ios_processing_safety_timeout_secs: Option<f64>,
            _ios_earliest_refresh_begin_minutes: Option<f64>,
            _ios_earliest_processing_begin_minutes: Option<f64>,
            _ios_requires_external_power: Option<bool>,
            _ios_requires_network_connectivity: Option<bool>,
            _ios_processing_ceiling_multiplier: Option<f64>,
        ) -> Result<(), ServiceError> {
            Ok(())
        }

        fn stop_keepalive(&self) -> Result<(), ServiceError> {
            Ok(())
        }

        fn get_android_service_state(
            &self,
        ) -> Result<Option<crate::models::AndroidServiceState>, ServiceError> {
            self.android_calls.fetch_add(1, Ordering::AcqRel);
            Ok(self.native_state.lock().unwrap().clone())
        }
    }

    /// Helper: create a default `AndroidServiceState` with the given
    /// `native_running` flag. All other fields get sensible defaults.
    fn native_state(running: bool) -> crate::models::AndroidServiceState {
        crate::models::AndroidServiceState {
            native_running: running,
            native_foreground: running,
            desired_running: running,
            durable_state: if running { "running" } else { "stopped" }.into(),
            service_label: None,
            foreground_service_type: None,
            notification_id: None,
            notification_channel_id: None,
            recovery_pending: false,
            recovery_reason: None,
            last_platform_error: None,
            data_dir: "/data".into(),
        }
    }

    /// AC1: Adopt native when running, Rust idle.
    #[tokio::test]
    async fn merge_adopt_native_when_running() {
        let mock = MockNativeState::new();
        let handle =
            setup_manager_with_factory_and_backend(Box::new(|| Box::new(BlockingService)), None);
        let app = tauri::test::mock_app();

        send_set_mobile(&handle, mock.clone()).await;
        // Start → Rust running, app handle stored.
        send_start(&handle, app.handle().clone()).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        // Stop → Rust becomes stopped.
        send_stop(&handle).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        // Native reports running (OS restarted service).
        mock.set_native_state(native_state(true));

        let status = send_get_lifecycle_status(&handle).await;
        assert_eq!(status.adopted, Some(true), "should adopt native");
        assert_eq!(status.degraded, Some(false), "adopt is not degraded");
        assert_eq!(status.native_running, Some(true));
        assert!(
            matches!(status.state, LifecycleState::Running),
            "expected Running after adopt, got {:?}",
            status.state,
        );
    }

    /// AC2: Auto-heal when native stopped but Rust running.
    #[tokio::test]
    async fn merge_autoheal_when_native_stopped() {
        let mock = MockNativeState::new();
        let handle =
            setup_manager_with_factory_and_backend(Box::new(|| Box::new(BlockingService)), None);
        let app = tauri::test::mock_app();

        send_set_mobile(&handle, mock.clone()).await;
        send_start(&handle, app.handle().clone()).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        // Native reports stopped while Rust is running.
        mock.set_native_state(native_state(false));

        let status = send_get_lifecycle_status(&handle).await;
        assert_eq!(
            status.degraded,
            Some(true),
            "transient degraded on mismatch"
        );
        assert_eq!(
            status.degraded_reason,
            Some("native_stopped_rust_running".into()),
            "should explain the mismatch"
        );
        // Auto-healed: Rust is now idle/stopped.
        assert!(
            matches!(status.state, LifecycleState::Stopped | LifecycleState::Idle),
            "expected Stopped or Idle after auto-heal, got {:?}",
            status.state,
        );
    }

    /// R-W1.4 / D-SPLITBRAIN: `is_running()` is native-authoritative.
    ///
    /// When the actor believes the service is running but the native authority
    /// (`LifecycleService.isRunning`) reports stopped — e.g. the OS killed or
    /// timed-out the FGS while the UI was closed — a direct `is_running()`
    /// query MUST reconcile to native truth: converge to `false` (closing the
    /// split-brain "stuck running" window the harness Scenario 8 tests) and
    /// converge the lifecycle state to `Stopped`. The divergence is logged on
    /// the reconcile path (NFR-1/NFR-5, no silent swallow).
    #[tokio::test]
    async fn actor_converges_to_native_stopped() {
        let mock = MockNativeState::new();
        let handle =
            setup_manager_with_factory_and_backend(Box::new(|| Box::new(BlockingService)), None);
        let app = tauri::test::mock_app();

        send_set_mobile(&handle, mock.clone()).await;
        send_start(&handle, app.handle().clone()).await.unwrap();
        // Poll for Running rather than a fixed sleep (mem-1781352466-ae2a).
        wait_until_running(&handle).await;

        // Precondition: with no native report yet, the actor believes it runs.
        assert!(
            send_is_running(&handle).await,
            "precondition: actor should believe it is running after start",
        );

        // Native authority now reports STOPPED (OS killed/timed-out the FGS
        // while the UI was closed) — the split-brain trigger.
        mock.set_native_state(native_state(false));

        // is_running() reconciles to native truth: converges to false, so a
        // caller can never observe a stale "running" after a native stop.
        assert!(
            !send_is_running(&handle).await,
            "is_running() must converge to native-stopped (no stuck 'running')",
        );

        // Full convergence: the lifecycle state also reflects native authority.
        assert_eq!(
            send_get_state(&handle).await.state,
            ServiceLifecycle::Stopped,
            "lifecycle state must converge to Stopped on native-authority reconcile",
        );
    }

    /// AC3: Normal when both agree running.
    #[tokio::test]
    async fn merge_normal_both_running() {
        let mock = MockNativeState::new();
        let handle =
            setup_manager_with_factory_and_backend(Box::new(|| Box::new(BlockingService)), None);
        let app = tauri::test::mock_app();

        send_set_mobile(&handle, mock.clone()).await;
        send_start(&handle, app.handle().clone()).await.unwrap();
        // Poll for Running instead of a fixed sleep, which races the
        // Initializing→Running transition under parallel-suite load
        // (mem-1781352466-ae2a).
        wait_until_running(&handle).await;

        // Native agrees: running.
        mock.set_native_state(native_state(true));

        let status = send_get_lifecycle_status(&handle).await;
        assert_eq!(status.degraded, Some(false));
        assert_eq!(status.adopted, Some(false));
        assert!(
            matches!(status.state, LifecycleState::Running),
            "expected Running, got {:?}",
            status.state,
        );
    }

    /// AC4: Normal when both agree idle.
    #[tokio::test]
    async fn merge_normal_both_idle() {
        let mock = MockNativeState::new();
        let handle = setup_manager();

        send_set_mobile(&handle, mock.clone()).await;

        // Neither started — Rust is idle, native reports stopped.
        mock.set_native_state(native_state(false));

        let status = send_get_lifecycle_status(&handle).await;
        assert_eq!(status.degraded, Some(false));
        assert!(
            matches!(status.state, LifecycleState::Idle),
            "expected Idle, got {:?}",
            status.state,
        );
    }

    /// AC5: Timeout detection — native timeout DurableState + Rust running.
    #[tokio::test]
    async fn merge_timeout_detection() {
        let mock = MockNativeState::new();
        let handle =
            setup_manager_with_factory_and_backend(Box::new(|| Box::new(BlockingService)), None);
        let app = tauri::test::mock_app();

        send_set_mobile(&handle, mock.clone()).await;
        send_start(&handle, app.handle().clone()).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        // Native reports running but DurableState says "timeout".
        let mut ns = native_state(true);
        ns.durable_state = "timeout".into();
        mock.set_native_state(ns);

        let status = send_get_lifecycle_status(&handle).await;
        assert_eq!(status.degraded, Some(true));
        assert_eq!(
            status.degraded_reason,
            Some("native_timeout".into()),
            "should report timeout degradation"
        );
    }

    /// AC6: Recovery pending from native surfaces in status.
    #[tokio::test]
    async fn merge_recovery_pending_surfaces() {
        let mock = MockNativeState::new();
        let handle = setup_manager();

        send_set_mobile(&handle, mock.clone()).await;

        // Native reports recovery pending.
        let mut ns = native_state(false);
        ns.recovery_pending = true;
        ns.recovery_reason = Some("core_start_failed".into());
        mock.set_native_state(ns);

        let status = send_get_lifecycle_status(&handle).await;
        assert!(
            status.recovery_pending,
            "recovery_pending should be true from native state"
        );
    }

    /// AC7: Degraded event emitted on state mismatch.
    #[tokio::test]
    async fn merge_degraded_event_emitted() {
        let mock = MockNativeState::new();
        let handle =
            setup_manager_with_factory_and_backend(Box::new(|| Box::new(BlockingService)), None);
        let app = tauri::test::mock_app();

        let event_received = Arc::new(AtomicBool::new(false));
        let event_received_clone = event_received.clone();
        let _listener = app
            .handle()
            .listen("background-service:state-degraded", move |_event| {
                event_received_clone.store(true, Ordering::Release);
            });

        send_set_mobile(&handle, mock.clone()).await;
        send_start(&handle, app.handle().clone()).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        // Trigger mismatch: native stopped, Rust running.
        mock.set_native_state(native_state(false));

        let _status = send_get_lifecycle_status(&handle).await;
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        assert!(
            event_received.load(Ordering::Acquire),
            "state-degraded event should be emitted on mismatch"
        );
    }

    /// AC8: Degraded clears when states converge on next query.
    #[tokio::test]
    async fn merge_degraded_clears_on_convergence() {
        let mock = MockNativeState::new();
        let handle =
            setup_manager_with_factory_and_backend(Box::new(|| Box::new(BlockingService)), None);
        let app = tauri::test::mock_app();

        send_set_mobile(&handle, mock.clone()).await;
        send_start(&handle, app.handle().clone()).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        // First query: mismatch → degraded.
        mock.set_native_state(native_state(false));
        let status1 = send_get_lifecycle_status(&handle).await;
        assert_eq!(
            status1.degraded,
            Some(true),
            "first query should be degraded"
        );

        // Auto-heal set Rust to stopped. Now both agree stopped.
        // Second query: convergence → degraded clears.
        let status2 = send_get_lifecycle_status(&handle).await;
        assert_eq!(
            status2.degraded,
            Some(false),
            "degraded should clear on convergence"
        );
        assert_eq!(status2.degraded_reason, None);
    }

    // ── Step 10: iOS native reconciliation + Android-gating (H6, L4) ───────

    /// Mock mobile that returns a configurable iOS [`IosNativeState`] via
    /// `query_native_state` and COUNTS `get_android_service_state` calls, so a
    /// test can assert the iOS status / reconcile paths never round-trip to the
    /// Android bridge (L4).
    struct MockIosNativeState {
        ios_state: std::sync::Mutex<Option<crate::models::IosNativeState>>,
        android_calls: AtomicUsize,
    }

    impl MockIosNativeState {
        fn new() -> Arc<Self> {
            Arc::new(Self {
                ios_state: std::sync::Mutex::new(None),
                android_calls: AtomicUsize::new(0),
            })
        }

        fn set_ios_state(&self, state: crate::models::IosNativeState) {
            *self.ios_state.lock().unwrap() = Some(state);
        }

        fn android_call_count(&self) -> usize {
            self.android_calls.load(Ordering::Acquire)
        }
    }

    impl MobileKeepalive for MockIosNativeState {
        #[allow(clippy::too_many_arguments)]
        fn start_keepalive(
            &self,
            _label: &str,
            _foreground_service_type: &str,
            _ios_safety_timeout_secs: Option<f64>,
            _ios_processing_safety_timeout_secs: Option<f64>,
            _ios_earliest_refresh_begin_minutes: Option<f64>,
            _ios_earliest_processing_begin_minutes: Option<f64>,
            _ios_requires_external_power: Option<bool>,
            _ios_requires_network_connectivity: Option<bool>,
            _ios_processing_ceiling_multiplier: Option<f64>,
        ) -> Result<(), ServiceError> {
            Ok(())
        }

        fn stop_keepalive(&self) -> Result<(), ServiceError> {
            Ok(())
        }

        fn get_android_service_state(
            &self,
        ) -> Result<Option<crate::models::AndroidServiceState>, ServiceError> {
            // L4 tripwire: the iOS status/reconcile path must NEVER reach this.
            self.android_calls.fetch_add(1, Ordering::AcqRel);
            Ok(None)
        }

        fn get_ios_native_state(
            &self,
        ) -> Result<Option<crate::models::IosNativeState>, ServiceError> {
            Ok(self.ios_state.lock().unwrap().clone())
        }

        fn query_native_state(&self) -> Result<Option<NativeAuthority>, ServiceError> {
            // Mirror the real iOS `MobileLifecycle`: tag the snapshot `Ios` and
            // never touch the Android bridge.
            Ok(self.get_ios_native_state()?.map(NativeAuthority::Ios))
        }
    }

    /// Helper: a default iOS native snapshot with the given desired-running
    /// flag, in-budget, no active task / pending / error.
    fn ios_state(desired_running: bool) -> crate::models::IosNativeState {
        crate::models::IosNativeState {
            desired_running,
            refresh_scheduled: false,
            processing_scheduled: false,
            active_task_kind: None,
            pending_task: None,
            last_completed_at: None,
            last_completion_reason: None,
            last_refresh_error: None,
            last_processing_error: None,
            in_budget: true,
        }
    }

    /// H6 / AC1: a native scheduling failure surfaces as degraded + the real
    /// error string — not silently swallowed and not stale actor memory.
    #[tokio::test]
    async fn ios_status_reflects_scheduling_failure() {
        let mock = MockIosNativeState::new();
        let handle =
            setup_manager_with_factory_and_backend(Box::new(|| Box::new(BlockingService)), None);
        send_set_mobile(&handle, mock.clone()).await;

        let mut s = ios_state(true);
        s.last_refresh_error = Some("BGTaskSchedulerErrorDomain code 1".into());
        mock.set_ios_state(s);

        let status = send_get_lifecycle_status(&handle).await;
        assert_eq!(
            status.degraded,
            Some(true),
            "iOS scheduling failure must report degraded",
        );
        assert_eq!(
            status.degraded_reason,
            Some("ios_scheduling_error".into()),
            "degraded reason must name the iOS scheduling error",
        );
        assert_eq!(
            status.last_platform_error,
            Some("BGTaskSchedulerErrorDomain code 1".into()),
            "the real native error string must surface",
        );
        assert_eq!(mock.android_call_count(), 0, "L4: no Android round-trip");
    }

    /// H6 / AC1: with the service desired but no BGTask currently executing,
    /// the status reflects the native "waiting for next BGTask" phase and an
    /// honest `native_running=false`, instead of the actor's stale "running".
    #[tokio::test]
    async fn ios_status_reflects_waiting_for_next_bgtask() {
        let mock = MockIosNativeState::new();
        let handle =
            setup_manager_with_factory_and_backend(Box::new(|| Box::new(BlockingService)), None);
        let app = tauri::test::mock_app();
        send_set_mobile(&handle, mock.clone()).await;
        // Actor believes it is running (BlockingService keeps run() alive)…
        send_start(&handle, app.handle().clone()).await.unwrap();
        wait_until_running(&handle).await;

        // …but the native snapshot shows no active BGTask (window expired).
        mock.set_ios_state(ios_state(true));

        let status = send_get_lifecycle_status(&handle).await;
        assert_eq!(
            status.last_platform_state,
            Some("waitingForBgTask".into()),
            "status must reflect the native waiting phase, not stale actor memory",
        );
        assert_eq!(
            status.native_running,
            Some(false),
            "no BGTask is executing natively",
        );
        assert_eq!(status.degraded, Some(false));
        assert_eq!(mock.android_call_count(), 0, "L4: no Android round-trip");
    }

    /// H6 / AC1: a desired-but-out-of-budget snapshot reports degraded.
    #[tokio::test]
    async fn ios_status_out_of_budget_is_degraded() {
        let mock = MockIosNativeState::new();
        let handle =
            setup_manager_with_factory_and_backend(Box::new(|| Box::new(BlockingService)), None);
        send_set_mobile(&handle, mock.clone()).await;

        let mut s = ios_state(true);
        s.in_budget = false;
        mock.set_ios_state(s);

        let status = send_get_lifecycle_status(&handle).await;
        assert_eq!(status.degraded, Some(true));
        assert_eq!(status.degraded_reason, Some("ios_out_of_budget".into()));
    }

    /// L4 / AC2: an iOS status poll must NOT invoke `getAndroidServiceState`.
    #[tokio::test]
    async fn ios_status_poll_does_not_call_get_android_service_state() {
        let mock = MockIosNativeState::new();
        let handle =
            setup_manager_with_factory_and_backend(Box::new(|| Box::new(BlockingService)), None);
        send_set_mobile(&handle, mock.clone()).await;
        mock.set_ios_state(ios_state(true));

        let status = send_get_lifecycle_status(&handle).await;
        // Proof the iOS native path actually ran:
        assert_eq!(status.last_platform_state, Some("waitingForBgTask".into()));
        // …without ever touching the Android bridge.
        assert_eq!(
            mock.android_call_count(),
            0,
            "iOS status poll must not call getAndroidServiceState (L4)",
        );
    }

    /// L4 / AC2: the iOS reconcile path (is_running) must not flip the actor's
    /// belief (iOS has no authoritative native running bit) and must not call
    /// `getAndroidServiceState`.
    #[tokio::test]
    async fn ios_reconcile_keeps_actor_belief_without_android_call() {
        let mock = MockIosNativeState::new();
        let handle =
            setup_manager_with_factory_and_backend(Box::new(|| Box::new(BlockingService)), None);
        let app = tauri::test::mock_app();
        send_set_mobile(&handle, mock.clone()).await;
        send_start(&handle, app.handle().clone()).await.unwrap();
        wait_until_running(&handle).await;

        mock.set_ios_state(ios_state(true));

        assert!(
            send_is_running(&handle).await,
            "iOS reconcile must keep the actor's running belief",
        );
        assert_eq!(
            mock.android_call_count(),
            0,
            "iOS reconcile must not call getAndroidServiceState (L4)",
        );
    }

    /// AC2 (Android path unchanged): the default `query_native_state` route
    /// still queries `getAndroidServiceState` for the Android/desktop bridge.
    #[tokio::test]
    async fn android_status_poll_still_queries_android_state() {
        let mock = MockNativeState::new();
        let handle =
            setup_manager_with_factory_and_backend(Box::new(|| Box::new(BlockingService)), None);
        send_set_mobile(&handle, mock.clone()).await;
        mock.set_native_state(native_state(true));

        let _ = send_get_lifecycle_status(&handle).await;
        assert!(
            mock.android_call_count() >= 1,
            "Android path must still query getAndroidServiceState",
        );
    }

    // ── Step 11: Core Adoption Tests ──────────────────────────────────────

    /// AC1: Native headless Core start → UI attach → event reception.
    ///
    /// Simulates Android OS sticky-restarting the service. The native layer
    /// starts Core via JNI without Rust knowing. When the UI (re)attaches and
    /// calls `get_lifecycle_status`, the merge logic adopts the native state.
    /// The late subscriber can then receive events from the adopted Core.
    #[tokio::test]
    async fn adoption_native_start_ui_attach_events() {
        let mock = MockNativeState::new();
        let handle =
            setup_manager_with_factory_and_backend(Box::new(|| Box::new(BlockingService)), None);
        let app = tauri::test::mock_app();

        // Register event listener BEFORE adoption (late subscriber).
        let event_received = Arc::new(AtomicBool::new(false));
        let event_received_clone = event_received.clone();
        let _listener = app
            .handle()
            .listen("background-service:state-degraded", move |_event| {
                event_received_clone.store(true, Ordering::Release);
            });

        send_set_mobile(&handle, mock.clone()).await;

        // Start service normally → sets app handle in state.
        send_start(&handle, app.handle().clone()).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        // Stop service → Rust becomes stopped (simulating app killed by OS).
        send_stop(&handle).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        // Native reports running (OS sticky restart).
        mock.set_native_state(native_state(true));

        // UI attaches → calls get_lifecycle_status.
        let status = send_get_lifecycle_status(&handle).await;

        // Adoption: native running, Rust idle → adopt.
        assert_eq!(status.adopted, Some(true), "should adopt native state");
        assert_eq!(status.degraded, Some(false), "adoption is not degraded");
        assert!(
            matches!(status.state, LifecycleState::Running),
            "expected Running after adoption, got {:?}",
            status.state,
        );

        // Verify the event system still works after adoption.
        // Trigger a state mismatch to emit the degraded event.
        mock.set_native_state(native_state(false));
        let _ = send_get_lifecycle_status(&handle).await;
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        assert!(
            event_received.load(Ordering::Acquire),
            "late subscriber should receive events after adoption"
        );
    }

    /// AC2: Data directory from native state surfaces in LifecycleStatus.
    ///
    /// When native reports its data directory, it should be visible in the
    /// merged status so the UI can validate path consistency.
    #[tokio::test]
    async fn adoption_data_dir_surfaces_in_status() {
        let mock = MockNativeState::new();
        let handle = setup_manager();

        send_set_mobile(&handle, mock.clone()).await;

        let mut ns = native_state(false);
        ns.data_dir = "/data/app/com.example".into();
        mock.set_native_state(ns);

        let status = send_get_lifecycle_status(&handle).await;
        assert_eq!(
            status.data_dir,
            Some("/data/app/com.example".to_string()),
            "data_dir from native should surface in status"
        );
    }

    /// AC3: setup_idle is reported as healthy, not failed.
    ///
    /// When Core reports setup_idle (account setup needed), the service
    /// is running in the background but waiting for user action.
    /// This is a valid healthy state, not an error.
    #[tokio::test]
    async fn adoption_setup_idle_is_healthy() {
        let mock = MockNativeState::new();
        let handle = setup_manager();

        send_set_mobile(&handle, mock.clone()).await;

        // Native reports setup_idle: service running, Core in setup mode.
        let mut ns = native_state(true);
        ns.durable_state = "setup_idle".into();
        mock.set_native_state(ns);

        let status = send_get_lifecycle_status(&handle).await;

        // Must NOT be Error or degraded.
        assert!(
            !matches!(status.state, LifecycleState::Error),
            "setup_idle should not be reported as Error"
        );
        assert_ne!(
            status.degraded,
            Some(true),
            "setup_idle should not be degraded"
        );

        // Must be reported as SetupIdle (not generic Running/Idle).
        assert!(
            matches!(status.state, LifecycleState::SetupIdle),
            "expected SetupIdle, got {:?}",
            status.state,
        );
    }

    /// AC4: locked_idle is reported as healthy, not failed.
    ///
    /// When Core reports locked_idle (account locked, needs unlock), the
    /// service is running in the background but waiting for user action.
    /// This is a valid healthy state, not an error.
    #[tokio::test]
    async fn adoption_locked_idle_is_healthy() {
        let mock = MockNativeState::new();
        let handle = setup_manager();

        send_set_mobile(&handle, mock.clone()).await;

        // Native reports locked_idle: service running, Core in locked mode.
        let mut ns = native_state(true);
        ns.durable_state = "locked_idle".into();
        mock.set_native_state(ns);

        let status = send_get_lifecycle_status(&handle).await;

        // Must NOT be Error or degraded.
        assert!(
            !matches!(status.state, LifecycleState::Error),
            "locked_idle should not be reported as Error"
        );
        assert_ne!(
            status.degraded,
            Some(true),
            "locked_idle should not be degraded"
        );

        // Must be reported as LockedIdle (not generic Running/Idle).
        assert!(
            matches!(status.state, LifecycleState::LockedIdle),
            "expected LockedIdle, got {:?}",
            status.state,
        );
    }

    // ── Step 12: Stale DurableState Safety Checks ──────────────────────────

    /// AC3: Stale timeout DurableState surfaces in status even when Rust is not running.
    ///
    /// Simulates: Android FGS timeout occurred (DurableState="timeout") but the
    /// app relaunched. Rust actor is idle. `get_lifecycle_status` must still
    /// surface the stale timeout so the UI can handle recovery.
    #[tokio::test]
    async fn stale_timeout_surfaces_in_status_when_not_running() {
        let mock = MockNativeState::new();
        let handle = setup_manager();

        send_set_mobile(&handle, mock.clone()).await;

        // Rust is idle (not started). Native reports NOT running, but DurableState
        // has "timeout" from a previous session.
        let mut ns = native_state(false);
        ns.durable_state = "timeout".into();
        ns.last_platform_error = Some("FGS timeout (type: remoteMessaging)".into());
        mock.set_native_state(ns);

        let status = send_get_lifecycle_status(&handle).await;
        assert!(
            status.degraded == Some(true) || status.degraded_reason.is_some(),
            "stale timeout DurableState should be reflected in status even when Rust is not running — \
             got degraded={:?}, degraded_reason={:?}",
            status.degraded,
            status.degraded_reason,
        );
    }

    // ── BGS-31: graceful SIGTERM stop (doc-08 Step 9) ──────────────────
    //
    // The SIGTERM handler's graceful path is factored into
    // `graceful_sigterm_shutdown` (desktop mod) so this test can drive the
    // SAME code the real signal arm runs — a real SIGTERM is not deliverable
    // in a unit test. Requires `--features desktop-service` (the desktop mod)
    // and is unix-only to match SIGTERM semantics.

    /// A service that stays running until its shutdown token is cancelled AND
    /// records `shutdown_gracefully` (the BGS-31 bounded-drain hook). The hook
    /// is stateless w.r.t. the instance — it sets a shared flag — so a fresh
    /// factory instance setting it is equivalent to the running instance.
    #[cfg(all(unix, feature = "desktop-service"))]
    struct GracefulShutdownService {
        drained: Arc<AtomicBool>,
    }

    #[cfg(all(unix, feature = "desktop-service"))]
    #[async_trait]
    impl BackgroundService<tauri::test::MockRuntime> for GracefulShutdownService {
        async fn init(
            &mut self,
            _ctx: &ServiceContext<tauri::test::MockRuntime>,
        ) -> Result<(), ServiceError> {
            Ok(())
        }

        async fn run(
            &mut self,
            ctx: &ServiceContext<tauri::test::MockRuntime>,
        ) -> Result<(), ServiceError> {
            // Block until stopped so the running token stays Some — else Stop
            // returns NotRunning and SKIPS all bookkeeping (AC1 precondition).
            ctx.shutdown.cancelled().await;
            Ok(())
        }

        async fn shutdown_gracefully(
            &mut self,
            _ctx: &ServiceContext<tauri::test::MockRuntime>,
        ) -> Result<(), ServiceError> {
            self.drained.store(true, Ordering::SeqCst);
            Ok(())
        }
    }

    /// BGS-31 (doc-08 Step 9): SIGTERM/SIGINT triggers `ManagerCommand::Stop`
    /// that REACHES manager_loop (bookkeeping) AND `ManagerCommand::ShutdownGracefully`
    /// that drives the bounded-drain hook — NOT the abrupt Drop abort.
    #[cfg(all(unix, feature = "desktop-service"))]
    #[tokio::test]
    async fn bgs31_sigterm_graceful_stop() {
        use crate::desktop::headless::graceful_sigterm_shutdown;

        let drained = Arc::new(AtomicBool::new(false));
        let drained_for_factory = drained.clone();
        let handle = setup_manager_with_factory(Box::new(move || {
            Box::new(GracefulShutdownService {
                drained: drained_for_factory.clone(),
            })
        }));

        // AC1 precondition: arrange a RUNNING token first. Without a running
        // service, handle_stop_with_reason returns NotRunning and SKIPS all
        // bookkeeping.
        let app = tauri::test::mock_app();
        send_start(&handle, app.handle().clone())
            .await
            .expect("Start should succeed");
        wait_until_running(&handle).await;
        assert!(
            handle.is_running().await,
            "precondition: service should be running before SIGTERM"
        );

        // Drive the SIGTERM graceful path — the SAME code the signal arm runs.
        graceful_sigterm_shutdown(&handle.cmd_tx).await;

        // AC1 (i): the bookkeeping Stop REACHED manager_loop — is_running
        // flipped to false (handle_stop clears it; the token was Some, so the
        // bookkeeping ran). NOT a placebo: a send that never reached the loop
        // would leave is_running true.
        assert!(
            !handle.is_running().await,
            "Stop did not reach manager_loop (is_running still true)"
        );

        // AC1 (ii): shutdown_gracefully RAN (the bounded-drain hook fired via
        // the fresh factory service) — NOT the abrupt process-exit Drop abort.
        assert!(
            drained.load(Ordering::SeqCst),
            "shutdown_gracefully hook did not run (bounded drain not driven)"
        );
    }
}