rustploy 0.1.61

Rustploy PaaS daemon — lightweight self-hosted deployment platform
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
//! Testes da web UI num Chrome sem cabeça (exigem `google-chrome` instalado): login, telas, janelas e IaC.
//!
//! Fase 0 do plano de convergência de templates (`docs/plano-convergencia-
//! templates-gui-webui.md`): equivalente web de
//! `crates/rustploy-gui/tests/templates_render.rs` — em vez de reimplementar
//! um servidor de estáticos, serve os MESMOS bytes que o daemon serve em
//! produção (`serve()` acima, já gzipados/minificados pelo `build.rs`) e
//! dirige um Chrome headless de verdade contra eles. Não passa por login/SSE
//! — como o teste iced, semeia o estado direto (aqui, `Alpine.store('app')`
//! em vez de `GlacierUI::define_data`) e varre as telas.

use super::serve;
use bytes::Bytes;
use chromiumoxide::browser::{Browser, BrowserConfig};
use futures::StreamExt;
use http_body_util::{BodyExt, Full, combinators::BoxBody};
use hyper::{Request, Response, StatusCode, server::conn::http1, service::service_fn};
use hyper_util::rt::TokioIo;
use std::time::Duration;
use tokio::net::TcpListener;

type ApiBody = BoxBody<Bytes, std::convert::Infallible>;

/// Sobe um servidor HTTP mínimo (mesmo padrão de accept-loop de
/// `http/mod.rs::listen`) que só chama `serve()` — os mesmos bytes que o
/// daemon real serve, sem precisar de `AppState` (Docker/DB/etc.), que
/// `serve()` não usa.
async fn spawn_static_server() -> std::net::SocketAddr {
    let listener = TcpListener::bind("127.0.0.1:0")
        .await
        .expect("bind do servidor estático de teste");
    let addr = listener.local_addr().expect("local_addr");
    tokio::spawn(async move {
        loop {
            let Ok((stream, _)) = listener.accept().await else {
                continue;
            };
            tokio::spawn(async move {
                let svc = service_fn(|req: Request<hyper::body::Incoming>| async move {
                    let resp: Response<ApiBody> = serve(req.uri().path()).unwrap_or_else(|| {
                        Response::builder()
                            .status(StatusCode::NOT_FOUND)
                            .body(Full::new(Bytes::from_static(b"not found")).boxed())
                            .expect("404 bem-formado")
                    });
                    Ok::<_, std::convert::Infallible>(resp)
                });
                let _ = http1::Builder::new()
                    .serve_connection(TokioIo::new(stream), svc)
                    .await;
            });
        }
    });
    addr
}

/// `cargo test` roda os 3 testes deste módulo em threads concorrentes;
/// sem um `user_data_dir` próprio, todos os Chrome apontam pro mesmo
/// perfil default do chromiumoxide e o segundo a chegar morre com
/// "Failed to create SingletonLock: File exists" — cada `launch()`
/// precisa do seu diretório.
static USER_DATA_DIR_COUNTER: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);

async fn launch() -> (Browser, tokio::task::JoinHandle<()>) {
    let n = USER_DATA_DIR_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let user_data_dir =
        std::env::temp_dir().join(format!("rustploy-webui-test-{}-{n}", std::process::id()));
    let config = BrowserConfig::builder()
        .chrome_executable("/usr/bin/google-chrome")
        .no_sandbox()
        // O `--headless` antigo não existe mais nos Chrome recentes (o launch estoura
        // em LaunchTimeout com stderr vazio); o modo novo é o `--headless=new`.
        .new_headless_mode()
        .user_data_dir(user_data_dir)
        .build()
        .expect("BrowserConfig");
    let (browser, mut handler) = Browser::launch(config)
        .await
        .expect("google-chrome deve estar instalado (ver docs/inventario-paridade-telas.md)");
    // A stream de eventos CDP precisa ser drenada continuamente — sem
    // isso nenhum comando (navigate/evaluate) recebe resposta. Mesmo
    // padrão do exemplo oficial do chromiumoxide.
    let h = tokio::spawn(async move {
        while let Some(ev) = handler.next().await {
            let _ = ev;
        }
    });
    (browser, h)
}

/// Injeta um coletor de erros ANTES de qualquer script da página rodar
/// (`Page.addScriptToEvaluateOnNewDocument`), pra pegar erros de módulo
/// ES (`app.js`) que disparam antes do nosso primeiro `evaluate()`.
const ERROR_COLLECTOR_JS: &str = r#"
    window.__errors = [];
    window.addEventListener('error', (e) => window.__errors.push(String(e.message || e.error)));
    window.addEventListener('unhandledrejection', (e) => window.__errors.push('rejection: ' + String(e.reason)));
"#;

/// Abre uma aba em branco, registra o coletor de erros e SÓ ENTÃO navega
/// pra `index.html` — nessa ordem, pra `evaluate_on_new_document` valer
/// já no primeiro load (`browser.new_page(url)` navegaria direto, o que
/// deixaria a carga inicial sem o coletor).
async fn open_page(browser: &Browser, addr: std::net::SocketAddr) -> chromiumoxide::Page {
    let page = browser.new_page("about:blank").await.expect("new_page");
    page.evaluate_on_new_document(ERROR_COLLECTOR_JS)
        .await
        .expect("injeta o coletor de erros");
    page.goto(format!("http://{addr}/")).await.expect("goto");
    let _ = page.wait_for_navigation().await;
    page
}

/// Espera até `Alpine.store('app')` existir — só depois do evento
/// `load` (ver o comentário no fim de `webui/app.js`: os módulos
/// registram os `Alpine.data`/`Alpine.store` primeiro, `Alpine.start()`
/// só dispara depois).
async fn wait_alpine_ready(page: &chromiumoxide::Page) {
    for _ in 0..100 {
        if let Ok(r) = page
            .evaluate("typeof window.Alpine !== 'undefined' && !!Alpine.store('app')")
            .await
            && r.into_value::<bool>().unwrap_or(false)
        {
            return;
        }
        tokio::time::sleep(Duration::from_millis(100)).await;
    }
    panic!("Alpine.store('app') não ficou pronto a tempo");
}

/// Snapshot mínimo — mesmo formato que `http/mod.rs::snapshot()` monta e
/// `app.js::applySnapshot` consome (`kind` é ignorado por `applySnapshot`,
/// só o `onStreamEvent` do SSE real olha pra ele). Cobre o suficiente
/// pra cada tela ter pelo menos uma linha de tabela — mesmo espírito das
/// fixtures de `templates_render.rs`, sem tentar ser exaustivo.
const SNAPSHOT_JS: &str = r#"
    {
        status: { version: '0.0.0-test', uptime_secs: 3600, services_running: 1, services_total: 1 },
        deployments: [{ service_name: 'api', project_name: 'acme',
            deployment: { state: 'Live', started_at: new Date().toISOString() } }],
        projects: [{ id: 'prj_1', name: 'acme', description: '', env_vars: [], env_comments: [], secrets: ['GITHUB_TOKEN'] }],
        services: [{ project_name: 'acme', service: {
            id: 'svc_1', status: 'Running', live_container_id: 'abc123', containers: [],
            spec: { name: 'api', project_id: 'prj_1', port: 8080, replicas: 1, env_vars: [], domains: [],
                source: { Git: { url: 'https://github.com/acme/api.git', branch: 'main', root_path: '.',
                    watch_paths: [], submodules: false, dockerfile_path: 'Dockerfile', build_context: '.',
                    build_stage: null, credentials: null, username: null, provider_id: null } },
                healthcheck: { kind: 'None', interval_secs: 5, timeout_secs: 3, retries: 10, start_period_secs: 5 } } } }],
        docker_images: [], docker_volumes: [], docker_networks: [], docker_containers: [],
        jobs: [], engine: { paused: false, queued: [], active: [], recent: [] },
        registry_status: { enabled: true, domain: '', port: 5100 }, registry_repos: [],
    }
"#;

/// Semeia a sessão (bypassa login/SSE, mesma ideia de `boot()` +
/// `define_data` em `templates_render.rs`) e roda `applySnapshot` — o
/// mesmo método que o SSE real chama, então `dataLoading`/`jobsById`
/// saem consistentes.
async fn seed_connected(page: &chromiumoxide::Page) {
    wait_alpine_ready(page).await;
    let js = format!(
        r#"(() => {{
            const s = Alpine.store('app');
            s.connected = true;
            s.screen = 'shell';
            s.api = {{ baseUrl: location.origin, token: 't',
                rpc: async () => ({{ ok: false, error: 'stub' }}),
                rpcChecked: async () => ({{ ok: false, error: 'stub' }}) }};
            s.applySnapshot({SNAPSHOT_JS});
        }})()"#
    );
    page.evaluate(js).await.expect("seed do Alpine store");
}

/// Avalia `js` (uma expressão, possivelmente uma Promise) e devolve o
/// resultado como `String` — os testes serializam com `JSON.stringify`.
async fn eval_str(page: &chromiumoxide::Page, js: &str) -> String {
    page.evaluate(js)
        .await
        .unwrap_or_else(|e| panic!("evaluate falhou: {e}\n{js}"))
        .into_value::<String>()
        .expect("o JS deveria devolver uma string")
}

/// `true` se o elemento existir e estiver de fato visível (`x-show`
/// escreve `display:none` inline; `offsetParent` é `null` tanto pra
/// `display:none` quanto pra ancestral escondido — cobre os dois).
///
/// Faz polling (não uma checagem só): Alpine aplica `x-show`/`x-if` num
/// microtask agendado pelo próprio scheduler dele, não sincronamente na
/// mutação do store — então um `evaluate()` (round-trip CDP) imediatamente
/// depois de mudar `view` pode chegar antes desse microtask rodar. Sem
/// isso, o teste ficava flaky (falhava numa tela aleatória do sweep a
/// cada corrida).
async fn visible(page: &chromiumoxide::Page, selector: &str) -> bool {
    let js = format!(
        "(() => {{ const el = document.querySelector({selector:?}); return !!el && el.offsetParent !== null; }})()"
    );
    for _ in 0..20 {
        let ok = page
            .evaluate(js.as_str())
            .await
            .ok()
            .and_then(|r| r.into_value::<bool>().ok())
            .unwrap_or(false);
        if ok {
            return true;
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    }
    false
}

async fn errors(page: &chromiumoxide::Page) -> Vec<String> {
    page.evaluate("window.__errors || []")
        .await
        .ok()
        .and_then(|r| r.into_value::<Vec<String>>().ok())
        .unwrap_or_default()
}

/// Login por token de conexão: `connect()` decodifica o base64 de
/// `host:porta::token` e usa o token da API direto como Bearer — sem
/// `/api/login`; o que não decodifica vira erro na tela. O `fetch` é substituído na
/// página (o servidor de teste só serve estáticos); o SSE fica pendurado
/// para a sessão não cair de volta no login.
#[tokio::test]
async fn login_with_access_key() {
    let addr = spawn_static_server().await;
    let (browser, _handler) = launch().await;
    let page = open_page(&browser, addr).await;
    wait_alpine_ready(&page).await;

    page.evaluate(
        r#"(() => {
            window.__requests = [];
            window.fetch = (url, init = {}) => {
                const path = new URL(url, location.origin).pathname;
                window.__requests.push({ path, body: init.body || null,
                    auth: (init.headers || {})["Authorization"] || null });
                const reply = (status, body) => Promise.resolve(new Response(JSON.stringify(body), { status }));
                if (path === "/api/events") return new Promise(() => {});
                if (path === "/api/rpc") return reply(200, { DaemonStatus: { version: "t" } });
                return reply(404, {});
            };
        })()"#,
    )
    .await
    .expect("stub do fetch");

    // Recusa: a mensagem do daemon chega ao usuário, a tela não muda.
    eval_str(
        &page,
        r#"(async () => { const s = Alpine.store('app'); s.accessKey = 'segredo'; await s.connect(); return 'ok'; })()"#,
    )
    .await;
    assert_eq!(
        eval_str(&page, "Alpine.store('app').error").await,
        "that is not a connection token — paste the whole connection token (base64 of host:port::token), not just the API token"
    );
    assert_eq!(eval_str(&page, "Alpine.store('app').screen").await, "login");

    // Sucesso: o token devolvido vira o Bearer das chamadas seguintes.
    eval_str(
        &page,
        r#"(async () => { const s = Alpine.store('app');
            s.accessKey = 'MTI3LjAuMC4xOjk6Ong=';
            await s.connect(); return 'ok'; })()"#,
    )
    .await;
    assert_eq!(eval_str(&page, "Alpine.store('app').screen").await, "shell");
    assert_eq!(
        eval_str(
            &page,
            "window.__requests.find(r => r.path === '/api/rpc').auth"
        )
        .await,
        "Bearer x"
    );
    assert!(
        !eval_str(&page, "JSON.stringify(window.__requests.map(r => r.path))")
            .await
            .contains("/api/login"),
        "a webui não passa mais pelo /api/login"
    );
    // O token de conexão para copiar em Settings é montado da sessão (origem + token).
    let chave = eval_str(&page, "Alpine.store('app').serverAccessKey").await;
    {
        use base64::Engine;
        let payload = base64::engine::general_purpose::STANDARD
            .decode(&chave)
            .expect("token de conexão em base64 padrão");
        assert_eq!(String::from_utf8(payload).unwrap(), format!("{addr}::x"));
    }
    let comando = eval_str(&page, "Alpine.store('app').serverMcpCommand").await;
    assert!(
        comando.contains("/mcp") && comando.contains("Bearer x"),
        "{comando}"
    );
    assert_eq!(
        errors(&page).await,
        Vec::<String>::new(),
        "sem erros de JS no console"
    );
}

