rustploy 0.1.18

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
//! 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,
        "isso não é um token de conexão — cole o token de conexão inteiro (base64 de host:porta::token), não só o token da API"
    );
    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"
    );
}

/// 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', db_kind: '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":["Informe o nome do serviço"]}"#,
        "mesmo nome não salva; vazio só avisa"
    );

    // Nome novo: manda o spec inteiro (fonte, porta, db_kind) 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.db_kind, 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"], "serviço renomeado");
    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("próximo 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', db_kind: '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 servidor compartilhado");

    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', db_kind: '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=\"Ações do job\"]').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#"["▶ Rodar agora","◐ Aquecer","‖ Pausar","✎ Editar","✕ Remover"]"#,
        "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('Aquecer')).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 já está aquecido"),
        "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('Reconstruir')).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("reconstrução iniciada"),
        "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#"["■ Cancelar execução","◐ Aquecer","↻ Reconstruir (sem cache)","≡ Ver logs","‖ Pausar","✎ Editar","✕ Remover"]"#
    );

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

/// Settings → Infra as Code, no mesmo fluxo do app desktop: exportar BAIXA um
/// `.zip` com `rustploy.yml` + `rustploy.vars.toml`, escolher um `.zip` valida
/// (exatamente um .yml e um .toml na raiz) e preenche os campos, e importar
/// confirma antes de aplicar e mostra o prune (verbo `Deleted` nas ações).
#[tokio::test]
async fn iac_zip_export_import() {
    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.__confirms = [];
            window.confirm = (m) => { window.__confirms.push(m); return true; };
            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 === 'ManifestExportAll'
                    ? { ok: true, value: { ManifestBundle: { yaml: 'projects: []', dotenv: '# vars' } } }
                    : { ok: false, error: 'stub' },
                rpc: async (cmd) => { window.__import = cmd.ManifestImport;
                    return { ok: true, value: window.__importReply }; } };
            s.refreshNow = async () => {};
            s.view = 'settings'; s.settingsTab = 'iac';
            return 'ok';
        })()"#,
    )
    .await;
    assert!(
        visible(&page, "input[type=file][accept*='zip']").await,
        "a aba IaC tem o seletor de .zip"
    );
    // O botão nativo do seletor de arquivo segue o tema escuro (não o branco do navegador).
    assert_eq!(
        eval_str(
            &page,
            r#"getComputedStyle(document.querySelector("input[type=file][accept*='zip']"), '::file-selector-button').backgroundColor"#
        )
        .await,
        "rgb(33, 38, 45)",
        "botão do seletor de arquivo usa a cor do tema"
    );

    // Exportar: um download rustploy-infra.zip cujo conteúdo é o par yml/toml.
    let exported = eval_str(
        &page,
        r#"(async () => {
            await Alpine.store('app').manifestExport();
            const d = window.__downloads[0];
            const { readManifestZip } = await import('/zip.js');
            const blob = await (await fetch(d.href)).blob();
            const r = await readManifestZip(blob);
            return JSON.stringify({ name: d.name, ok: r.ok, yaml: r.yaml, toml: r.toml,
                msg: Alpine.store('app').manifestExportMessage });
        })()"#,
    )
    .await;
    assert_eq!(
        exported,
        r##"{"name":"rustploy-infra.zip","ok":true,"yaml":"projects: []","toml":"# vars","msg":"baixado como rustploy-infra.zip"}"##
    );

    // Escolher um zip inválido (arquivo sobrando) é recusado; um válido preenche os campos.
    let picked = eval_str(
        &page,
        r#"(async () => {
            const s = Alpine.store('app');
            const { buildManifestZip } = await import('/zip.js');
            const good = new File([buildManifestZip('a: 1', 'b = 2')], 'infra.zip');
            await s.manifestPickZip({ target: { files: [new File(['isto nao e um zip'], 'x.zip')], value: '' } });
            const bad = s.manifestImportMessage;
            await s.manifestPickZip({ target: { files: [good], value: '' } });
            return JSON.stringify({ bad, yaml: s.manifestImportYaml, toml: s.manifestImportDotenv, zip: s.manifestZipName });
        })()"#,
    )
    .await;
    assert_eq!(
        picked,
        r##"{"bad":"zip inválido: não achei o fim do arquivo (não é um .zip?)","yaml":"a: 1","toml":"b = 2","zip":"infra.zip"}"##
    );

    // Importar com prune: confirma antes, manda o pedido certo e mostra o que foi removido.
    let imported = eval_str(
        &page,
        r#"(async () => {
            const s = Alpine.store('app');
            window.__importReply = { ManifestReport: { deployed: [],
                actions: [{ kind: 'Service', name: 'loja/web', action: 'Updated' },
                          { kind: 'Service', name: 'loja/velho', action: 'Deleted' }] } };
            s.manifestPrune = true; s.manifestDeploy = true;
            await s.manifestImport();
            return JSON.stringify({ req: window.__import, confirm: window.__confirms[0],
                lines: s.manifestReportLines, msg: s.manifestImportMessage });
        })()"#,
    )
    .await;
    let imported: serde_json::Value = serde_json::from_str(&imported).expect("json");
    assert_eq!(
        imported["req"],
        serde_json::json!({"yaml":"a: 1","dotenv":"b = 2","prune":true,"deploy":true})
    );
    let confirm = imported["confirm"].as_str().unwrap();
    assert!(
        confirm.contains("Do zip infra.zip") && confirm.contains("prune): SIM"),
        "{confirm}"
    );
    assert_eq!(
        imported["lines"],
        serde_json::json!([
            "[Updated] Service loja/web",
            "[Deleted] Service loja/velho",
            "removidos (prune): loja/velho",
            "deploy ligado — nada mudou para disparar"
        ])
    );
    assert_eq!(imported["msg"], "import concluído ✓");

    // Variável sem valor: nada é aplicado e a lista aparece.
    let missing = eval_str(
        &page,
        r#"(async () => {
            const s = Alpine.store('app');
            window.__importReply = { MissingEnvVars: ['loja/web: APP_PORT'] };
            await s.manifestImport();
            return JSON.stringify({ has: s.manifestHasMissing, vars: s.manifestMissingVars, msg: s.manifestImportMessage });
        })()"#,
    )
    .await;
    assert_eq!(
        missing,
        r##"{"has":true,"vars":"loja/web: APP_PORT","msg":"faltam variáveis — nada foi aplicado"}"##
    );

    // Cancelar na confirmação não manda nada.
    let cancelled = eval_str(
        &page,
        r#"(async () => {
            const s = Alpine.store('app');
            window.confirm = () => false; window.__import = null;
            await s.manifestImport();
            return JSON.stringify({ sent: window.__import, msg: s.manifestImportMessage });
        })()"#,
    )
    .await;
    assert_eq!(cancelled, r##"{"sent":null,"msg":"cancelado"}"##);

    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",
        "Abrir serviço",
        "Abrir projeto",
    ] {
        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], "Há uma versão nova: 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"
    );
}