/// Varre as telas de nível superior (equivalente ao loop `for view in
/// [...]` de `templates_render.rs::all_screens_and_service_tabs_render`)
/// e confirma que cada uma monta (`x-data` fica visível) sem erro de JS.
/// `support` não existe na webui (só no client iced — ver
/// `docs/inventario-paridade-telas.md`), então não entra aqui.
#[tokio::test]
async fn all_main_screens_render() {
    let addr = spawn_static_server().await;
    let (browser, _handler) = launch().await;
    let page = open_page(&browser, addr).await;

    // Login (tela default, antes de qualquer seed).
    wait_alpine_ready(&page).await;
    assert!(
        visible(&page, ".login").await,
        "tela de login deveria estar visível antes do login"
    );

    seed_connected(&page).await;

    let views: &[(&str, &str)] = &[
        ("deployments", "[x-data=\"dashboard\"]"),
        ("running", "[x-data=\"running\"]"),
        ("projects", "[x-data=\"projects\"]"),
        ("monitoring", "[x-data=\"monitoring\"]"),
        ("ingress", "[x-data=\"ingress\"]"),
        ("docker", "[x-data=\"docker\"]"),
        ("schedules", "[x-data=\"schedules\"]"),
        ("settings", "[x-data=\"settings\"]"),
        ("deploy_engine", "[x-data=\"deployEngine\"]"),
    ];
    for (view, selector) in views {
        page.evaluate(format!("Alpine.store('app').view = {view:?}"))
            .await
            .unwrap_or_else(|e| panic!("set view={view}: {e}"));
        assert!(
            visible(&page, selector).await,
            "view={view} deveria estar visível (seletor {selector})"
        );
    }
    assert_eq!(
        errors(&page).await,
        Vec::<String>::new(),
        "sem erros de JS no console"
    );
}

/// Aba "Projeto aberto" — `view` chama-se `project` na webui contra
/// `project_services` no client iced (divergência mecânica de nome, ver
/// `docs/inventario-paridade-telas.md`); precisa de `selectedProjectId`.
#[tokio::test]
async fn project_detail_renders() {
    let addr = spawn_static_server().await;
    let (browser, _handler) = launch().await;
    let page = open_page(&browser, addr).await;
    seed_connected(&page).await;

    page.evaluate(
        "Alpine.store('app').view = 'project'; Alpine.store('app').selectedProjectId = 'prj_1'",
    )
    .await
    .expect("abre o projeto");
    assert!(
        visible(&page, "[x-data=\"projectDetail\"]").await,
        "project_detail deveria estar visível"
    );
    assert_eq!(
        errors(&page).await,
        Vec::<String>::new(),
        "sem erros de JS no console"
    );
}

/// Modal "plano de deploy": serviço com dependências mostra a ordem e três
/// botões (Confirmar / Só o serviço / Rejeitar); projeto mostra dois
/// (Aceitar / Rejeitar). Rejeitar fecha sem enfileirar nada.
#[tokio::test]
async fn deploy_plan_modal_lists_order_and_buttons() {
    let addr = spawn_static_server().await;
    let (browser, _handler) = launch().await;
    let page = open_page(&browser, addr).await;
    seed_connected(&page).await;

    let items = "[{service_id:'a',service_name:'db',wave:0,status:'Queued'},\
                 {service_id:'b',service_name:'api',wave:1,status:'Queued'}]";
    page.evaluate(format!(
        "Alpine.store('app').deployPlan = {{kind:'service',id:'b',fromDetail:false,items:{items}}}"
    ))
    .await
    .expect("abre o plano de serviço");
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
    let text = eval_str(
        &page,
        "document.querySelector('[x-win=\"\\'deploy_plan\\'\"]')?.innerText || ''",
    )
    .await;
    assert!(
        text.contains("1. db") && text.contains("2. api"),
        "ordem do plano: {text}"
    );
    assert!(
        text.contains("Only the service"),
        "botão só o serviço: {text}"
    );

    page.evaluate(format!(
        "Alpine.store('app').deployPlan = {{kind:'project',id:'p',fromDetail:false,items:{items}}}"
    ))
    .await
    .expect("abre o plano de projeto");
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
    let text = eval_str(
        &page,
        "document.querySelector('[x-win=\"\\'deploy_plan\\'\"]')?.innerText || ''",
    )
    .await;
    assert!(text.contains("Accept"), "botão aceitar: {text}");
    assert!(
        !text.contains("Only the service"),
        "projeto não oferece só o serviço: {text}"
    );

    page.evaluate("Alpine.store('app').closeDeployPlan()")
        .await
        .expect("rejeita");
    assert_eq!(
        eval_str(&page, "String(Alpine.store('app').deployPlan)").await,
        "null"
    );
    assert_eq!(errors(&page).await, Vec::<String>::new(), "sem erros de JS");
}

/// Modal "reordenar serviços": mover (↑/↓ e arrastar) muda só a ordem em edição;
/// Cancelar descarta e o RPC vai com os ids na nova ordem.
#[tokio::test]
async fn services_reorder_modal_moves_and_cancels() {
    let addr = spawn_static_server().await;
    let (browser, _handler) = launch().await;
    let page = open_page(&browser, addr).await;
    seed_connected(&page).await;

    let seed = r#"(() => {
        const s = Alpine.store('app');
        s.snap = { ...(s.snap || {}), services: [['a','alfa'], ['b','beta'], ['c','gama']].map(([k, n]) => ({ service: { id: 'svc_' + k, status: 'Running', spec: { name: n, project_id: 'prj_1' } } })) };
        s.selectedProjectId = 'prj_1';
        s.openServicesReorder();
        s.servicesReorderStep('svc_c', -1);          // a b c -> a c b
        s.servicesReorderMove('svc_b', 'svc_a');     // a c b -> b a c
        return s.servicesReorder.ids.join(',');
    })()"#;
    assert_eq!(
        eval_str(&page, seed).await,
        "svc_b,svc_a,svc_c",
        "ordem em edição"
    );
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
    let text = eval_str(
        &page,
        "document.querySelector('[x-win=\"\\'services_reorder\\'\"]')?.innerText || ''",
    )
    .await;
    assert!(
        text.contains("Reorder") && text.contains("Cancel"),
        "botões: {text}"
    );
    assert!(
        text.find("beta") < text.find("alfa") && text.find("alfa") < text.find("gama"),
        "linhas na ordem editada: {text}"
    );

    page.evaluate("Alpine.store('app').closeServicesReorder()")
        .await
        .expect("cancela");
    assert_eq!(
        eval_str(&page, "String(Alpine.store('app').servicesReorder)").await,
        "null"
    );
    assert_eq!(errors(&page).await, Vec::<String>::new(), "sem erros de JS");
}

/// Detalhe de serviço + a aba General (edição de origem — Compose / Git
/// / conta conectada / Zip), implementada nesta sessão. `serviceDetail`
/// não é derivado de `snap` (o real vem de `fetchServiceDetail`), então
/// precisa ser semeado à mão — mesma razão de `m.define_data("service_env",
/// ...)` no teste iced.
#[tokio::test]
async fn service_detail_and_general_tab_render() {
    let addr = spawn_static_server().await;
    let (browser, _handler) = launch().await;
    let page = open_page(&browser, addr).await;
    seed_connected(&page).await;

    let open_service = r#"(() => {
        const s = Alpine.store('app');
        s.view = 'service';
        s.selectedServiceId = 'svc_1';
        s.serviceTab = 'general';
        s.serviceLoading = false;
        s.serviceDeployments = [];
        s.serviceDetail = {
            id: 'svc_1', status: 'Running', live_container_id: 'abc123',
            spec: { name: 'api', port: 8080, replicas: 1, project_id: 'prj_1', env_vars: [], domains: [],
                source: { Git: { url: 'https://github.com/acme/api.git', branch: 'main', root_path: '.',
                    watch_paths: ['src'], submodules: false, dockerfile_path: 'Dockerfile', build_context: '.',
                    build_stage: null, credentials: null, username: null, provider_id: null } },
                healthcheck: { kind: 'None', interval_secs: 5, timeout_secs: 3, retries: 10, start_period_secs: 5 } },
        };
    })()"#;
    page.evaluate(open_service).await.expect("abre o serviço");
    assert!(
        visible(&page, "[x-data=\"serviceDetail\"]").await,
        "service_detail deveria estar visível"
    );
    assert!(
        visible(
            &page,
            "[x-data=\"serviceDetail\"] input[x-model=\"serviceFormRepoUrl\"]"
        )
        .await,
        "aba General deveria mostrar o form Git (sourceKind=Git)"
    );

    // As 3 sub-abas Provider (mesma cobertura do sweep de prov_tab em
    // templates_render.rs) — cada uma com um marcador só seu no DOM.
    let prov_tabs: &[(&str, &str)] = &[
        (
            "git",
            "[x-data=\"serviceDetail\"] input[x-model=\"serviceFormRepoUrl\"]",
        ),
        (
            "gitea",
            "[x-data=\"serviceDetail\"] select[x-model=\"giteaProviderId\"]",
        ),
        ("zip", "[x-data=\"serviceDetail\"] input[type=\"file\"]"),
    ];
    for (tab, selector) in prov_tabs {
        page.evaluate(format!(
            "Alpine.$data(document.querySelector('[x-data=\"serviceDetail\"]')).setProviderTab({tab:?})"
        ))
        .await
        .unwrap_or_else(|e| panic!("setProviderTab({tab}): {e}"));
        assert!(
            visible(&page, selector).await,
            "prov_tab={tab} deveria mostrar {selector}"
        );
    }

    // Compose: troca a origem inteira e confirma que o textarea aparece.
    page.evaluate(
        r#"(() => {
            const s = Alpine.store('app');
            s.serviceDetail = JSON.parse(JSON.stringify(s.serviceDetail));
            s.serviceDetail.spec.source = { Compose: { content: 'services:\n  web:\n    image: nginx\n' } };
            Alpine.$data(document.querySelector('[x-data="serviceDetail"]')).initGeneralForm();
        })()"#,
    )
    .await
    .expect("troca pra origem Compose");
    // Seletor ESCOPADO ao componente: `composeText` também é o nome do
    // campo local do wizard "Novo serviço" (`newService`, passo Compose
    // colado) — `document.querySelector` sem escopo pegava aquele
    // textarea (fora de tela, `x-show=false`) em vez do nosso.
    assert!(
        visible(
            &page,
            "[x-data=\"serviceDetail\"] textarea[x-model=\"composeText\"]"
        )
        .await,
        "origem Compose deveria mostrar o editor de texto"
    );

    assert_eq!(
        errors(&page).await,
        Vec::<String>::new(),
        "sem erros de JS no console"
    );
}

/// Renomear serviço (aba General): o campo aparece, o aviso muda conforme o
/// tipo (Compose × Application), `renameService()` manda o spec inteiro só
/// com o nome trocado, não manda nada se o nome não mudou, e o card
/// "Internal URL" de um Compose continua apontando para a chave do YAML
/// depois do rename (o hostname interno não acompanha o nome).
#[tokio::test]
async fn rename_service_in_general_tab() {
    let addr = spawn_static_server().await;
    let (browser, _handler) = launch().await;
    let page = open_page(&browser, addr).await;
    seed_connected(&page).await;

    page.evaluate(
        r#"(() => {
            const s = Alpine.store('app');
            s.view = 'service';
            s.selectedServiceId = 'svc_1';
            s.serviceTab = 'general';
            s.serviceLoading = false;
            s.serviceDeployments = [];
            s.serviceDetail = {
                id: 'svc_1', status: 'Running', live_container_id: null,
                spec: { name: 'banco', port: 5432, replicas: 1, project_id: 'prj_1', product: 'postgres',
                    env_vars: [], domains: [],
                    source: { Compose: { content: 'services:\n  # comentário\n\n  rp_banco:\n    image: postgres:18\n' } },
                    healthcheck: { kind: 'None', interval_secs: 5, timeout_secs: 3, retries: 10, start_period_secs: 5 } },
            };
            // Captura o que o rename manda salvar, sem daemon.
            window.__saved = [];
            s.saveServiceSpec = async (spec, msg) => { window.__saved.push({ spec, msg }); return { ok: true }; };
            window.__toasts = [];
            s.toastError = (m) => window.__toasts.push(m);
            Alpine.$data(document.querySelector('[x-data="serviceDetail"]')).initGeneralForm();
        })()"#,
    )
    .await
    .expect("abre o serviço Compose");

    assert!(
        visible(
            &page,
            "[x-data=\"serviceDetail\"] input[x-model=\"editName\"]"
        )
        .await,
        "a aba General deveria mostrar o campo de nome"
    );
    let d = "Alpine.$data(document.querySelector('[x-data=\"serviceDetail\"]'))";
    assert_eq!(
        eval_str(
            &page,
            "(() => Alpine.$data(document.querySelector('[x-data=\"serviceDetail\"]')).editName)()"
        )
        .await,
        "banco",
        "o campo começa com o nome atual"
    );
    assert!(
        eval_str(&page, "(() => Alpine.$data(document.querySelector('[x-data=\"serviceDetail\"]')).renameNote)()")
            .await
            .contains("volumes"),
        "Compose: o aviso diz que a stack e os volumes não mudam"
    );

    // Mesmo nome e nome vazio: nada é salvo; o vazio avisa.
    let _ = eval_str(
        &page,
        &format!("(async () => {{ const d = {d}; d.editName = 'banco'; await d.renameService(); d.editName = '   '; await d.renameService(); return ''; }})()")
    )
    .await;
    assert_eq!(
        eval_str(
            &page,
            "(() => JSON.stringify({ saved: window.__saved.length, toasts: window.__toasts }))()"
        )
        .await,
        r#"{"saved":0,"toasts":["Enter the service name"]}"#,
        "mesmo nome não salva; vazio só avisa"
    );

    // Nome novo: manda o spec inteiro (fonte, porta, product) só com o nome trocado.
    let saved = eval_str(
        &page,
        &format!("(async () => {{ const d = {d}; d.editName = '  meu-banco  '; await d.renameService(); const x = window.__saved[0]; return JSON.stringify({{ n: window.__saved.length, msg: x.msg, name: x.spec.name, port: x.spec.port, kind: x.spec.product, content: x.spec.source.Compose.content, edit: d.editName }}); }})()")
    )
    .await;
    let v: serde_json::Value = serde_json::from_str(&saved).unwrap();
    assert_eq!(v["n"], 1);
    assert_eq!(v["msg"], "service renamed");
    assert_eq!(v["name"], "meu-banco", "o nome é aparado");
    assert_eq!(v["port"], 5432);
    assert_eq!(v["kind"], "postgres");
    assert!(v["content"].as_str().unwrap().contains("rp_banco:"));
    assert_eq!(v["edit"], "meu-banco");

    // O detalhe passa a ter o nome novo; o host interno segue o YAML.
    let url = eval_str(
        &page,
        &format!("(() => {{ Alpine.store('app').serviceDetail.spec.name = 'meu-banco'; {d}.connectionUrl = 'postgresql://u:p@rp_banco:5432/db'; return {d}.connectionInfo.internalUrl; }})()")
    )
    .await;
    // O host (chave do YAML) agora é decidido no daemon
    // (`crate::platform::connection::compose_host`, testado lá); a webui só exibe.
    assert_eq!(url, "postgresql://u:p@rp_banco:5432/db");

    // Application: outro aviso.
    let app = eval_str(
        &page,
        &format!("(() => {{ {d}.connectionUrl = ''; const s = Alpine.store('app'); s.serviceDetail = {{ id: 'svc_2', status: 'Running', live_container_id: null, spec: {{ name: 'meu-api', port: 8080, replicas: 1, project_id: 'prj_1', env_vars: [], domains: [], source: {{ Registry: {{ image: 'nginx' }} }}, healthcheck: {{ kind: 'None', interval_secs: 5, timeout_secs: 3, retries: 10, start_period_secs: 5 }} }} }}; return JSON.stringify({{ note: {d}.renameNote, url: {d}.connectionInfo.internalUrl }}); }})()")
    )
    .await;
    let a: serde_json::Value = serde_json::from_str(&app).unwrap();
    assert!(a["note"].as_str().unwrap().contains("next deploy"));
    assert_eq!(a["url"], "—", "sem a URL do daemon, não inventa uma");

    assert_eq!(
        errors(&page).await,
        Vec::<String>::new(),
        "sem erros de JS no console"
    );
}

/// Toasts (`$store.app.toast`): o feedback de ação da webui, que até
/// então só existia na GUI desktop. Cobre o que a mudança promete —
/// aparecer com a cor do kind, empilhar, sair no clique do "×" e expirar
/// sozinho — porque nada disso passa por um snapshot ou por uma rota: é
/// só store + template, e um `cargo test` verde sem navegador não diria
/// nada sobre ele.
#[tokio::test]
async fn toasts_appear_stack_and_expire() {
    let addr = spawn_static_server().await;
    let (browser, _handler) = launch().await;
    let page = open_page(&browser, addr).await;
    seed_connected(&page).await;

    page.evaluate(
        r#"(() => {
            const s = Alpine.store('app');
            s.toastOk('salvo');
            s.toastError('erro: falhou');
            s.toastWarn('confira os campos');
        })()"#,
    )
    .await
    .expect("dispara três toasts");

    assert!(
        visible(&page, ".toast-wrap .toast--success").await,
        "toast de sucesso deveria aparecer"
    );
    for kind in ["success", "error", "warning"] {
        assert!(
            visible(&page, &format!(".toast-wrap .toast--{kind}")).await,
            "toast kind={kind} deveria aparecer"
        );
    }
    let count = page
        .evaluate("document.querySelectorAll('.toast-wrap .toast').length")
        .await
        .expect("conta os toasts")
        .into_value::<u32>()
        .expect("contagem numérica");
    assert_eq!(
        count, 3,
        "os três toasts deveriam empilhar, não se substituir"
    );

    // O "×" dispensa só o seu.
    page.evaluate("document.querySelector('.toast-wrap .toast--error .toast__close').click()")
        .await
        .expect("clica no × do toast de erro");
    for _ in 0..20 {
        let n = page
            .evaluate("document.querySelectorAll('.toast-wrap .toast').length")
            .await
            .ok()
            .and_then(|r| r.into_value::<u32>().ok())
            .unwrap_or(9);
        if n == 2 {
            break;
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    }
    let restantes = page
        .evaluate(
            "[...document.querySelectorAll('.toast-wrap .toast')].map(e => e.className).join(' ')",
        )
        .await
        .expect("classes restantes")
        .into_value::<String>()
        .expect("string");
    assert!(
        !restantes.contains("toast--error"),
        "o × deveria remover o toast clicado; restou: {restantes}"
    );
    assert!(
        restantes.contains("toast--success") && restantes.contains("toast--warning"),
        "os outros dois deveriam continuar; restou: {restantes}"
    );

    // Expiração automática: duração curta em vez de esperar os 4s padrão.
    page.evaluate("Alpine.store('app').toast('some sozinho', 'info', 150)")
        .await
        .expect("toast curto");
    assert!(
        visible(&page, ".toast-wrap .toast--info").await,
        "toast info deveria aparecer antes de expirar"
    );
    tokio::time::sleep(Duration::from_millis(400)).await;
    let sobrou_info = page
        .evaluate("!!document.querySelector('.toast-wrap .toast--info')")
        .await
        .expect("consulta o toast info")
        .into_value::<bool>()
        .expect("bool");
    assert!(!sobrou_info, "o toast deveria ter expirado sozinho");

    assert_eq!(
        errors(&page).await,
        Vec::<String>::new(),
        "sem erros de JS no console"
    );
}

/// Servidor de banco compartilhado: a aba Databases só aparece no serviço
/// `shared`, lista os databases e manda o `ManagedDatabaseCreate` certo.
#[tokio::test]
async fn shared_server_databases_tab() {
    let addr = spawn_static_server().await;
    let (browser, _handler) = launch().await;
    let page = open_page(&browser, addr).await;
    seed_connected(&page).await;

    page.evaluate(
        r#"(() => {
            const s = Alpine.store('app');
            window.__rpc = [];
            s.api.rpc = async (c) => {
                window.__rpc.push(c);
                if (c === 'ProjectList') return { ok: true, value: { Projects: [{ id: 'prj_a', name: 'app-a' }] } };
                if (c.ManagedDatabaseList) return { ok: true, value: { ManagedDatabases: [{ id: 'mdb_1', project_id: 'prj_a', name: 'gestao', env_var: 'DATABASE_URL', connection_url: 'postgresql://gestao:pw@rp-shared-x:5432/gestao' }] } };
                return { ok: false, error: 'stub' };
            };
            s.api.rpcChecked = async (c) => { window.__rpc.push(c); return { ok: true, value: {} }; };
            s.view = 'service';
            s.selectedServiceId = 'svc_1';
            s.serviceTab = 'databases';
            s.serviceLoading = false;
            s.serviceDeployments = [];
            s.toastOk = () => {};
            s.serviceDetail = {
                id: 'svc_1', status: 'Running', live_container_id: null,
                spec: { name: 'pg', port: 5432, replicas: 1, project_id: 'prj_i', product: 'postgres', shared: {},
                    env_vars: [], domains: [],
                    source: { Compose: { content: 'services:\n  rp_pg:\n    image: postgres:18\n' } },
                    healthcheck: { kind: 'None', interval_secs: 5, timeout_secs: 3, retries: 10, start_period_secs: 5 } },
            };
        })()"#,
    )
    .await
    .expect("abre o shared server");

    assert!(
        visible(
            &page,
            "[x-data=\"serviceDetail\"] input[x-model=\"serviceFormSharedDatabase.name\"]"
        )
        .await,
        "a aba Databases deveria mostrar o formulário"
    );
    let d = "Alpine.$data(document.querySelector('[x-data=\"serviceDetail\"]'))";
    let listed = eval_str(
        &page,
        &format!("(async () => {{ const d = {d}; await d.loadSharedState(); return JSON.stringify({{ n: d.mdbs.length, proj: d.mdbs[0].project, env: d.mdbs[0].envVar }}); }})()"),
    )
    .await;
    assert_eq!(listed, r#"{"n":1,"proj":"app-a","env":"DATABASE_URL"}"#);

    let sent = eval_str(
        &page,
        &format!("(async () => {{ const d = {d}; window.__rpc = []; d.serviceFormSharedDatabase = {{ name: ' rdo ', project: 'prj_a', env: '', limit: '20', timeout: '', overwrite: true }}; await d.createSharedDatabase(); return JSON.stringify(window.__rpc.find(c => c.ManagedDatabaseCreate).ManagedDatabaseCreate); }})()"),
    )
    .await;
    let v: serde_json::Value = serde_json::from_str(&sent).unwrap();
    assert_eq!(v["name"], "rdo", "o nome é aparado");
    assert_eq!(v["server_service_id"], "svc_1");
    assert_eq!(v["connection_limit"], 20);
    assert!(v["statement_timeout_ms"].is_null(), "vazio vira null");
    assert_eq!(v["overwrite_env"], true);

    assert_eq!(
        errors(&page).await,
        Vec::<String>::new(),
        "sem erros de JS no console"
    );
}

/// Aba Migrar: só aparece num banco Compose não compartilhado, lista os
/// destinos do mesmo projeto e manda o `MigrationStart` certo.
#[tokio::test]
async fn migrate_old_database_tab() {
    let addr = spawn_static_server().await;
    let (browser, _handler) = launch().await;
    let page = open_page(&browser, addr).await;
    seed_connected(&page).await;

    page.evaluate(
        r#"(() => {
            const s = Alpine.store('app');
            window.__rpc = [];
            s.api.rpc = async (c) => {
                window.__rpc.push(c);
                if (c === 'ManagedDatabaseListAll') return { ok: true, value: { ManagedDatabases: [
                    { id: 'mdb_1', project_id: 'prj_a', name: 'rdo', env_var: 'DATABASE_URL' },
                    { id: 'mdb_2', project_id: 'prj_outro', name: 'x', env_var: 'DATABASE_URL' }] } };
                if (c.MigrationList) return { ok: true, value: { Migrations: [{ id: 'mig_1', source_service_id: 'svc_old', status: 'Completed',
                    steps: [{ name: 'Pré-checagem', state: 'ok', detail: '' }, { name: 'Dump + restore', state: 'ok', detail: '' }] }] } };
                return { ok: false, error: 'stub' };
            };
            s.api.rpcChecked = async (c) => { window.__rpc.push(c); return { ok: true, value: {} }; };
            s.toastOk = () => {};
            s.view = 'service';
            s.selectedServiceId = 'svc_old';
            s.serviceTab = 'migrar';
            s.serviceLoading = false;
            s.serviceDeployments = [];
            s.serviceDetail = {
                id: 'svc_old', status: 'Running', live_container_id: null,
                spec: { name: 'banco', port: 5432, replicas: 1, project_id: 'prj_a', product: 'postgres',
                    env_vars: [{ key: 'POSTGRES_DB', value: { Plain: 'meu_db' } }], domains: [],
                    source: { Compose: { content: 'services:\n  rp_banco:\n    image: postgres:18\n' } },
                    healthcheck: { kind: 'None', interval_secs: 5, timeout_secs: 3, retries: 10, start_period_secs: 5 } },
            };
        })()"#,
    )
    .await
    .expect("abre o banco antigo");

    let d = "Alpine.$data(document.querySelector('[x-data=\"serviceDetail\"]'))";
    let loaded = eval_str(
        &page,
        &format!("(async () => {{ const d = {d}; await d.loadMigration(); return JSON.stringify({{ dests: d.migrationDestinations.map(x => x.id), db: d.serviceFormMigration.db, st: d.mig.status, steps: d.migrationSteps.map(x => x.icon).join('') }}); }})()"),
    )
    .await;
    assert_eq!(
        loaded, r#"{"dests":["mdb_1"],"db":"meu_db","st":"Completed","steps":"✓✓"}"#,
        "só destinos do mesmo projeto; origem preenchida do POSTGRES_DB"
    );
    assert!(
        visible(
            &page,
            "[x-data=\"serviceDetail\"] input[x-model=\"serviceFormMigration.db\"]"
        )
        .await,
        "a aba Migrar deveria mostrar o formulário"
    );
    let sent = eval_str(
        &page,
        &format!("(async () => {{ window.confirm = () => true; const d = {d}; window.__rpc = []; d.serviceFormMigration.dest = 'mdb_1'; d.serviceFormMigration.env = ' URL_BANCO '; await d.startMigration(); return JSON.stringify(window.__rpc.find(c => c.MigrationStart).MigrationStart); }})()"),
    )
    .await;
    let v: serde_json::Value = serde_json::from_str(&sent).unwrap();
    assert_eq!(v["source_service_id"], "svc_old");
    assert_eq!(v["source_database"], "meu_db");
    assert_eq!(v["dest_database_id"], "mdb_1");
    assert_eq!(v["env_var"], "URL_BANCO", "a env var é aparada");

    assert_eq!(
        errors(&page).await,
        Vec::<String>::new(),
        "sem erros de JS no console"
    );
}
/// A janela "Ações do job" (a lista de botões da linha não cabia): o estado
/// quente/frio vem do daemon, o "⋯" abre a janela com as ações certas para o
/// estado do job, e "Aquecer" num job já quente só avisa — sem disparar nada.
#[tokio::test]
async fn job_actions_window_lists_actions_and_warm_status() {
    let addr = spawn_static_server().await;
    let (browser, _handler) = launch().await;
    let page = open_page(&browser, addr).await;
    seed_connected(&page).await;

    let seeded = eval_str(
        &page,
        &format!(
            r#"(() => {{
                const s = Alpine.store('app');
                const snapshot = {SNAPSHOT_JS};
                const job = {{ id: 'job_1', project_id: 'prj_1', trigger_service_id: 'svc_1', name: 'migrator',
                    compose: 'services: {{}}', main_service: 'main', env_vars: [], env_comments: [], enabled: true,
                    recurrence: null, last_run_at: null, next_run_at: null }};
                snapshot.jobs = [{{ job, project_name: 'acme', trigger_service_name: 'api', last_run: null,
                    warm: {{ job_id: 'job_1', warm: false, warming: false, reason: 'nunca aquecido', warmed_at: null }} }}];
                s.applySnapshot(snapshot);
                window.__commands = [];
                s.api.rpcChecked = async (command) => {{
                    window.__commands.push(command);
                    return {{ ok: true, value: {{ JobWarmRequested: {{ already_warm: true }} }} }};
                }};
                s.view = 'schedules';
                return 'ok';
            }})()"#
        ),
    )
    .await;
    assert_eq!(seeded, "ok");

    assert!(
        visible(&page, ".table__col-warm.state-cell--muted").await,
        "a linha deveria mostrar o job frio, com o estado vindo do daemon"
    );
    assert!(
        !visible(&page, ".job-actions").await,
        "a janela de ações começa fechada"
    );

    eval_str(
        &page,
        "(() => { document.querySelector('[title=\"Job actions\"]').click(); return 'ok'; })()",
    )
    .await;
    assert!(
        visible(&page, ".job-actions").await,
        "o ⋯ da linha deveria abrir a janela de ações"
    );
    let items = eval_str(
        &page,
        "JSON.stringify([...document.querySelectorAll('.job-actions__item')].filter(el => el.offsetParent !== null).map(el => el.textContent.trim()))",
    )
    .await;
    assert_eq!(
        items, r#"["▶ Run now","◐ Warm","‖ Pause","🔑 Variables and secrets","✎ Edit","✕ Remove"]"#,
        "job parado e sem execução: sem cancelar nem logs"
    );
    assert!(
        eval_str(
            &page,
            "document.querySelector('.job-actions__status').textContent"
        )
        .await
        .contains("nunca aquecido"),
        "a janela mostra por que o job está frio"
    );

    // Quente: "Aquecer" só avisa — o daemon respondeu `already_warm`, e a tela mostra o aviso.
    eval_str(
        &page,
        r#"(() => { Alpine.store('app').snap.jobs[0].warm = { job_id: 'job_1', warm: true, warming: false, reason: null, warmed_at: new Date().toISOString() }; return 'ok'; })()"#,
    )
    .await;
    assert!(
        visible(&page, ".job-actions .state-cell--ok").await,
        "a janela relê o estado do snapshot ao vivo"
    );
    eval_str(
        &page,
        "(() => { [...document.querySelectorAll('.job-actions__item')].find(el => el.textContent.includes('Warm')).click(); return 'ok'; })()",
    )
    .await;
    tokio::time::sleep(Duration::from_millis(300)).await;
    assert_eq!(
        eval_str(&page, "JSON.stringify(window.__commands)").await,
        r#"[{"JobWarm":{"job_id":"job_1"}}]"#
    );
    assert!(
        eval_str(
            &page,
            "JSON.stringify(Alpine.store('app').toasts.map(t => t.message))"
        )
        .await
        .contains("job is already warm"),
        "job quente: o toast avisa que já estava aquecido"
    );

    // Quente: "Reconstruir (sem cache)" aparece, confirma e manda `force: true`.
    eval_str(
        &page,
        "(() => { window.confirm = () => true; window.__commands = []; [...document.querySelectorAll('.job-actions__item')].find(el => el.textContent.includes('Rebuild')).click(); return 'ok'; })()",
    )
    .await;
    tokio::time::sleep(Duration::from_millis(300)).await;
    assert_eq!(
        eval_str(&page, "JSON.stringify(window.__commands)").await,
        r#"[{"JobWarm":{"job_id":"job_1","force":true}}]"#
    );
    assert!(
        eval_str(
            &page,
            "JSON.stringify(Alpine.store('app').toasts.map(t => t.message))"
        )
        .await
        .contains("rebuild started"),
        "o toast confirma que a reconstrução começou"
    );

    // Em execução: cancelar no lugar de rodar, e os logs da última execução.
    eval_str(
        &page,
        r#"(() => { Alpine.store('app').snap.jobs[0].last_run = { id: 'jrun_1', success: null }; return 'ok'; })()"#,
    )
    .await;
    tokio::time::sleep(Duration::from_millis(300)).await;
    let items = eval_str(
        &page,
        "JSON.stringify([...document.querySelectorAll('.job-actions__item')].filter(el => el.offsetParent !== null).map(el => el.textContent.trim()))",
    )
    .await;
    assert_eq!(
        items,
        r#"["■ Cancel run","◐ Warm","↻ Rebuild (no cache)","≡ View logs","‖ Pause","🔑 Variables and secrets","✎ Edit","✕ Remove"]"#
    );

    assert_eq!(
        errors(&page).await,
        Vec::<String>::new(),
        "sem erros de JS no console"
    );
}

/// Settings → Sync → "Baixar infra": o daemon devolve os arquivos do `state_git` (`InfraFiles`) e a
/// webui os entrega num `.zip`. A aba "Infra as Code" não existe mais.
#[tokio::test]
async fn infra_download_zip() {
    let addr = spawn_static_server().await;
    let (browser, _handler) = launch().await;
    let page = open_page(&browser, addr).await;
    seed_connected(&page).await;

    eval_str(
        &page,
        r#"(async () => {
            const s = Alpine.store('app');
            window.__downloads = [];
            const click = HTMLAnchorElement.prototype.click;
            HTMLAnchorElement.prototype.click = function () {
                if (this.download) { window.__downloads.push({ name: this.download, href: this.href }); return; }
                return click.call(this);
            };
            s.api = { baseUrl: location.origin, token: 't',
                rpcChecked: async (cmd) => cmd === 'InfraDownload'
                    ? { ok: true, value: { InfraFiles: [
                        { path: 'MANIFEST.json', content: '{"schema":1}\n' },
                        { path: 'projects/prj_1/project.yml', content: 'name: loja\n' } ] } }
                    : { ok: false, error: 'stub' },
                rpc: async () => ({ ok: false, error: 'stub' }) };
            s.view = 'settings'; s.settingsTab = 'gitsync';
            return 'ok';
        })()"#,
    )
    .await;
    assert!(
        visible(&page, "[x-data=\"settings\"]").await,
        "Settings visível"
    );
    assert_eq!(
        eval_str(
            &page,
            "String([...document.querySelectorAll('.tabs__tab')].some(b => b.textContent.includes('Infra as Code')))"
        )
        .await,
        "false",
        "a aba Infra as Code saiu"
    );
    assert_eq!(
        eval_str(
            &page,
            "String([...document.querySelectorAll('button')].some(b => b.textContent.trim() === 'Download infra'))"
        )
        .await,
        "true",
        "o botão Baixar infra está na aba Sync"
    );

    let out = eval_str(
        &page,
        r#"(async () => {
            await Alpine.store('app').infraDownload();
            const d = window.__downloads[0];
            const bytes = new Uint8Array(await (await fetch(d.href)).arrayBuffer());
            const text = new TextDecoder('latin1').decode(bytes);
            return JSON.stringify({ name: d.name, pk: text.startsWith('PK'),
                tem_manifest: text.includes('MANIFEST.json'), tem_projeto: text.includes('projects/prj_1/project.yml'),
                tem_conteudo: text.includes('name: loja'), msg: Alpine.store('app').infraDownloadMessage });
        })()"#,
    )
    .await;
    assert_eq!(
        out,
        r##"{"name":"rustploy-infra.zip","pk":true,"tem_manifest":true,"tem_projeto":true,"tem_conteudo":true,"msg":"downloaded as rustploy-infra.zip"}"##
    );

    // Erro do daemon (valor em claro no estado): aparece na mensagem, sem baixar nada.
    let err = eval_str(
        &page,
        r#"(async () => {
            const s = Alpine.store('app');
            window.__downloads = [];
            s.api.rpcChecked = async () => ({ ok: false, error: 'há 1 valor(es) em claro' });
            await s.infraDownload();
            return JSON.stringify({ n: window.__downloads.length, msg: s.infraDownloadMessage });
        })()"#,
    )
    .await;
    assert_eq!(err, r##"{"n":0,"msg":"erro: há 1 valor(es) em claro"}"##);

    assert_eq!(
        errors(&page).await,
        Vec::<String>::new(),
        "sem erros de JS no console"
    );
}

/// Aba Logs do serviço: nasce do log guardado (`LogsHistory`), "Carregar anteriores" põe a página
/// mais velha por cima e marca onde o container mudou; sem histórico, cai no `LogsGet` ao vivo.
#[tokio::test]
async fn service_logs_start_from_history_and_load_older() {
    let addr = spawn_static_server().await;
    let (browser, _handler) = launch().await;
    let page = open_page(&browser, addr).await;
    seed_connected(&page).await;

    let out = eval_str(
        &page,
        r#"(async () => {
            const s = Alpine.store('app');
            const calls = [];
            const e = (t, c, line, stream = 'Stdout') => ({ timestamp: t, container_id: c, stream, line });
            s.api = { baseUrl: location.origin, token: 't',
                rpcChecked: async (cmd) => {
                    const a = cmd.LogsHistory;
                    calls.push(['older', a.before]);
                    return { ok: true, value: { LogsHistory: {
                        entries: [e('2026-11-05T01:00:00Z', 'aaaaaaaaaaaa1234', 'velho 1'), e('2026-11-05T01:00:01Z', 'aaaaaaaaaaaa1234', 'velho 2')],
                        next_before: null } } };
                },
                rpc: async (cmd) => {
                    if (cmd.LogsHistory) {
                        calls.push(['seed', cmd.LogsHistory.before ?? null]);
                        return { ok: true, value: { LogsHistory: {
                            entries: [e('2026-11-05T02:00:00Z', 'bbbbbbbbbbbb9999', 'novo 1'), e('2026-11-05T02:00:01Z', 'bbbbbbbbbbbb9999', 'novo erro', 'Stderr')],
                            next_before: '2026-11-05T02:00:00Z' } } };
                    }
                    return { ok: false, error: 'stub' };
                } };
            s.selectedServiceId = 'svc_1'; s.serviceTab = 'logs';
            await s.startServiceLogs();
            const seeded = s.serviceLogLines.map(l => l.line);
            const more1 = s.serviceLogMore;
            await s.serviceLogLoadOlder();
            return JSON.stringify({ seeded, more1, after: s.serviceLogLines.map(l => l.line),
                more2: s.serviceLogMore, calls });
        })()"#,
    )
    .await;
    let v: serde_json::Value = serde_json::from_str(&out).unwrap();
    assert_eq!(v["seeded"], serde_json::json!(["novo 1", "novo erro"]));
    assert_eq!(v["more1"], "2026-11-05T02:00:00Z", "há mais log guardado");
    assert_eq!(
        v["after"],
        serde_json::json!([
            "velho 1",
            "velho 2",
            "— other container: bbbbbbbbbbbb —",
            "novo 1",
            "novo erro"
        ]),
        "o mais velho vem por cima, com separador onde o container mudou"
    );
    assert_eq!(v["more2"], serde_json::Value::Null, "acabou o histórico");
    assert_eq!(
        v["calls"][1],
        serde_json::json!(["older", "2026-11-05T02:00:00Z"])
    );

    // Sem histórico (Compose, log desligado): cai no log ao vivo do motor.
    let fallback = eval_str(
        &page,
        r#"(async () => {
            const s = Alpine.store('app');
            s.api = { baseUrl: location.origin, token: 't',
                rpcChecked: async () => ({ ok: false, error: 'stub' }),
                rpc: async (cmd) => cmd.LogsGet
                    ? { ok: true, value: { Logs: [{ stream: 'Stdout', line: 'ao vivo', timestamp: '2026-11-05T03:00:00Z' }] } }
                    : { ok: false, error: 'LogsDisabled' } };
            s.serviceLogLines = [];
            await s.startServiceLogs();
            return JSON.stringify({ lines: s.serviceLogLines.map(l => l.line), more: s.serviceLogMore });
        })()"#,
    )
    .await;
    assert_eq!(fallback, r##"{"lines":["ao vivo"],"more":null}"##);
    assert_eq!(
        errors(&page).await,
        Vec::<String>::new(),
        "sem erros de JS no console"
    );
}

/// Aba Logs por execução: o painel ao vivo mostra SÓ a execução atual; as anteriores viram uma lista
/// (deploy, imagem, desfecho) com "Ver logs" (janela só dela, com data e hora), excluir e
/// "limpar selecionados" (em lote, com confirmação); depois de excluir a lista recarrega.
#[tokio::test]
async fn service_log_executions_list_open_and_delete() {
    let addr = spawn_static_server().await;
    let (browser, _handler) = launch().await;
    let page = open_page(&browser, addr).await;
    seed_connected(&page).await;

    let out = eval_str(
        &page,
        r#"(async () => {
            const s = Alpine.store('app');
            window.confirm = () => true;
            const calls = [];
            let executions = [
              { container_ids: ['cur000000001'], deployment_id: 'dep_3', image: 'api:3', started_at: '2026-11-06T10:00:00Z', ended_at: '2026-11-06T11:00:00Z', lines: 30, bytes: 3000, current: true, partial: false, outcome: 'Live' },
              { container_ids: ['old000000002'], deployment_id: 'dep_2', image: 'api:2', started_at: '2026-11-05T10:00:00Z', ended_at: '2026-11-05T11:00:00Z', lines: 20, bytes: 2000, current: false, partial: false, outcome: 'Stopped' },
              { container_ids: ['bad000000003'], deployment_id: 'dep_1', image: 'api:1', started_at: '2026-11-04T10:00:00Z', ended_at: '2026-11-04T10:05:00Z', lines: 5, bytes: 500, current: false, partial: true, outcome: 'Failed' },
            ];
            const entry = (c, line) => ({ timestamp: '2026-11-05T10:00:00Z', container_id: c, stream: 'Stdout', line });
            s.api = { baseUrl: location.origin, token: 't',
                rpcChecked: async (cmd) => {
                    if (cmd.LogsHistory) {
                        calls.push(['history', cmd.LogsHistory.container_ids]);
                        return { ok: true, value: { LogsHistory: { entries: [entry('old000000002', 'da execução velha')], next_before: null } } };
                    }
                    if (cmd.LogsExecutionDelete) {
                        calls.push(['delete', cmd.LogsExecutionDelete.container_ids]);
                        executions = executions.filter(e => !cmd.LogsExecutionDelete.container_ids.includes(e.container_ids[0]));
                        return { ok: true, value: { LogsExecutionsDeleted: { deleted: cmd.LogsExecutionDelete.container_ids.length, freed_bytes: 2500 } } };
                    }
                    return { ok: false, error: 'stub' };
                },
                rpc: async (cmd) => {
                    if (cmd.LogsExecutions) return { ok: true, value: { LogsExecutions: executions } };
                    if (cmd.LogsHistory) {
                        calls.push(['live', cmd.LogsHistory.container_ids]);
                        return { ok: true, value: { LogsHistory: { entries: [entry('cur000000001', 'ao vivo atual')], next_before: null } } };
                    }
                    return { ok: false, error: 'stub' };
                } };
            s.selectedServiceId = 'svc_1'; s.serviceTab = 'logs';
            await s.startServiceLogs();
            const live = s.serviceLogLines.map(l => l.line);
            const past = s.serviceLogExecutions.map(r => [r.key, r.outcomeLabel, r.partial]);
            await s.serviceLogExecutionOpen(s.serviceLogExecutions[0]);
            const win = { title: s.serviceLogExecWin.title, lines: s.serviceLogExecWin.lines.map(l => l.line) };
            s.serviceLogToggleAll();
            const selected = [...s.serviceLogSelected];
            await s.serviceLogSelectedDelete();
            return JSON.stringify({ live, past, win, selected, calls,
                after: s.serviceLogExecutions.length, sel_after: s.serviceLogSelected.length });
        })()"#,
    )
    .await;
    let v: serde_json::Value = serde_json::from_str(&out).unwrap();
    assert_eq!(v["live"], serde_json::json!(["ao vivo atual"]));
    assert_eq!(
        v["calls"][0],
        serde_json::json!(["live", ["cur000000001"]]),
        "o painel ao vivo pede só a execução atual"
    );
    assert_eq!(
        v["past"],
        serde_json::json!([
            ["old000000002", "Replaced", false],
            ["bad000000003", "Failed", true]
        ]),
        "a atual não entra na lista; desfecho e parcial aparecem"
    );
    assert_eq!(v["win"]["lines"], serde_json::json!(["da execução velha"]));
    assert!(
        v["win"]["title"].as_str().unwrap().contains("→"),
        "o título diz qual execução é"
    );
    assert_eq!(
        v["calls"][1],
        serde_json::json!(["history", ["old000000002"]])
    );
    assert_eq!(
        v["selected"],
        serde_json::json!(["old000000002", "bad000000003"])
    );
    assert_eq!(
        v["calls"][2],
        serde_json::json!(["delete", ["old000000002", "bad000000003"]]),
        "limpar selecionados = uma chamada em lote"
    );
    assert_eq!(v["after"], 0, "a lista recarrega depois de excluir");
    assert_eq!(v["sel_after"], 0);
    assert_eq!(
        errors(&page).await,
        Vec::<String>::new(),
        "sem erros de JS no console"
    );
}

/// Tela "Em execução": só o que `snapshot.dashboard` traz, com o webhook mascarado até
/// "Mostrar", os pré-deploy checks na ordem e os atalhos de abrir/deploy/parar.
#[tokio::test]
async fn running_screen_lists_running_services() {
    let addr = spawn_static_server().await;
    let (browser, _handler) = launch().await;
    let page = open_page(&browser, addr).await;
    seed_connected(&page).await;

    let seed = r#"(() => {
        const s = Alpine.store('app');
        s.snap.dashboard = [{ project_id: 'prj_1', project_name: 'acme', services: [{
            service_id: 'svc_1', name: 'api', status: 'Running', kind: 'git', kind_label: 'App · Git',
            branch: 'release', repo_url: 'https://github.com/acme/api.git', image: null, engine: null,
            port: 8080, domains: ['api.acme.dev'], webhook: 'https://h/webhook/svc_1/segredo',
            pre_deploy_checks: [{ job_id: 'j1', name: 'migrate' }, { job_id: 'j2', name: 'seed' }],
            warm: { service_id: 'svc_1', warm: false, warming: false, reason: 'nunca aquecido', warmed_at: null } }] }];
        s.view = 'running';
        return 'ok';
    })()"#;
    assert!(
        !eval_str(&page, &format!("(() => {seed})()"))
            .await
            .is_empty()
    );
    assert!(
        visible(&page, "[x-data=\"running\"]").await,
        "tela running visível"
    );

    let text = eval_str(
        &page,
        "document.querySelector('[x-data=\"running\"]').innerText",
    )
    .await;
    for esperado in [
        "acme",
        "api",
        "release",
        "migrate",
        "seed",
        "Deploy",
        "Open service",
        "Open project",
    ] {
        assert!(
            text.contains(esperado),
            "faltou {esperado:?} na tela: {text}"
        );
    }
    // A URL fica no `value` do input (não no innerText): mascarada até "Mostrar".
    let url = eval_str(
        &page,
        r#"document.querySelector('[x-data="running"] .webhook__url').value"#,
    )
    .await;
    assert_eq!(url, "https://h/webhook/svc_1/••••••••");
    assert!(
        !text.contains("segredo"),
        "o token do webhook não pode aparecer: {text}"
    );
    assert_eq!(
        errors(&page).await,
        Vec::<String>::new(),
        "sem erros de JS no console"
    );
}

/// O selo de versão nova acende pelo snapshot, sem ninguém clicar em "Verificar": o campo `update`
/// traz a última consulta do daemon (inclusive a periódica). Um snapshot com o mesmo `checked_at`
/// não reescreve a aba; um com `checked_at` novo, sim.
#[tokio::test]
async fn update_badge_lights_up_from_the_snapshot() {
    let addr = spawn_static_server().await;
    let (browser, _handler) = launch().await;
    let page = open_page(&browser, addr).await;
    seed_connected(&page).await;
    assert!(
        !visible(&page, ".nav-item__badge").await,
        "sem `update` no snapshot o selo fica apagado"
    );

    let applied = eval_str(
        &page,
        &format!(
            r#"(() => {{
                const s = Alpine.store('app');
                const snapshot = {SNAPSHOT_JS};
                snapshot.update = {{ current_version: '0.1.14', latest_version: '0.1.15',
                    is_update_available: true, release_url: 'https://github.com/o/r/releases/tag/v0.1.21',
                    published_at: null, checked_at: '2026-10-27T10:00:00Z' }};
                s.applySnapshot(snapshot);
                return JSON.stringify([s.updateIsAvailable, s.updateLatestVersion, s.updateMessage]);
            }})()"#
        ),
    )
    .await;
    let v: serde_json::Value = serde_json::from_str(&applied).unwrap();
    assert_eq!(v[0], true);
    assert_eq!(v[1], "0.1.15");
    assert_eq!(v[2], "There is a new version: 0.1.15");
    assert!(
        visible(&page, ".nav-item__badge").await,
        "o selo do Settings deveria acender"
    );

    let after = eval_str(
        &page,
        &format!(
            r#"(() => {{
                const s = Alpine.store('app');
                const snapshot = {SNAPSHOT_JS};
                snapshot.update = {{ current_version: '0.1.14', latest_version: '0.1.15',
                    is_update_available: true, release_url: '', published_at: null,
                    checked_at: '2026-10-27T10:00:00Z' }};
                s.updateMessage = 'mensagem da tela';
                s.applySnapshot(snapshot);
                const kept = s.updateMessage;
                snapshot.update = {{ ...snapshot.update, latest_version: '0.1.14',
                    is_update_available: false, checked_at: '2026-10-27T16:00:00Z' }};
                s.applySnapshot(snapshot);
                return JSON.stringify([kept, s.updateIsAvailable]);
            }})()"#
        ),
    )
    .await;
    let v: serde_json::Value = serde_json::from_str(&after).unwrap();
    assert_eq!(
        v[0], "mensagem da tela",
        "mesmo checked_at: a aba não é reescrita"
    );
    assert_eq!(v[1], false, "checked_at novo: a aba segue a consulta nova");

    assert_eq!(
        errors(&page).await,
        Vec::<String>::new(),
        "sem erros de JS no console"
    );
}

/// Abrir Settings já carrega a lista de contas Git (como o botão "Refresh git list"), para a aba
/// Sync não ficar vazia quando a pessoa não passou pela aba Git antes.
#[tokio::test]
async fn opening_settings_loads_the_git_provider_list() {
    let addr = spawn_static_server().await;
    let (browser, _handler) = launch().await;
    let page = open_page(&browser, addr).await;
    seed_connected(&page).await;

    let out = eval_str(
        &page,
        r#"(async () => {
            const s = Alpine.store('app');
            const calls = [];
            s.api = { rpc: async (c) => {
                calls.push(typeof c === 'string' ? c : Object.keys(c)[0]);
                return { ok: true, value: { GitProviders: [{ id: 'gp_1', name: 'GitHub', kind: 'Github' }] } };
            } };
            s.gitProviders = [];
            s.nav('settings');
            await new Promise(r => setTimeout(r, 100));
            return JSON.stringify([calls.includes('GitProviderList'), s.gitProviders.length]);
        })()"#,
    )
    .await;
    let v: serde_json::Value = serde_json::from_str(&out).unwrap();
    assert_eq!(v[0], true, "nav('settings') pede GitProviderList");
    assert_eq!(v[1], 1, "a lista chega ao estado");
}

/// A sincronização do estado com o git (Fases 6 e 7 do plano de estado em git): o aviso do topo, a
/// aba "Sync" do Settings (situação, divergência, commit recusado, removidos, auditoria), o selo
/// "mudança pendente de deploy" e o container órfão em Runtime → Containers. Tudo vem do snapshot.
#[tokio::test]
async fn git_sync_screens_render_from_the_snapshot() {
    let addr = spawn_static_server().await;
    let (browser, _handler) = launch().await;
    let page = open_page(&browser, addr).await;
    seed_connected(&page).await;

    // Sem `state_git` no snapshot (daemon antigo, ou ainda carregando): nada de aviso e nada quebra.
    assert!(
        !eval_str(
            &page,
            "String(Alpine.store('app').stateGitAlertMessage === '')"
        )
        .await
        .is_empty()
    );
    assert_eq!(
        eval_str(&page, "Alpine.store('app').stateGitAlertMessage").await,
        ""
    );

    let seeded = eval_str(
        &page,
        &format!(
            r#"(() => {{
                const s = Alpine.store('app');
                const snapshot = {SNAPSHOT_JS};
                snapshot.state_git = {{
                    mode: 'sync', remote: 'https://github.com/o/estado.git', branch: 'main', provider_id: null,
                    git_available: true, recovery_configured: false,
                    last_commit: {{ sha: 'da3da09aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', at: '2026-11-02T06:28:44Z', subject: 'Atualiza projeto E2E' }},
                    last_push_ok: true, last_push_at: '2026-11-02T06:28:50Z', last_fetch_at: '2026-11-02T06:29:00Z',
                    last_error: null, blocked_by_plaintext: 0, needs_push: false, ahead: 1, behind: 1,
                    paused_reason: 'o histórico divergiu',
                    incoming_rejected: {{ sha: '40c22c1240580bde3cac6512dab507c663335a85', reason: 'traz 1 valor(es) em claro' }},
                    removed_in_git: [{{ id: 'serviço:svc_web', kind: 'serviço', name: 'web', project: 'E2E',
                                       sha: 'da3da09aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', at: '2026-11-02T06:28:44Z' }}],
                    pending_deploy: ['svc_pendente'],
                }};
                snapshot.infra_audit = [
                    {{ definite: false, allowed: false, project: 'E2E', scope: 'projeto', what: 'env PASSWORD_MIN_LENGTH' }},
                    {{ definite: true, allowed: false, project: 'E2E', scope: 'serviço api', what: 'token de webhook sem cifra' }},
                ];
                snapshot.docker_containers = [
                    {{ id: 'a'.repeat(64), name: 'orfao_vivo', image: 'debian', state: 'running', status: 'Up',
                       managed: true, project: null, service: null, removed_in_git: 'web' }},
                    {{ id: 'b'.repeat(64), name: 'servico_vivo', image: 'debian', state: 'running', status: 'Up',
                       managed: true, project: 'E2E', service: 'api', removed_in_git: null }},
                ];
                s.applySnapshot(snapshot);
                return JSON.stringify([s.stateGitAlertMessage, s.stateGitPendingDeploy('svc_pendente'),
                                       s.stateGitPendingDeploy('outro'), s.stateGitAuditFindings.length]);
            }})()"#
        ),
    )
    .await;
    let v: serde_json::Value = serde_json::from_str(&seeded).unwrap();
    assert!(
        v[0].as_str().unwrap().contains("paused"),
        "a pausa tem prioridade no aviso: {}",
        v[0]
    );
    assert_eq!(v[1], true, "serviço com mudança pendente de deploy");
    assert_eq!(v[2], false);
    assert_eq!(v[3], 2, "a auditoria vem no snapshot");
    assert!(
        visible(&page, ".banner--warn").await,
        "o aviso do topo aparece (pausada)"
    );

    // Settings → Sync
    let page_text = eval_str(
        &page,
        r#"(() => {
            const s = Alpine.store('app');
            s.nav('settings');
            s.settingsTab = 'gitsync';
            s.stateGitFormLoad();
            return 'ok';
        })()"#,
    )
    .await;
    assert!(!page_text.is_empty());
    // O Alpine aplica `x-show`/`x-if` num microtask: espera a tela de fato aparecer antes de medir
    // (senão `innerText` de um elemento ainda oculto devolve o texto todo e o teste passa em falso).
    assert!(
        visible(&page, "[x-data=\"settings\"]").await,
        "Settings visível"
    );
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
    let text = eval_str(
        &page,
        "document.querySelector('[x-data=\"settings\"]').innerText",
    )
    .await;
    for esperado in [
        "GIT SYNC",
        "DIVERGED HISTORY",
        "Use the repository's",
        "Use the server's",
        "Resume",
        "REPOSITORY COMMIT REJECTED",
        "REMOVED IN GIT",
        "Dismiss",
        "PLAINTEXT VALUES (2)",
        "env PASSWORD_MIN_LENGTH",
        "Not a secret",
        "da3da09 · Atualiza projeto E2E",
    ] {
        assert!(
            text.contains(esperado),
            "faltou {esperado:?} na aba Sync:\n{text}"
        );
    }
    // O formulário parte do status gravado no daemon.
    assert_eq!(
        eval_str(&page, "Alpine.store('app').stateGitRemote").await,
        "https://github.com/o/estado.git"
    );
    // A certeza (token de webhook) NÃO pode ser liberada: só a suspeita tem o botão.
    let buttons = eval_str(
        &page,
        r#"JSON.stringify([...document.querySelectorAll('[x-data="settings"] button')]
            .filter(b => b.getClientRects().length > 0).map(b => b.innerText.trim()))"#,
    )
    .await;
    let buttons: Vec<String> = serde_json::from_str(&buttons).unwrap();
    assert_eq!(
        buttons
            .iter()
            .filter(|b| b.as_str() == "Not a secret")
            .count(),
        1,
        "só a suspeita tem o botão; botões visíveis: {buttons:?}"
    );

    // Runtime → Containers: o órfão que ainda roda oferece "Stop"; o container de serviço vivo, não.
    eval_str(
        &page,
        "(() => { Alpine.store('app').nav('docker'); return 'ok'; })()",
    )
    .await;
    assert!(
        visible(&page, "[x-data=\"docker\"]").await,
        "Runtime visível"
    );
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
    let rows = eval_str(
        &page,
        "document.querySelector('[x-data=\"docker\"]').innerText",
    )
    .await;
    assert!(
        rows.contains("removed in git (web)"),
        "dono do órfão:\n{rows}"
    );
    let docker_buttons = eval_str(
        &page,
        r#"JSON.stringify([...document.querySelectorAll('[x-data="docker"] button')]
            .filter(b => b.getClientRects().length > 0).map(b => b.innerText.trim()))"#,
    )
    .await;
    let docker_buttons: Vec<String> = serde_json::from_str(&docker_buttons).unwrap();
    assert_eq!(
        docker_buttons
            .iter()
            .filter(|b| b.as_str() == "Stop")
            .count(),
        1,
        "só o órfão tem o botão Stop; botões visíveis: {docker_buttons:?}"
    );

    assert_eq!(
        errors(&page).await,
        Vec::<String>::new(),
        "sem erros de JS no console"
    );
}

/// Settings → Backups (docs/plano-backup-de-dados-para-s3.md, Fase 1): abrir Settings lê o destino S3
/// gravado, o formulário o recebe **sem** chave secreta, e salvar manda a chave só quando digitada.
#[tokio::test]
async fn backups_tab_loads_and_saves_the_s3_destination() {
    let addr = spawn_static_server().await;
    let (browser, _handler) = launch().await;
    let page = open_page(&browser, addr).await;
    seed_connected(&page).await;

    let out = eval_str(
        &page,
        r#"(async () => {
            const s = Alpine.store('app');
            const sent = [];
            const view = { configured: true, endpoint: 'http://rp_s3:9000', region: 'us-east-1', bucket: 'bk',
                           prefix: 'rustploy', path_style: true, access_key: 'AK', secret_set: true,
                           recovery_configured: false };
            s.api = { rpc: async (c) => {
                const name = typeof c === 'string' ? c : Object.keys(c)[0];
                sent.push(c);
                if (name === 'BackupDestinationGet' || name === 'BackupDestinationSet')
                    return { ok: true, value: { BackupDestination: view } };
                return { ok: true, value: 'Ok' };
            } };
            s.api.rpcChecked = s.api.rpc;
            s.nav('settings');
            await new Promise(r => setTimeout(r, 100));
            const loaded = [s.backupDestBucket, s.backupDestAccessKey, s.backupDestSecretSet,
                            s.backupDestRecoveryMissing, s.backupDestSecretKey];
            // salvar sem digitar a chave: manda `secret_key: null` (mantém a gravada)
            await s.backupDestinationSave();
            const semChave = sent.find(c => c.BackupDestinationSet).BackupDestinationSet.destination.secret_key;
            // digitando a chave: ela vai, e some do campo depois
            s.backupDestSecretKey = 'nova-chave';
            await s.backupDestinationSave();
            const sets = sent.filter(c => c.BackupDestinationSet);
            const comChave = sets[1].BackupDestinationSet.destination.secret_key;
            return JSON.stringify({ loaded, semChave, comChave, depois: s.backupDestSecretKey });
        })()"#,
    )
    .await;
    let v: serde_json::Value = serde_json::from_str(&out).unwrap();
    assert_eq!(v["loaded"], serde_json::json!(["bk", "AK", true, true, ""]));
    assert_eq!(
        v["semChave"],
        serde_json::Value::Null,
        "sem digitar, mantém a chave gravada"
    );
    assert_eq!(v["comChave"], "nova-chave");
    assert_eq!(v["depois"], "", "a chave digitada não fica no formulário");
}

/// Aba Dados → "Backup no S3" (docs/plano-backup-de-dados-para-s3.md, Fase 2): abrir a aba lista os
/// backups e a última operação; "Fazer backup agora" e "Restaurar" mandam o comando certo (restaurar com
/// `confirm: true`); sem destino configurado a tela mostra o motivo e esconde o botão.
#[tokio::test]
async fn data_tab_shows_s3_backups_and_sends_the_commands() {
    let addr = spawn_static_server().await;
    let (browser, _handler) = launch().await;
    let page = open_page(&browser, addr).await;
    seed_connected(&page).await;

    let out = eval_str(
        &page,
        r#"(async () => {
            const s = Alpine.store('app');
            s.view = 'service';
            s.selectedServiceId = 'svc_1';
            s.serviceTab = 'dados';
            s.serviceLoading = false;
            s.serviceDeployments = [];
            s.serviceDetail = { id: 'svc_1', status: 'Running', live_container_id: 'x',
                spec: { name: 'db', port: 5432, replicas: 1, project_id: 'prj_1', env_vars: [], domains: [],
                    source: { Registry: { image: 'busybox' } },
                    healthcheck: { kind: 'None', interval_secs: 5, timeout_secs: 3, retries: 10, start_period_secs: 5 } } };
            const sent = [];
            let blocked = null;
            const lista = () => ({ ServiceBackups: {
                entries: [{ key: 'p/prj_1/svc_1/20261111-100000.rpdata.age', last_modified: '2026-11-11T10:00:00Z', size_bytes: 3008554 }],
                last_run: { op: 'backup', state: 'ok', started_at: 'a', finished_at: '2026-11-11T10:00:05Z', size_bytes: 3008554, key: 'k', error: null, checks: [] },
                blocked, list_error: null } });
            const rpc = async (c) => {
                const name = typeof c === 'string' ? c : Object.keys(c)[0];
                sent.push(c);
                if (name === 'ServiceDataPlan') return { ok: true, value: { ServiceDataPlan: { service_name: 'db', parts: [], running: true, blocked: null, notes: [], encrypt_default: true } } };
                if (name === 'ServiceBackupList') return { ok: true, value: lista() };
                return { ok: true, value: 'Ok' };
            };
            s.api = { rpc, rpcChecked: rpc };
            const el = document.querySelector('[x-data="serviceDetail"]');
            const d = Alpine.$data(el);
            await d.loadData();
            await new Promise(r => setTimeout(r, 100));
            const texto = el.innerText;
            const listado = [d.backups.entries.length, d.backupRunLabel.includes('3 MB'), texto.includes('Fazer backup agora') || texto.includes('Back up now')];
            // restaurar manda confirm:true (o confirm do navegador é aceito aqui)
            window.confirm = () => true;
            await d.backupNow();
            await d.restoreBackup(d.backups.entries[0]);
            const restore = sent.find(c => c.ServiceBackupRestore).ServiceBackupRestore;
            const now = sent.find(c => c.ServiceBackupNow).ServiceBackupNow;
            // sem destino: o motivo aparece e o botão some
            blocked = 'nenhum destino S3 configurado';
            await d.loadBackups();
            await new Promise(r => setTimeout(r, 100));
            const semDestino = [el.innerText.includes('nenhum destino S3 configurado'),
                !!Array.from(el.querySelectorAll('button')).find(b => /Fazer backup agora|Back up now/.test(b.innerText) && b.offsetParent !== null)];
            return JSON.stringify({ listado, restore, now, semDestino });
        })()"#,
    )
    .await;
    let v: serde_json::Value = serde_json::from_str(&out).unwrap();
    assert_eq!(v["listado"], serde_json::json!([1, true, true]), "{out}");
    assert_eq!(v["restore"]["confirm"], true, "{out}");
    assert_eq!(v["restore"]["service_id"], "svc_1", "{out}");
    assert_eq!(v["now"]["service_id"], "svc_1", "{out}");
    assert_eq!(v["semDestino"], serde_json::json!([true, false]), "{out}");
}

/// Aba Dados → política do backup automático (Fase 3): o formulário nasce da política gravada (semanal,
/// 04:30 UTC), editar e salvar manda o `Recurrence` certo para as três frequências, e o repoll não apaga
/// o que a pessoa está digitando.
#[tokio::test]
async fn data_tab_backup_policy_form_roundtrips() {
    let addr = spawn_static_server().await;
    let (browser, _handler) = launch().await;
    let page = open_page(&browser, addr).await;
    seed_connected(&page).await;

    let out = eval_str(
        &page,
        r#"(async () => {
            const s = Alpine.store('app');
            s.view = 'service'; s.selectedServiceId = 'svc_1'; s.serviceTab = 'dados';
            s.serviceLoading = false; s.serviceDeployments = [];
            s.serviceDetail = { id: 'svc_1', status: 'Running', live_container_id: 'x',
                spec: { name: 'db', port: 5432, replicas: 1, project_id: 'prj_1', env_vars: [], domains: [],
                    source: { Registry: { image: 'busybox' } },
                    healthcheck: { kind: 'None', interval_secs: 5, timeout_secs: 3, retries: 10, start_period_secs: 5 } } };
            const sent = [];
            const policy = { enabled: true, recurrence: { Weekly: { weekday: 2, hour: 4, minute: 30 } }, keep: 5, stop: false };
            const lista = (p) => ({ ServiceBackups: { entries: [], last_run: null, blocked: null, list_error: null,
                policy: p, next_run_at: p && p.enabled ? '2026-11-12T04:30:00+00:00' : null } });
            const rpc = async (c) => {
                const name = typeof c === 'string' ? c : Object.keys(c)[0];
                sent.push(c);
                if (name === 'ServiceDataPlan') return { ok: true, value: { ServiceDataPlan: { service_name: 'db', parts: [], running: false, blocked: null, notes: [], encrypt_default: true } } };
                if (name === 'ServiceBackupList') return { ok: true, value: lista(policy) };
                if (name === 'ServiceBackupPolicySet') return { ok: true, value: lista(c.ServiceBackupPolicySet.policy) };
                return { ok: true, value: 'Ok' };
            };
            s.api = { rpc, rpcChecked: rpc };
            const el = document.querySelector('[x-data="serviceDetail"]');
            const d = Alpine.$data(el);
            await d.loadData();
            await new Promise(r => setTimeout(r, 100));
            const f = d.backupForm;
            const lido = [f.enabled, f.kind, f.weekday, f.time, f.keep, f.stop];
            // o repoll (loadBackups sem preencher) não apaga uma edição em andamento
            d.backupForm.keep = 9;
            await d.loadBackups(false);
            const mantido = d.backupForm.keep;
            const enviar = async (patch) => {
                Object.assign(d.backupForm, patch);
                await d.saveBackupPolicy();
                return sent.filter(c => c.ServiceBackupPolicySet).pop().ServiceBackupPolicySet.policy;
            };
            const diario = await enviar({ kind: 'daily', time: '03:15', keep: 7, stop: true });
            const horas = await enviar({ kind: 'interval', hours: 6 });
            const semanal = await enviar({ kind: 'weekly', weekday: 6, time: '23:00' });
            const desligado = await enviar({ enabled: false });
            return JSON.stringify({ lido, mantido, diario, horas, semanal, desligado: desligado.enabled,
                proximo: el.innerText.includes('2026-11-12') });
        })()"#,
    )
    .await;
    let v: serde_json::Value = serde_json::from_str(&out).unwrap();
    assert_eq!(
        v["lido"],
        serde_json::json!([true, "weekly", 2, "04:30", 5, false]),
        "{out}"
    );
    assert_eq!(v["mantido"], 9, "{out}");
    assert_eq!(
        v["diario"]["recurrence"],
        serde_json::json!({"Daily": {"hour": 3, "minute": 15}}),
        "{out}"
    );
    assert_eq!(v["diario"]["keep"], 7);
    assert_eq!(
        v["horas"]["recurrence"],
        serde_json::json!({"IntervalHours": 6}),
        "{out}"
    );
    assert_eq!(
        v["semanal"]["recurrence"],
        serde_json::json!({"Weekly": {"weekday": 6, "hour": 23, "minute": 0}}),
        "{out}"
    );
    assert_eq!(v["desligado"], false, "{out}");
}

/// Settings → Recuperar (Fase 4): o formulário manda o repositório, o token e a chave; **a chave e o token
/// somem dos campos** deem certo ou não; o resumo mostra cada serviço com o backup achado; confirmar manda
/// `ServerRecoverRun` e cancelar volta ao começo.
#[tokio::test]
async fn recover_tab_sends_the_fields_and_forgets_the_secrets() {
    let addr = spawn_static_server().await;
    let (browser, _handler) = launch().await;
    let page = open_page(&browser, addr).await;
    seed_connected(&page).await;

    let out = eval_str(
        &page,
        r#"(async () => {
            const s = Alpine.store('app');
            s.view = 'settings'; s.settingsTab = 'recover';
            const sent = [];
            let fail = true;
            const ready = { phase: 'ready', projects: 1, destination_configured: true, destination_error: null,
                services: [
                  { service_id: 'svc_db', name: 'banco', project: 'loja', kind: 'database', latest_backup: '2026-11-11T13:44:06Z', step: 'pending', error: null },
                  { service_id: 'svc_web', name: 'web', project: 'loja', kind: 'volume', latest_backup: null, step: 'pending', error: null } ] };
            const rpc = async (c) => {
                const name = typeof c === 'string' ? c : Object.keys(c)[0];
                sent.push(c);
                if (name === 'ServerRecoverStatus') return { ok: true, value: { ServerRecover: { phase: 'idle', projects: 0, services: [] } } };
                if (name === 'ServerRecoverStart') return fail ? { ok: false, error: 'token inválido' } : { ok: true, value: { ServerRecover: ready } };
                if (name === 'ServerRecoverCancel') return { ok: true, value: { ServerRecover: { phase: 'idle', projects: 0, services: [], message: 'cancelada' } } };
                return { ok: true, value: 'Ok' };
            };
            s.api = { rpc, rpcChecked: rpc };
            window.confirm = () => true;
            await s.recoverStatusLoad();
            s.recoverRemote = ' https://github.com/org/estado.git ';
            s.recoverToken = 'ghp_segredo';
            s.recoverKey = 'AGE-SECRET-KEY-1ABC';
            // 1ª tentativa falha: mesmo assim os segredos saem dos campos
            await s.recoverStart();
            const aposErro = [s.recoverKey, s.recoverToken, s.recoverRemote.trim()];
            // 2ª dá certo
            fail = false;
            s.recoverKey = 'AGE-SECRET-KEY-1ABC'; s.recoverToken = 'tok';
            await s.recoverStart();
            await new Promise(r => setTimeout(r, 100));
            const start = sent.filter(c => c.ServerRecoverStart).pop().ServerRecoverStart;
            const texto = document.body.innerText;
            const resumo = [s.recoverInfo.phase, texto.includes('banco'), texto.includes('sem backup') || texto.includes('no backup')];
            await s.recoverRun();
            const rodou = sent.includes('ServerRecoverRun');
            await s.recoverCancel();
            return JSON.stringify({ aposErro, start, resumo, rodou, fase: s.recoverInfo.phase,
                chaveNoEstado: JSON.stringify(s).includes('AGE-SECRET-KEY') });
        })()"#,
    )
    .await;
    let v: serde_json::Value = serde_json::from_str(&out).unwrap();
    assert_eq!(
        v["aposErro"],
        serde_json::json!(["", "", "https://github.com/org/estado.git"]),
        "{out}"
    );
    assert_eq!(
        v["start"]["remote"], "https://github.com/org/estado.git",
        "{out}"
    );
    assert_eq!(v["start"]["recovery_key"], "AGE-SECRET-KEY-1ABC", "{out}");
    assert_eq!(v["start"]["token"], "tok");
    assert_eq!(v["start"]["branch"], serde_json::Value::Null);
    assert_eq!(
        v["resumo"],
        serde_json::json!(["ready", true, true]),
        "{out}"
    );
    assert_eq!(v["rodou"], true, "{out}");
    assert_eq!(v["fase"], "idle", "{out}");
    assert_eq!(
        v["chaveNoEstado"], false,
        "a chave não pode ficar no estado do app: {out}"
    );
}

/// Portas TCP do host na aba Domains (`docs/plano-multiplas-portas-tcp.md`): a lista nova, o legado
/// (`host_port` sozinho) virando a primeira linha, adicionar com a porta do container e o rótulo,
/// apagar, e as sugestões preenchendo o formulário. A webui nunca tinha tido editor de porta TCP.
#[tokio::test]
async fn tcp_ports_editor_lists_adds_deletes_and_suggests() {
    let addr = spawn_static_server().await;
    let (browser, _handler) = launch().await;
    let page = open_page(&browser, addr).await;
    seed_connected(&page).await;

    page.evaluate(
        r#"(() => {
            const s = Alpine.store('app');
            s.view = 'service';
            s.selectedServiceId = 'svc_s3';
            s.serviceTab = 'domains';
            s.serviceLoading = false;
            s.serviceDeployments = [];
            s.serviceDetail = {
                id: 'svc_s3', status: 'Running', live_container_id: null,
                spec: { name: 's3', port: 9000, replicas: 1, project_id: 'prj_1', product: 'rustfs',
                    host_port: 20002, env_vars: [], domains: [],
                    source: { Compose: { content: 'services:\n  rp_s3:\n    image: rustfs/rustfs\n' } },
                    healthcheck: { kind: 'None', interval_secs: 5, timeout_secs: 3, retries: 10, start_period_secs: 5 } },
            };
            window.__saved = [];
            s.saveServiceSpec = async (spec, msg) => { window.__saved.push({ spec, msg }); return { ok: true }; };
            window.__toasts = [];
            s.toastError = (m) => window.__toasts.push(m);
            s.api.rpcChecked = async (cmd) => cmd.ServicePortSuggestions
                ? { ok: true, value: { ServicePortSuggestions: [
                    { port: 9001, label: 'console', sources: ['listening', 'product'], internal: false },
                ] } }
                : { ok: false, error: 'inesperado' };
        })()"#,
    )
    .await
    .expect("abre a aba Domains do s3");

    let d = "Alpine.$data(document.querySelector('[x-data=\"serviceDetail\"]'))";

    // O legado (`host_port` sozinho) aparece como uma porta para a porta do serviço.
    assert_eq!(
        eval_str(&page, &format!("(() => JSON.stringify({d}.tcpPorts))()")).await,
        r#"[{"hostPort":20002,"containerPort":9000,"label":""}]"#
    );
    assert!(
        visible(
            &page,
            "[x-data=\"serviceDetail\"] input[x-model=\"newTcpContainer\"]"
        )
        .await,
        "a aba Domains deveria mostrar o formulário de porta TCP"
    );
    // Nada espremido: cada controle do bloco de portas tem altura de verdade (no app desktop, o bloco
    // novo ficou sem rolagem e cortado; aqui o `.env` cresce com o conteúdo e a página rola).
    let heights = eval_str(
        &page,
        r#"(() => JSON.stringify(['input[x-model="newTcpHost"]', 'input[x-model="newTcpContainer"]',
            'input[x-model="newTcpLabel"]', 'button[\\@click="addTcpPort()"]', 'button[\\@click="suggestPorts()"]']
            .map((sel) => Math.round(document.querySelector('[x-data="serviceDetail"] ' + sel).getBoundingClientRect().height))))()"#,
    )
    .await;
    let heights: Vec<u32> = serde_json::from_str(&heights).unwrap();
    assert!(
        heights.iter().all(|h| *h >= 20),
        "controle espremido: alturas {heights:?}"
    );

    // Sugestões: o botão vem com nome e "escutando agora"; clicar preenche porta e rótulo.
    let picked = eval_str(
        &page,
        &format!("(async () => {{ const d = {d}; await d.suggestPorts(); d.pickSuggestion(d.portSuggestions[0]); return JSON.stringify({{ text: d.portSuggestions[0].text, port: d.newTcpContainer, label: d.newTcpLabel }}); }})()"),
    )
    .await;
    let p: serde_json::Value = serde_json::from_str(&picked).unwrap();
    assert_eq!(p["text"], "9001 console (listening now)");
    assert_eq!(p["port"], "9001");
    assert_eq!(p["label"], "console");

    // Adicionar (host vazio = automática): o legado vira lista, `host_port` vai nulo, e a nova entra.
    let added = eval_str(
        &page,
        &format!("(async () => {{ const d = {d}; await d.addTcpPort(); const x = window.__saved[0]; return JSON.stringify({{ msg: x.msg, host_port: x.spec.host_port, tcp: x.spec.tcp_ports, cleared: d.newTcpContainer === '' && d.newTcpLabel === '' }}); }})()"),
    )
    .await;
    let a: serde_json::Value = serde_json::from_str(&added).unwrap();
    assert_eq!(a["msg"], "port added");
    assert!(
        a["host_port"].is_null(),
        "o espelho é do daemon: o cliente manda null"
    );
    assert_eq!(
        a["tcp"],
        serde_json::json!([
            { "host_port": 20002 },
            { "host_port": 0, "container_port": 9001, "label": "console" }
        ])
    );
    assert_eq!(a["cleared"], true, "o formulário zera depois de salvar");

    // Porta inválida: só avisa, não salva.
    let invalid = eval_str(
        &page,
        &format!("(async () => {{ const d = {d}; d.newTcpHost = '70000'; await d.addTcpPort(); d.newTcpHost = ''; return JSON.stringify({{ saved: window.__saved.length, toasts: window.__toasts.length }}); }})()"),
    )
    .await;
    assert_eq!(invalid, r#"{"saved":1,"toasts":1}"#);

    // Apagar: a lista volta sem a porta, também com `host_port` nulo.
    let deleted = eval_str(
        &page,
        &format!("(async () => {{ const s = Alpine.store('app'); s.serviceDetail.spec.tcp_ports = [{{ host_port: 20002 }}, {{ host_port: 20003, container_port: 9001, label: 'console' }}]; s.serviceDetail.spec.host_port = 20002; await {d}.deleteTcpPort(20002); const x = window.__saved[window.__saved.length - 1]; return JSON.stringify({{ msg: x.msg, host_port: x.spec.host_port, tcp: x.spec.tcp_ports }}); }})()"),
    )
    .await;
    let del: serde_json::Value = serde_json::from_str(&deleted).unwrap();
    assert_eq!(del["msg"], "port removed");
    assert!(del["host_port"].is_null());
    assert_eq!(
        del["tcp"],
        serde_json::json!([{ "host_port": 20003, "container_port": 9001, "label": "console" }])
    );

    // Tela de Ingress: uma linha por porta, com a porta do container e o rótulo.
    let rows = eval_str(
        &page,
        r#"(async () => {
            const { hostPortRows } = await import('./format.js');
            const spec = { name: 's3', project_id: 'prj_1', port: 9000,
                tcp_ports: [{ host_port: 20003, container_port: 9001, label: 'console' }, { host_port: 20002 }] };
            const legado = { name: 'db', project_id: 'prj_1', port: 5432, host_port: 20000 };
            return JSON.stringify(hostPortRows([{ svc: { id: 'a', spec }, proj: 'p' }, { svc: { id: 'b', spec: legado }, proj: 'p' }])
                .map((r) => [r.hostPort, r.containerPort]));
        })()"#,
    )
    .await;
    assert_eq!(
        rows,
        r#"[[20000,5432],[20002,9000],[20003,"9001 (console)"]]"#
    );

    assert_eq!(
        errors(&page).await,
        Vec::<String>::new(),
        "sem erros de JS no console"
    );
}