rustploy 0.1.0

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
// app.js — único <script type="module"> carregado por index.html. Orquestra
// a ordem de boot do Alpine "na mão" (em vez do CDN clássico com `defer`):
// um `<script defer>` do Alpine e módulos ES separados entram na mesma fila
// de execução em ordem, mas plugins/CDNs alternativos podem correr fora de
// ordem — e um `Alpine.store`/`Alpine.data` registrado DEPOIS que o Alpine já
// disparou `alpine:init` nunca é visto (x-show/x-data leem `undefined` e a
// tela fica em branco). Aqui a ordem é garantida pelos próprios `import`
// (sempre resolvidos antes do corpo do módulo que os declara):
//   1. screens/*.js rodam primeiro — só REGISTRAM listeners de `alpine:init`.
//   2. Alpine é importado como módulo (não via `<script>` solto).
//   3. este módulo registra o `Alpine.store('app', …)` (a "ctx" global).
//   4. só então `Alpine.start()` — dispara `alpine:init`, todos os
//      listeners acima já registrados.
import "./screens/login.js";
import "./screens/dashboard.js";
import "./screens/deploy_engine.js";
import "./screens/monitoring.js";
import "./screens/ingress.js";
import "./screens/docker.js";
import "./screens/schedules.js";
import "./screens/settings.js";
import "./screens/projects.js";
import "./screens/project_detail.js";
import "./screens/new_service.js";
import "./screens/service_detail.js";
import Alpine from "https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/module.esm.js";
import { Api } from "./net/api.js";
import { openStream } from "./net/sse.js";
import { registerDirectives } from "./directives.js";
import {
  fmtUptime,
  fmtBytes,
  stripAnsi,
  oauthRedirectUri,
  timeHms,
  dateDmHms,
  dateDmHm,
  parseDotenv,
  dotenvFromVars,
  dockerCleanupLastRunSummary,
  shortReason,
  hmJoin,
  hmSplit,
} from "./fmt.js";

window.Alpine = Alpine;
registerDirectives(Alpine);

const PREFS_KEY = "rustploy.prefs";

function loadPrefs() {
  try {
    return JSON.parse(localStorage.getItem(PREFS_KEY) || "{}");
  } catch {
    return {};
  }
}

function savePrefs(p) {
  localStorage.setItem(PREFS_KEY, JSON.stringify(p));
}

document.addEventListener("alpine:init", () => {
  const prefs = loadPrefs();

  Alpine.store("app", {
    // ── Sessão / navegação (≈ ctx.screen/ctx.view do glacier) ────────────
    screen: "login",
    view: "deployments",
    connected: false,
    statusLine: "pronto para conectar",
    error: "",

    // ── Formulário de login ───────────────────────────────────────────
    // Sem campo de servidor: a webui é sempre servida pelo próprio daemon
    // (ver net/api.js), então o servidor é a própria origem da página.
    token: prefs.rememberToken && prefs.token ? prefs.token : "",
    rememberToken: !!prefs.rememberToken,

    // ── Sessão ativa ─────────────────────────────────────────────────
    api: null,
    stream: null,
    search: "",

    // ── Dados do snapshot (≈ State.snap) ────────────────────────────
    snap: null,
    dataLoading: true,
    daemonVersion: "",
    daemonUptime: "…",
    servicesLabel: "…",
    deploymentsMsg: "",

    // ── Eventos ao vivo do bus (≈ State.metrics_by_id / ctx.sys_*) ─────
    // Só chegam por /api/events kind="bus" — o snapshot periódico (2s) não
    // carrega métricas por container nem do host (ver onStreamEvent).
    metricsById: {}, // service_id -> ContainerMetricsPoint
    sysCpu: "—",
    sysMem: "—",
    sysDisk: "—",
    sysLoad: "—",

    // ── Docker / Registry (aba Docker) ──────────────────────────────────
    dockerTab: "containers",
    onlyUsedImages: false,
    onlyUsedVolumes: false,
    onlyUsedNetworks: false,
    pruneAllImages: false,
    pruneAllVolumes: false,
    registrySelectedRepo: "",
    registryTags: [],
    registryTagsLoading: false,
    registryTokens: [],

    // ── Schedules (jobs one-shot) ────────────────────────────────────────
    jobsById: {}, // id -> Job cru (porta de State.jobs_by_id, precisa do
    // record completo pra reenviar em JobUpdate — só `enabled` muda)
    jobLogLines: [],
    jobLogStream: null,
    jobsInflight: {}, // id -> true entre o click em "Rodar agora" e o
    // refreshNow() que segue (trava double-click durante o round-trip da
    // RPC — depois disso o botão passa a refletir `running` do snapshot).

    // Wizard "novo job" (3 passos: projeto → serviço gatilho → form) — mora
    // no store (não num componente de tela) porque duas entradas abrem o
    // MESMO wizard: a tela global "Schedules" e a aba "Jobs" do projeto
    // (equivalente ao new_job_window do cliente iced, aberto por ambos
    // handlers/jobs.luau::open_new_job_window e a aba do projeto). Modal
    // renderizado uma vez em index.html, fora do escopo de qualquer tela.
    showNewJob: false,
    njobStep: "pick_project", // "pick_project" | "pick_service" | "form"
    // Modo edição: aberto por openEditJob(id) em vez do fluxo normal — pula
    // pro passo "form" (project_id/trigger_service_id não são editáveis via
    // JobUpdate, então não há passos 1/2). `null` = criando um job novo.
    njobEditId: null,
    njobEnabled: true,
    njobProjectId: "",
    njobProjectName: "",
    njobServiceId: "",
    njobServiceName: "",
    njobName: "",
    njobCompose: "",
    // Fonte do compose: "compose" (colado, default) | "git" (clona um repo a
    // cada execução, mesmo picker conta→repo→branch da aba Git de serviço —
    // ver njobSetSourceTab/njobGitProviderPick/njobGitRepoPick).
    njobSourceTab: "compose",
    njobGitProviderId: "",
    njobGitProviders: [],
    njobGitRepos: [],
    njobGitRepoFullName: "",
    njobGitBranches: [],
    njobGitBranch: "",
    njobComposePath: "docker-compose.yml",
    njobGitMsg: "",
    njobMainService: "",
    // Env vars próprias do job — maior precedência (por cima de projeto +
    // serviço gatilho). Blob .env colado, parseado em njobCreate.
    njobEnvText: "",
    njobKind: "manual", // "manual" | "interval" | "daily" | "weekly"
    njobHours: "6",
    // Uma chave só, "HH:MM": quem edita agora é o <input type="time">.
    // hmJoin/hmSplit fazem a ponte com o {hour, minute} do daemon.
    njobTime: "03:00",
    njobWeekday: "0",
    njobErr: "",
    njobSubmitting: false,

    // Modal de logs ao vivo de uma execução de job — mesma razão do wizard
    // acima (aberto tanto da tela Schedules quanto da aba Jobs do projeto).
    jobLogsFor: null,

    // ── Settings (Web Server / Git / Infra as Code) ─────────────────────
    settingsTab: "web",
    ssPublicBase: "",
    ssEmail: "",
    ssRegistryDomain: "",
    settingsMsg: "",
    gitProviders: [],
    gpKind: "gitea", // "gitea" | "github"
    gpMode: "oauth", // "oauth" | "pat"
    gpName: "",
    gpBaseUrl: "",
    gpClientId: "",
    gpClientSecret: "",
    gpPat: "",
    gpMsg: "",
    gpOauthUrl: "",
    iacYaml: "",
    iacDotenv: "",
    iacHasExport: false,
    iacExportMsg: "",
    iacImportYaml: "",
    iacImportDotenv: "",
    iacPrune: false,
    iacDeploy: false,
    iacHasMissing: false,
    iacMissingVars: "",
    iacHasReport: false,
    iacReportLines: [],
    iacImportMsg: "",

    // Settings → Manutenção (limpeza automática de Docker) — ver
    // docs/plano-limpeza-automatica-docker.md. Porta de handlers/settings.luau
    // (dc_*). `dcLastRunAtRaw` é um campo "mudo" (não exibido, só round-trip):
    // preserva o `last_run_at` real entre saves pra um agendamento
    // IntervalHours não reiniciar a contagem toda vez que o usuário salva.
    dcEnabled: false,
    dcKind: "daily", // "interval" | "daily" | "weekly"
    dcHours: "6",
    dcTime: "03:00",
    dcWeekday: "0",
    dcContainers: false,
    dcImages: false,
    dcImagesAll: false,
    dcVolumes: false,
    dcVolumesAll: false,
    dcNetworks: false,
    dcBuildCache: false,
    dcNextRunLabel: "—",
    dcLastRunAtRaw: null,
    dcLastRunText: "ainda não rodou",
    dcRunning: false,
    dcMsg: "",

    get gpRedirect() {
      return oauthRedirectUri(this.ssPublicBase, this.gpKind);
    },

    // ── Navegação (≈ ctx.view do glacier) ───────────────────────────
    // "deployments" | "projects" | "project" | "service" | "new_service"
    view: "deployments",
    selectedProjectId: null,
    selectedServiceId: null,

    // Serviço cujo deploy foi disparado DESTA aba (ver applyBusEvent):
    // sobrevive à navegação, ao contrário de `selectedServiceId`.
    deployTrackId: null,

    // ── Detalhe de serviço aberto ────────────────────────────────────
    serviceDetail: null, // Service (ServiceGet)
    serviceDeployments: [], // Vec<Deployment> (DeployHistory)
    serviceTab: "general",
    serviceMsg: "",
    serviceLoading: false,
    serviceLogLines: [],
    serviceLogStream: null,

    // ── Toasts ────────────────────────────────────────────────────────
    // O par do `toast{ message, kind }` do glacier-ui na GUI desktop: mesmos
    // quatro kinds, mesma duração de 4s, empilhados no canto inferior
    // direito. Existe porque metade das ações da webui só escrevia `*Msg`
    // numa linha da tela — e em quase toda ação bem-sucedida essa linha
    // recebia `""`, ou seja, silêncio total: o único jeito de saber se o
    // clique funcionou era ver a lista mudar.
    //
    // Mensagem de PROGRESSO ("salvando…", "carregando repositórios…")
    // continua inline no `*Msg` da tela. Toast some sozinho; estado, não.
    toasts: [],
    toastSeq: 0,

    toast(message, kind = "info", durationMs = 4000) {
      if (!message) return null;
      const id = ++this.toastSeq;
      this.toasts.push({ id, kind, message: String(message) });
      setTimeout(() => this.dismissToast(id), durationMs);
      return id;
    },

    toastOk(message) {
      return this.toast(message, "success");
    },
    toastErr(message) {
      return this.toast(message, "error");
    },
    toastWarn(message) {
      return this.toast(message, "warning");
    },

    // Desfecho de um rpc num passo só: `okMessage` omitido = sucesso
    // silencioso (a tela já mostra o resultado, um toast seria ruído).
    // Devolve `r.ok` para caber num `if`.
    toastResult(r, okMessage) {
      if (r.ok) {
        if (okMessage) this.toastOk(okMessage);
      } else {
        this.toastErr("erro: " + r.error);
      }
      return r.ok;
    },

    dismissToast(id) {
      const i = this.toasts.findIndex((t) => t.id === id);
      if (i !== -1) this.toasts.splice(i, 1);
    },

    serviceNameById(id) {
      const e = (this.snap?.services || []).find((x) => x.service.id === id);
      return e?.service?.spec?.name || "serviço";
    },

    nav(view) {
      this.stopServiceLogs();
      this.view = view;
    },

    persistPrefs() {
      savePrefs({
        rememberToken: this.rememberToken,
        token: this.rememberToken ? this.token : undefined,
      });
    },

    async connect() {
      // Sem servidor pra digitar: a webui só existe servida pelo próprio
      // daemon, então a origem da página É o servidor.
      const base = window.location.origin;
      this.persistPrefs();
      this.statusLine = "conectando…";
      this.error = "";

      const client = new Api(base, this.token);
      const r = await client.rpc("DaemonStatus");
      if (!r.ok) {
        this.error = r.error;
        this.statusLine = "falha na conexão";
        this.connected = false;
        return;
      }

      this.api = client;
      this.connected = true;
      this.statusLine = "conectado";
      this.screen = "shell";
      this.dataLoading = true;
      await this.loadSettings();
      this.openStream();
    },

    disconnect() {
      this.stopServiceLogs();
      this.stream?.close();
      this.stream = null;
      this.api = null;
      this.snap = null;
      this.connected = false;
      this.screen = "login";
      this.statusLine = "desconectado";
      this.view = "deployments";
      this.selectedProjectId = null;
      this.selectedServiceId = null;
      this.serviceDetail = null;
    },

    openStream() {
      this.stream?.close();
      this.stream = openStream(this.api.baseUrl, this.api.token, "/api/events", {
        onEvent: (kind, data) => this.onStreamEvent(data),
        onError: (msg) => {
          this.statusLine = "stream: " + msg;
        },
        onClose: () => {
          this.stream = null;
          if (this.connected) {
            this.statusLine = "conexão encerrada";
            this.connected = false;
            this.screen = "login";
          }
        },
      });
    },

    onStreamEvent(msg) {
      if (!msg || typeof msg !== "object") return;
      if (msg.kind === "snapshot") this.applySnapshot(msg);
      else if (msg.kind === "bus") this.applyBusEvent(msg.event);
    },

    /** Um evento do bus (mesmo formato que stream.luau::apply_bus trata) —
     * unit variants chegam como string crua (ex. "DeployQueueChanged"). */
    applyBusEvent(ev) {
      if (ev === "DeployQueueChanged") {
        this.refreshNow();
        return;
      }
      if (!ev || typeof ev !== "object") return;
      if (ev.DockerCleanupCompleted) {
        const p = ev.DockerCleanupCompleted;
        this.dcRunning = false;
        this.dcLastRunText = dockerCleanupLastRunSummary({ at: p.at, results: p.results });
        this.dcLastRunAtRaw = p.at;
      } else if (ev.ContainerMetrics) {
        const p = ev.ContainerMetrics;
        if (p.service_id) this.metricsById[p.service_id] = p;
      } else if (ev.SystemMetrics) {
        const s = ev.SystemMetrics;
        this.sysCpu = `${(s.cpu_percent || 0).toFixed(0)}%`;
        this.sysMem = `${fmtBytes(s.mem_used_bytes)} / ${fmtBytes(s.mem_total_bytes)}`;
        this.sysDisk = `${fmtBytes(s.disk_used_bytes)} / ${fmtBytes(s.disk_total_bytes)}`;
        this.sysLoad = `${(s.load_avg_1 || 0).toFixed(2)} ${(s.load_avg_5 || 0).toFixed(2)} ${(s.load_avg_15 || 0).toFixed(2)}`;
      } else if (ev.DeployStateChanged) {
        // O evento sempre carregou `message` — o MOTIVO da falha (texto do
        // docker build, healthcheck que não passou…) — e nenhum dos dois
        // clientes o lia. Sem isto, a tela do serviço só via a linha do
        // deployment virar `Failed` no snapshot de 2s, sem hipótese nenhuma
        // do porquê. Ver docs/plano-erro-de-deploy-invisivel.md.
        const d = ev.DeployStateChanged;
        const terminal =
          d.state === "Live" || d.state === "Failed" || d.state === "Stopped";
        const motivo = shortReason(d.message);
        if (d.service_id && d.service_id === this.selectedServiceId) {
          if (terminal) {
            this.serviceMsg =
              d.state === "Live"
                ? "deploy concluído"
                : motivo
                  ? `deploy falhou: ${motivo}`
                  : `deploy: ${d.state}`;
            this.fetchServiceDetail(d.service_id);
          } else {
            this.serviceMsg = `deploy · ${d.state}`;
          }
        }
        // Desfecho do deploy que ESTE usuário disparou, mesmo que ele já
        // tenha saído da tela do serviço — quem manda deployar vai fazer
        // outra coisa enquanto o build roda. A GUI desktop resolve isso com
        // notificação do SO mais toast; no browser ficamos no toast (uma
        // Notification exigiria pedir permissão, que ninguém pediu).
        if (terminal && d.service_id && d.service_id === this.deployTrackId) {
          this.deployTrackId = null;
          const nome = this.serviceNameById(d.service_id);
          if (d.state === "Live") {
            this.toastOk(`${nome}: deploy concluído`);
          } else {
            this.toastErr(`${nome}: ${motivo || "deploy " + d.state}`);
          }
        }
      }
    },

    applySnapshot(msg) {
      this.snap = msg;
      const st = msg.status;
      if (st) {
        this.daemonVersion = st.version || "";
        this.daemonUptime = fmtUptime(st.uptime_secs);
        this.servicesLabel = `${st.services_running || 0}/${st.services_total || 0}`;
      }
      const byId = {};
      for (const s of msg.jobs || []) byId[s.job.id] = s.job;
      this.jobsById = byId;
      this.dataLoading = false;
    },

    searchChanged(v) {
      this.search = v || "";
    },

    async stopAll() {
      if (!confirm("Parar todos os serviços? Todos os serviços em execução serão parados agora.")) {
        return;
      }
      if (!this.api) return;
      this.statusLine = "parando todos…";
      const r = await this.api.rpcChecked("StopAllManaged");
      this.statusLine = r.ok ? "todos os serviços parados" : "falha ao parar";
      this.toastResult(r, "todos os serviços parados");
    },

    async clearFinished() {
      if (!this.snap) return;
      const ids = (this.snap.deployments || [])
        .map((s) => s.deployment)
        .filter((d) => d.state === "Stopped" || d.state === "Failed")
        .map((d) => d.id);
      if (ids.length === 0) {
        this.toastWarn("nada para limpar");
        return;
      }
      if (
        !confirm(
          `Remove do histórico ${ids.length} deployment(s) em estado Stopped ou Failed, e seus build logs. Ação irreversível.`
        )
      ) {
        return;
      }
      this.deploymentsMsg = `removendo ${ids.length} deployment(s)…`;
      let removed = 0,
        failed = 0;
      for (const id of ids) {
        const r = await this.api.rpcChecked({ DeployDelete: { deployment_id: id } });
        if (r.ok) removed++;
        else failed++;
      }
      this.deploymentsMsg = "";
      if (failed === 0) this.toastOk(`${removed} deployment(s) removido(s)`);
      else this.toastErr(`${removed} removido(s), ${failed} falharam`);
    },

    async refreshNow() {
      if (!this.api) return;
      const r = await this.api.rpc("Snapshot");
      if (r.ok && r.value && typeof r.value.Snapshot === "string") {
        try {
          this.applySnapshot(JSON.parse(r.value.Snapshot));
        } catch {
          /* snapshot malformado — ignora, o próximo tick de 2s corrige */
        }
      }
    },

    // ── Projects ─────────────────────────────────────────────────────

    async createProject(name, description) {
      if (!name || !name.trim()) return { ok: false, error: "nome obrigatório" };
      const r = await this.api.rpcChecked({
        ProjectCreate: { name: name.trim(), description: description?.trim() || null },
      });
      if (r.ok) {
        this.toastOk("projeto criado");
        await this.refreshNow();
      }
      return r;
    },

    async updateProject(id, name, description) {
      const r = await this.api.rpcChecked({
        ProjectUpdate: { id, name: name.trim(), description: description?.trim() || null },
      });
      this.toastResult(r, "projeto atualizado");
      if (r.ok) await this.refreshNow();
      return r;
    },

    async deleteProject(id) {
      if (!confirm("Remover este projeto? Só funciona se não houver serviços nele.")) {
        return { ok: false, error: "cancelado" };
      }
      const r = await this.api.rpcChecked({ ProjectDelete: { id } });
      this.toastResult(r, "projeto removido");
      if (r.ok) {
        await this.refreshNow();
        this.nav("projects");
      }
      return r;
    },

    openProject(id) {
      this.selectedProjectId = id;
      this.nav("project");
    },

    async saveProjectEnv(envVars, envComments) {
      const r = await this.api.rpcChecked({
        ProjectEnvSet: {
          project_id: this.selectedProjectId,
          env_vars: envVars,
          env_comments: envComments,
        },
      });
      this.toastResult(r, "variáveis salvas");
      if (r.ok) await this.refreshNow();
      return r;
    },

    async addSecret(name, value) {
      if (!name.trim()) return { ok: false, error: "nome obrigatório" };
      const r = await this.api.rpcChecked({
        SecretSet: { project_id: this.selectedProjectId, name: name.trim(), value },
      });
      this.toastResult(r, `secret ${name.trim()} salvo`);
      if (r.ok) await this.refreshNow();
      return r;
    },

    async deleteSecret(name) {
      if (!confirm(`Remover o secret "${name}"? Serviços que o referenciam vão falhar no próximo deploy.`)) {
        return;
      }
      const r = await this.api.rpcChecked({
        SecretDelete: { project_id: this.selectedProjectId, name },
      });
      this.toastResult(r, `secret ${name} removido`);
      if (r.ok) await this.refreshNow();
    },

    // ── Services ─────────────────────────────────────────────────────

    openNewService() {
      this.nav("new_service");
    },

    /** Catálogos do wizard (bancos/brokers/templates) — buscados uma vez ao
     * abrir a tela "Novo serviço" (ver screens/new_service.js). */
    async fetchWizardCatalog(search) {
      const r = await this.api.rpc({ WizardCatalog: { search: search || "" } });
      if (!r.ok || !r.value?.WizardCatalog) return { dbs: [], brokers: [], templates: [] };
      const c = r.value.WizardCatalog;
      try {
        return {
          dbs: JSON.parse(c.dbs),
          brokers: JSON.parse(c.brokers),
          templates: JSON.parse(c.templates),
        };
      } catch {
        return { dbs: [], brokers: [], templates: [] };
      }
    },

    /** `req` é o `WizardCreateReq` completo (ver screens/new_service.js) — o
     * daemon (shared::wizard::build_spec) monta o ServiceSpec certo conforme
     * `req.kind`. Usado por Compose/Database/Broker/Template: o backend gera
     * o compose e as env vars corretas (mesma lógica do client iced). */
    async wizardCreate(req) {
      const r = await this.api.rpcChecked({ WizardCreate: req });
      if (r.ok) {
        this.toastOk("serviço criado");
        await this.refreshNow();
        const created = r.value?.Service;
        if (created) this.openService(created.id);
        else this.nav("project");
      }
      return r;
    },

    /** `source` já é o `ServiceSource` externally-tagged. Usado só pelo tipo
     * "Application" do wizard: diferente dos outros 4 tipos, o
     * `WizardCreateReq` não carrega URL de Git nem imagem de registry — o
     * wizard iced cria um serviço vazio (`Registry{image:""}`) e deixa o
     * usuário preencher depois na aba General. Aqui coletamos a origem já na
     * criação (mais direto), então vamos por `ServiceCreate` puro. */
    async createServiceDirect(name, source, port, domain) {
      const spec = {
        name: name.trim(),
        project_id: this.selectedProjectId,
        source,
        port: Number(port) || 80,
        host_port: null,
        domain: domain?.trim() || null,
        tls_enabled: false,
        env_vars: [],
        env_comments: [],
        volumes: [],
        healthcheck: {
          kind: "None",
          interval_secs: 5,
          timeout_secs: 3,
          retries: 10,
          start_period_secs: 5,
        },
        replicas: 1,
        resources: { cpu_shares: 0, mem_limit_bytes: 0 },
        run_command: null,
        run_args: [],
        db_kind: null,
        domains: [],
      };
      const r = await this.api.rpcChecked({ ServiceCreate: spec });
      if (r.ok) {
        this.toastOk("serviço criado");
        await this.refreshNow();
        const created = r.value?.Service;
        if (created) this.openService(created.id);
        else this.nav("project");
      }
      return r;
    },

    async openService(id) {
      this.selectedServiceId = id;
      this.serviceTab = "general";
      this.serviceMsg = "";
      this.serviceDeployments = [];
      this.serviceLoading = true;
      this.nav("service");
      await this.fetchServiceDetail(id);
    },

    async fetchServiceDetail(id) {
      const r = await this.api.rpc({ ServiceGet: { id } });
      if (!r.ok || !r.value?.Service) {
        this.serviceMsg = r.ok ? "serviço não encontrado" : r.error;
        this.serviceLoading = false;
        return;
      }
      this.serviceDetail = r.value.Service;
      const rh = await this.api.rpc({ DeployHistory: { service_id: id, limit: 30 } });
      this.serviceDeployments = (rh.ok && rh.value?.Deployments) || [];
      this.serviceLoading = false;
    },

    async saveServiceSpec(spec, okMsg) {
      const id = this.selectedServiceId;
      const r = await this.api.rpcChecked({ ServiceUpdate: { id, spec } });
      if (r.ok) {
        this.toastOk(okMsg || "salvo");
        await this.fetchServiceDetail(id);
        await this.refreshNow();
      } else {
        this.toastErr("erro: " + r.error);
      }
      return r;
    },

    async deleteService(id) {
      if (!confirm("Remover este serviço? Para o container e apaga o histórico. Ação irreversível.")) {
        return;
      }
      const r = await this.api.rpcChecked({ ServiceDelete: { id } });
      if (r.ok) {
        await this.refreshNow();
        this.nav("project");
        this.toastOk("serviço removido");
      } else {
        this.toastErr("erro ao remover: " + r.error);
      }
    },

    /** Botão "Parar" do card de serviço (grid do projeto) — porta de
     * handlers/projects.luau::svc_stop_id. */
    async stopService(id) {
      if (!confirm("Parar serviço? O tráfego para ele será interrompido até um novo deploy.")) {
        return;
      }
      const r = await this.api.rpcChecked({ ServiceStop: { service_id: id } });
      this.toastResult(r, "serviço parado");
      await this.refreshNow();
    },

    /** Botão "Remover" do card de serviço (grid do projeto) — porta de
     * handlers/projects.luau::stop_delete_service. `ServiceDelete` sozinho
     * NÃO para o container (o handler só apaga linhas do DB e rotas de
     * ingress — ver service_delete.rs), então parar primeiro evita deixar
     * um container órfão rodando fora do controle do rustploy. */
    async stopAndDeleteService(id) {
      const depJobs = (this.snap?.jobs || [])
        .filter((s) => s.job.trigger_service_id === id)
        .map((s) => s.job.name)
        .sort();
      let message = "O serviço será parado e removido.";
      if (depJobs.length > 0) {
        message += ` Os jobs de Schedules que dependem dele também serão removidos, com histórico: ${depJobs.join(", ")}.`;
      }
      message += " Essa ação não pode ser desfeita.";
      if (!confirm(message)) return;

      const r1 = await this.api.rpcChecked({ ServiceStop: { service_id: id } });
      if (!r1.ok) {
        this.toastErr("erro ao parar: " + r1.error);
        return;
      }
      const r2 = await this.api.rpcChecked({ ServiceDelete: { id } });
      if (r2.ok) this.toastOk("serviço parado e removido");
      else this.toastErr("erro ao remover: " + r2.error);
      await this.refreshNow();
    },

    async deployStart() {
      const id = this.selectedServiceId;
      this.serviceMsg = "iniciando deploy…";
      const r = await this.api.rpcChecked({ DeployStart: { service_id: id } });
      this.serviceMsg = "";
      // Guarda quem o USUÁRIO mandou deployar: o desfecho (DeployStateChanged)
      // vira toast mesmo que ele já tenha navegado para outra tela — é o par
      // do `State.deploy_track` da GUI desktop.
      if (r.ok) this.deployTrackId = id;
      this.toastResult(r, "deploy iniciado");
      await this.fetchServiceDetail(id);
      await this.refreshNow();
    },

    async deployAbort(deploymentId) {
      const r = await this.api.rpcChecked({ DeployAbort: { deployment_id: deploymentId } });
      this.toastResult(r, "deploy cancelado");
      await this.fetchServiceDetail(this.selectedServiceId);
    },

    async deployRollback() {
      if (!confirm("Reverter para o deploy anterior?")) return;
      const id = this.selectedServiceId;
      const r = await this.api.rpcChecked({ DeployRollback: { service_id: id } });
      if (r.ok) this.deployTrackId = id;
      this.toastResult(r, "rollback iniciado");
      await this.fetchServiceDetail(id);
    },

    async deleteDeployment(deploymentId) {
      const r = await this.api.rpcChecked({ DeployDelete: { deployment_id: deploymentId } });
      this.toastResult(r, "deployment removido");
      if (r.ok) await this.fetchServiceDetail(this.selectedServiceId);
      return r;
    },

    // ── Deploy Engine (fila global) ─────────────────────────────────────
    // Porta de handlers/deploy_queue.luau — sem drag-and-drop (só glacier);
    // "↑ topo" e "✕" cobrem furar fila / desistir de um item.

    /** Cancela um deploy que ainda espera na fila — reaproveita DeployAbort
     * (o daemon já trata remoção da fila como caso do abort). */
    async queueCancel(deploymentId) {
      const r = await this.api.rpcChecked({ DeployAbort: { deployment_id: deploymentId } });
      this.toastResult(r, "deploy cancelado");
      await this.refreshNow();
    },

    async queuePromote(deploymentId) {
      const r = await this.api.rpcChecked({ DeployQueuePromote: { deployment_id: deploymentId } });
      this.toastResult(r, "deploy movido para o topo da fila");
      await this.refreshNow();
    },

    async queueTogglePause() {
      const paused = !!this.snap?.engine?.paused;
      const r = await this.api.rpcChecked({ DeployQueuePause: { paused: !paused } });
      this.toastResult(r, paused ? "fila retomada" : "fila pausada");
      await this.refreshNow();
    },

    // ── Docker (host-wide) ──────────────────────────────────────────────
    // Porta de handlers/docker.luau — cada prune/remove segue o mesmo padrão:
    // rpcChecked + toast do desfecho + refreshNow() pra refletir na hora
    // (o snapshot de 2s pegaria de qualquer jeito, mas assim fica imediato).

    /** Toast de um prune, com o Response::PruneResult{count,reclaimed_bytes}
     * quando o daemon o devolve; sem esse payload (algum prune que responde
     * só Ok), mensagem genérica. */
    toastPrune(r) {
      if (!r.ok) return this.toastErr("erro: " + r.error);
      const pr = r.value?.PruneResult;
      return this.toastOk(
        pr
          ? `removidos: ${pr.count} · ${fmtBytes(pr.reclaimed_bytes)} liberados`
          : "limpeza concluída"
      );
    },

    async dockerPruneContainers() {
      const r = await this.api.rpcChecked("PruneContainers");
      this.toastPrune(r);
      await this.refreshNow();
    },
    async dockerPruneImages() {
      const r = await this.api.rpcChecked({ PruneImages: { all: this.pruneAllImages } });
      this.toastPrune(r);
      await this.refreshNow();
    },
    async dockerPruneVolumes() {
      const r = await this.api.rpcChecked({ PruneVolumes: { all: this.pruneAllVolumes } });
      this.toastPrune(r);
      await this.refreshNow();
    },
    async dockerPruneNetworks() {
      const r = await this.api.rpcChecked("PruneNetworks");
      this.toastPrune(r);
      await this.refreshNow();
    },

    async dockerRemoveContainer(id) {
      const r = await this.api.rpcChecked({ RemoveContainer: { id } });
      this.toastResult(r, "removido");
      if (r.ok) await this.refreshNow();
    },
    async dockerRemoveImage(id) {
      const r = await this.api.rpcChecked({ RemoveImage: { id } });
      this.toastResult(r, "removido");
      if (r.ok) await this.refreshNow();
    },
    async dockerRemoveVolume(name) {
      const r = await this.api.rpcChecked({ RemoveVolume: { name } });
      this.toastResult(r, "removido");
      if (r.ok) await this.refreshNow();
    },
    async dockerRemoveNetwork(id) {
      const r = await this.api.rpcChecked({ RemoveNetwork: { id } });
      this.toastResult(r, "removido");
      if (r.ok) await this.refreshNow();
    },

    /** Troca a sub-aba Docker; ao entrar em "registry" busca os tokens (não
     * vêm no snapshot periódico, diferente de repos/containers/imagens). */
    async dockerSetTab(tab) {
      this.dockerTab = tab;
      if (tab === "registry") await this.registryRefreshTokens();
    },

    // ── Registry OCI embutido ────────────────────────────────────────────

    async registryOpenRepo(name) {
      this.registrySelectedRepo = name;
      this.registryTagsLoading = true;
      const r = await this.api.rpc({ RegistryTagList: { repo: name } });
      this.registryTags = (r.ok && r.value?.RegistryTags) || [];
      this.registryTagsLoading = false;
    },
    registryCloseRepo() {
      this.registrySelectedRepo = "";
      this.registryTags = [];
    },

    /** Sem rpcChecked de propósito (mesmo comportamento silencioso do Luau —
     * falha aqui não é acionável pelo usuário, só deixa a lista vazia). */
    async registryRefreshTokens() {
      const r = await this.api.rpc("RegistryTokenList");
      this.registryTokens = (r.ok && r.value?.RegistryTokens) || [];
    },

    async registryRmTag(tag) {
      const repo = this.registrySelectedRepo;
      const r = await this.api.rpcChecked({ RegistryTagDelete: { repo, tag } });
      this.toastResult(r, `tag ${tag} removida`);
      if (r.ok) {
        await this.registryOpenRepo(repo);
        await this.refreshNow();
      }
    },
    async registryRmRepo(name) {
      const r = await this.api.rpcChecked({ RegistryRepoDelete: { repo: name } });
      this.toastResult(r, `repositório ${name} removido`);
      if (r.ok) {
        if (this.registrySelectedRepo === name) this.registryCloseRepo();
        await this.refreshNow();
      }
    },
    async registryGc() {
      const r = await this.api.rpcChecked("RegistryGc");
      if (r.ok) {
        const gc = r.value?.RegistryGcResult;
        this.toastOk(
          gc
            ? `GC: ${gc.blobs_removed} arquivo(s) removido(s) · ${fmtBytes(gc.bytes_freed)} liberados`
            : "GC concluído"
        );
        await this.refreshNow();
      } else {
        this.toastErr("erro: " + r.error);
      }
    },
    async registryRmToken(name) {
      const r = await this.api.rpcChecked({ RegistryTokenRevoke: { name } });
      this.toastResult(r, `token ${name} revogado`);
      if (r.ok) await this.registryRefreshTokens();
    },

    /** Devolve {ok, secret} pro modal de "novo token" — o segredo só existe
     * nesta resposta, nunca mais é recuperável depois. */
    async registryCreateToken(name, scope) {
      const r = await this.api.rpcChecked({ RegistryTokenCreate: { name, scope } });
      if (!r.ok) return { ok: false, error: r.error };
      await this.registryRefreshTokens();
      return { ok: true, secret: r.value.RegistryTokenCreated.secret };
    },

    // ── Schedules (jobs one-shot) ────────────────────────────────────────
    // Porta de handlers/jobs.luau.

    async jobRunNow(id) {
      if (this.jobsInflight[id]) return;
      this.jobsInflight[id] = true;
      try {
        const r = await this.api.rpcChecked({ JobRunNow: { id } });
        this.toastResult(r, "job disparado");
        await this.refreshNow();
      } finally {
        delete this.jobsInflight[id];
      }
    },

    /** Cancela um job_run em execução (ver docs/plano-cancelamento-de-jobs.md):
     * mata o processo `docker compose up` de verdade no daemon, não só a UI.
     * `jobRunId` vem de `j.lastRunId` — enquanto `j.running` só reflete o
     * estado otimista de `jobsInflight` (antes do primeiro refresh confirmar
     * o job_run novo), pode ainda apontar pro run ANTERIOR; o daemon devolve
     * NotFound nesse caso (inofensivo, só a mensagem de erro). */
    async jobRunCancel(jobRunId) {
      if (!jobRunId) return;
      const r = await this.api.rpcChecked({ JobRunCancel: { job_run_id: jobRunId } });
      this.toastResult(r, "cancelamento solicitado");
      await this.refreshNow();
    },

    /** Reenvia o Job inteiro (só `enabled` inverte) — o daemon não tem um
     * PATCH parcial; mesma limitação do cliente iced. */
    async jobToggle(id) {
      const job = this.jobsById[id];
      if (!job) {
        this.toastWarn("job não encontrado no snapshot atual");
        return;
      }
      const r = await this.api.rpcChecked({
        JobUpdate: {
          id: job.id,
          name: job.name,
          compose: job.compose,
          git_source: job.git_source ?? null,
          main_service: job.main_service,
          env_vars: job.env_vars ?? [],
          env_comments: job.env_comments ?? [],
          enabled: !job.enabled,
          recurrence: job.recurrence,
        },
      });
      this.toastResult(r, job.enabled ? "job desativado" : "job ativado");
      await this.refreshNow();
    },

    async jobDelete(id) {
      if (!confirm("Remover este job? Ação irreversível.")) return;
      const r = await this.api.rpcChecked({ JobDelete: { id } });
      this.toastResult(r, "job removido");
      await this.refreshNow();
    },

    /** `payload` = { project_id, trigger_service_id, name, compose,
     * main_service, recurrence }. */
    async jobCreate(payload) {
      const r = await this.api.rpcChecked({ JobCreate: payload });
      if (r.ok) await this.refreshNow();
      return r;
    },

    // ── Wizard "novo job" (ver campos no bloco de estado acima) ──────────
    // Porta de new_job_window.luau — mesmos passos e mesma validação.

    get njobProjects() {
      return this.snap?.projects || [];
    },
    /** Serviços do projeto escolhido — já em memória (snap.services), sem
     * re-fetch (diferente do Luau, que precisa pré-semear a janela isolada). */
    get njobServicesFiltered() {
      return (this.snap?.services || []).filter(
        (e) => e.service.spec.project_id === this.njobProjectId
      );
    },

    openNewJob() {
      this.showNewJob = true;
      this.njobStep = "pick_project";
      this.njobEditId = null;
      this.njobEnabled = true;
      this.njobProjectId = "";
      this.njobProjectName = "";
      this.njobServiceId = "";
      this.njobServiceName = "";
      this.njobName = "";
      this.njobCompose = "";
      this.njobSourceTab = "compose";
      this.njobGitProviderId = "";
      this.njobGitProviders = [];
      this.njobGitRepos = [];
      this.njobGitRepoFullName = "";
      this.njobGitBranches = [];
      this.njobGitBranch = "";
      this.njobComposePath = "docker-compose.yml";
      this.njobGitMsg = "";
      this.njobMainService = "";
      this.njobEnvText = "";
      this.njobKind = "manual";
      this.njobHours = "6";
      this.njobTime = "03:00";
      this.njobWeekday = "0";
      this.njobErr = "";
    },
    closeNewJob() {
      this.showNewJob = false;
    },
    njobPickProject(id, name) {
      this.njobProjectId = id;
      this.njobProjectName = name;
      this.njobStep = "pick_service";
    },
    njobPickService(id, name) {
      this.njobServiceId = id;
      this.njobServiceName = name;
      this.njobStep = "form";
    },
    njobPickNoService() {
      this.njobServiceId = "";
      this.njobServiceName = "nenhum (autônomo)";
      this.njobStep = "form";
    },
    njobBack() {
      // Modo edição: não há passos 1/2 pra voltar (project_id/
      // trigger_service_id não são editáveis via JobUpdate) — fecha o modal.
      if (this.njobEditId) {
        this.closeNewJob();
        return;
      }
      if (this.njobStep === "form") this.njobStep = "pick_service";
      else if (this.njobStep === "pick_service") this.njobStep = "pick_project";
    },

    // ── Fonte do compose: aba "Compose" x aba "Git" (picker conta→repo→branch) ──
    // Porta de njob_source/njob_git_provider_pick/njob_git_repo_pick do
    // cliente iced (new_job_window.luau) — mesma resolução, sem a limitação
    // de janela isolada (aqui é só um fetch preguiçoso na primeira troca de aba).
    async njobSetSourceTab(kind) {
      this.njobSourceTab = kind;
      if (kind === "git" && this.njobGitProviders.length === 0) {
        this.njobGitMsg = "carregando contas…";
        const r = await this.api.rpc("GitProviderList");
        if (r.ok && r.value?.GitProviders) {
          this.njobGitProviders = r.value.GitProviders;
          this.njobGitMsg = "";
        } else {
          this.njobGitMsg = "erro ao listar contas conectadas";
        }
      }
    },
    async njobGitProviderPick(id) {
      this.njobGitProviderId = id || "";
      this.njobGitRepoFullName = "";
      this.njobGitRepos = [];
      this.njobGitBranches = [];
      if (!this.njobGitProviderId) return;
      this.njobGitMsg = "carregando repositórios…";
      const r = await this.api.rpc({ GitRepoList: { provider_id: this.njobGitProviderId } });
      if (r.ok && r.value?.GitRepos) {
        this.njobGitRepos = r.value.GitRepos;
        this.njobGitMsg = `${r.value.GitRepos.length} repositório(s)`;
      } else {
        this.njobGitMsg = "erro ao listar repositórios";
      }
    },
    async njobGitRepoPick(fullName) {
      if (!fullName) return;
      this.njobGitRepoFullName = fullName;
      const repo = this.njobGitRepos.find((r) => r.full_name === fullName);
      if (repo?.default_branch) this.njobGitBranch = repo.default_branch;
      this.njobGitBranches = [];
      if (!this.njobGitProviderId) return;
      this.njobGitMsg = "carregando branches…";
      const r = await this.api.rpc({
        GitBranchList: { provider_id: this.njobGitProviderId, repo_full_name: fullName },
      });
      if (r.ok && r.value?.GitBranches) {
        this.njobGitBranches = r.value.GitBranches;
        this.njobGitMsg = "";
      } else {
        this.njobGitMsg = "erro ao listar branches";
      }
    },

    /** Monta `recurrence` (Option<Recurrence>, externally-tagged) a partir
     * de njobKind. */
    buildNjobRecurrence() {
      if (this.njobKind === "interval") {
        return { IntervalHours: Math.max(1, Number(this.njobHours) || 1) };
      }
      const [hora, minuto] = hmSplit(this.njobTime);
      if (this.njobKind === "daily") {
        return { Daily: { hour: hora, minute: minuto } };
      }
      if (this.njobKind === "weekly") {
        return {
          Weekly: {
            weekday: Number(this.njobWeekday) || 0,
            hour: hora,
            minute: minuto,
          },
        };
      }
      return null;
    },

    async njobCreate() {
      if (!this.njobName.trim() || !this.njobMainService.trim()) {
        this.njobErr = "nome e main service são obrigatórios";
        return;
      }
      let compose = "";
      let gitSource = null;
      if (this.njobSourceTab === "git") {
        const branch = this.njobGitBranch.trim();
        if (!this.njobGitRepoFullName || !branch) {
          this.njobErr = "selecione repositório e branch";
          return;
        }
        const composePath = this.njobComposePath.trim() || "docker-compose.yml";
        const repo = this.njobGitRepos.find((r) => r.full_name === this.njobGitRepoFullName);
        if (!repo?.clone_url) {
          this.njobErr = "não foi possível resolver a URL do repositório — selecione de novo";
          return;
        }
        gitSource = {
          provider_id: this.njobGitProviderId || null,
          url: repo.clone_url,
          branch,
          username: null,
          credentials: null,
          compose_path: composePath,
        };
      } else {
        compose = this.njobCompose;
        if (!compose.trim()) {
          this.njobErr = "cole o docker-compose.yml do job";
          return;
        }
      }
      this.njobErr = "";
      this.njobSubmitting = true;
      const { vars: envVars, comments: envComments } = parseDotenv(this.njobEnvText);
      let r;
      if (this.njobEditId) {
        r = await this.api.rpcChecked({
          JobUpdate: {
            id: this.njobEditId,
            name: this.njobName.trim(),
            compose,
            git_source: gitSource,
            main_service: this.njobMainService.trim(),
            env_vars: envVars,
            env_comments: envComments,
            enabled: this.njobEnabled,
            recurrence: this.buildNjobRecurrence(),
          },
        });
        if (r.ok) await this.refreshNow();
      } else {
        r = await this.jobCreate({
          project_id: this.njobProjectId,
          // "" (não null) = job autônomo — Command::JobCreate::trigger_service_id
          // é String simples no protocolo (não Option<String>); o handler no
          // daemon é quem converte "" → None (job_create.rs).
          trigger_service_id: this.njobServiceId || "",
          name: this.njobName.trim(),
          compose,
          git_source: gitSource,
          main_service: this.njobMainService.trim(),
          env_vars: envVars,
          env_comments: envComments,
          recurrence: this.buildNjobRecurrence(),
        });
      }
      this.njobSubmitting = false;
      if (r.ok) {
        this.toastOk(this.njobEditId ? "job atualizado" : "job criado");
        this.closeNewJob();
      } else {
        this.njobErr = r.error;
      }
    },

    /** Abre o mesmo modal do wizard, mas em modo edição: pula pro passo
     * "form" já preenchido com o job existente (project_id/trigger_service_id
     * não são editáveis via JobUpdate, então não há passos 1/2 aqui). Só
     * webui — sem a limitação de janela isolada do cliente iced, então
     * resolve a conta/repo/branch do git_source direto, sem pré-fetch. */
    async openEditJob(id) {
      const job = this.jobsById[id];
      if (!job) {
        this.toastWarn("job não encontrado no snapshot atual");
        return;
      }
      this.showNewJob = true;
      this.njobEditId = id;
      this.njobStep = "form";
      this.njobErr = "";
      this.njobName = job.name || "";
      this.njobMainService = job.main_service || "";
      this.njobEnabled = !!job.enabled;
      this.njobEnvText = dotenvFromVars(job.env_vars, job.env_comments);

      const rec = job.recurrence;
      if (rec?.IntervalHours != null) {
        this.njobKind = "interval";
        this.njobHours = String(rec.IntervalHours);
      } else if (rec?.Daily) {
        this.njobKind = "daily";
        this.njobTime = hmJoin(rec.Daily.hour, rec.Daily.minute);
      } else if (rec?.Weekly) {
        this.njobKind = "weekly";
        this.njobWeekday = String(rec.Weekly.weekday);
        this.njobTime = hmJoin(rec.Weekly.hour, rec.Weekly.minute);
      } else {
        this.njobKind = "manual";
      }

      if (job.git_source) {
        this.njobSourceTab = "git";
        this.njobCompose = "";
        this.njobGitBranch = job.git_source.branch || "";
        this.njobComposePath = job.git_source.compose_path || "docker-compose.yml";
        this.njobGitProviderId = job.git_source.provider_id || "";
        if (this.njobGitProviderId) {
          // O modal já está visível neste ponto (showNewJob=true lá em cima)
          // — sem esta mensagem os selects de repo/branch ficam vazios,
          // sem nenhuma explicação, durante os 2-3 round-trips abaixo.
          this.njobGitMsg = "carregando repositórios…";
          const rp = await this.api.rpc("GitProviderList");
          if (rp.ok && rp.value?.GitProviders) this.njobGitProviders = rp.value.GitProviders;
          const rr = await this.api.rpc({ GitRepoList: { provider_id: this.njobGitProviderId } });
          if (rr.ok && rr.value?.GitRepos) {
            this.njobGitRepos = rr.value.GitRepos;
            const match = this.njobGitRepos.find((repo) => repo.clone_url === job.git_source.url);
            this.njobGitRepoFullName = match?.full_name || "";
            if (this.njobGitRepoFullName) {
              this.njobGitMsg = "carregando branches…";
              const rb = await this.api.rpc({
                GitBranchList: {
                  provider_id: this.njobGitProviderId,
                  repo_full_name: this.njobGitRepoFullName,
                },
              });
              if (rb.ok && rb.value?.GitBranches) this.njobGitBranches = rb.value.GitBranches;
            }
          }
          this.njobGitMsg = "";
        }
      } else {
        this.njobSourceTab = "compose";
        this.njobCompose = job.compose || "";
      }
    },

    openJobLogs(jobRunId) {
      this.jobLogsFor = jobRunId;
      this.startJobLogs(jobRunId);
    },
    closeJobLogs() {
      this.jobLogsFor = null;
      this.stopJobLogs();
    },

    /** Logs ao vivo de UMA execução de job — mesmo par seed+SSE de
     * startServiceLogs/stopServiceLogs, apontando pro endpoint dedicado de
     * job run (gêmeo do de serviço: mesmo framing bus_batch). */
    async startJobLogs(jobRunId) {
      this.stopJobLogs();
      const seed = await this.api.rpc({ GetJobLogs: { job_run_id: jobRunId } });
      this.jobLogLines = ((seed.ok && seed.value?.JobLogs) || []).map(this.cleanLogEntry);
      this.jobLogStream = openStream(
        this.api.baseUrl,
        this.api.token,
        `/api/jobs/runs/${jobRunId}/logs`,
        {
          onEvent: (_kind, data) => {
            if (data?.kind === "bus_batch" && Array.isArray(data.events)) {
              for (const ev of data.events) {
                const line = ev?.JobLogLine;
                if (line) this.jobLogLines.push(this.cleanLogEntry(line));
              }
              const MAX = 2000;
              if (this.jobLogLines.length > MAX) {
                this.jobLogLines.splice(0, this.jobLogLines.length - MAX);
              }
            }
          },
        }
      );
    },
    stopJobLogs() {
      this.jobLogStream?.close();
      this.jobLogStream = null;
    },

    // ── Settings ──────────────────────────────────────────────────────────
    // Porta de handlers/settings.luau + a load_settings() de connection.luau.
    // Buscado uma vez na conexão (não a cada snapshot — senão apagaria o que
    // o usuário está digitando nos formulários).

    async loadSettings() {
      const r = await this.api.rpc("GetDaemonSettings");
      if (r.ok && r.value?.DaemonSettings) {
        const s = r.value.DaemonSettings;
        this.ssPublicBase = s.public_base_url || "";
        this.ssEmail = s.acme_email || "";
        this.ssRegistryDomain = s.registry_domain || "";
      }
      await this.gpRefresh();
      await this.dcLoad();
    },

    async settingsSave() {
      const email = this.ssEmail.trim();
      const registryDomain = this.ssRegistryDomain.trim();
      this.settingsMsg = "salvando…";
      const r = await this.api.rpcChecked({
        SetDaemonSettings: {
          acme_email: email || null,
          registry_domain: registryDomain || null,
        },
      });
      this.settingsMsg = "";
      this.toastResult(r, "configurações salvas");
    },

    async gpRefresh() {
      const r = await this.api.rpc("GitProviderList");
      this.gitProviders = (r.ok && r.value?.GitProviders) || [];
    },

    /** Mesmas validações de handlers/settings.luau::gp_connect: GitHub cai
     * pro github.com se a Base URL vier vazia (só existe pra Enterprise);
     * Gitea sempre exige Base URL. Client id+secret OU PAT, conforme gpMode. */
    async gpConnect() {
      this.gpOauthUrl = "";
      const isGithub = this.gpKind === "github";
      const kindWire = isGithub ? "Github" : "Gitea";
      const label = isGithub ? "GitHub" : "Gitea";
      let base = this.gpBaseUrl.trim();
      if (!base) {
        if (isGithub) base = "https://github.com";
        else {
          this.toastWarn("informe a Base URL do Gitea");
          return;
        }
      }
      const name = this.gpName.trim() || label;
      const isOauth = this.gpMode !== "pat";
      let cmd;
      if (isOauth) {
        const cid = this.gpClientId.trim();
        const csec = this.gpClientSecret || "";
        if (!cid || !csec.trim()) {
          this.toastWarn("Client ID e Client Secret são obrigatórios");
          return;
        }
        cmd = {
          GitProviderCreate: {
            kind: kindWire,
            name,
            base_url: base,
            auth_mode: "OAuth",
            oauth_client_id: cid,
            oauth_client_secret: csec,
            pat: null,
          },
        };
      } else {
        const pat = this.gpPat || "";
        if (!pat.trim()) {
          this.toastWarn("informe o Personal Access Token");
          return;
        }
        cmd = {
          GitProviderCreate: {
            kind: kindWire,
            name,
            base_url: base,
            auth_mode: "Pat",
            oauth_client_id: null,
            oauth_client_secret: null,
            pat,
          },
        };
      }
      this.gpMsg = "conectando…";
      const r = await this.api.rpc(cmd);
      if (!r.ok || !r.value?.GitProviderInfo) {
        this.gpMsg = "";
        this.toastErr("erro: " + (r.ok ? "resposta inesperada" : r.error));
        return;
      }
      const pid = r.value.GitProviderInfo.id;
      if (isOauth) {
        // OAuth precisa de round-trip no navegador — diferente do Luau (que só
        // linkava por não saber abrir o browser), aqui abrimos direto.
        const ro = await this.api.rpc({ GitOAuthStart: { provider_id: pid } });
        if (ro.ok && ro.value?.OAuthUrl) {
          this.gpOauthUrl = ro.value.OAuthUrl;
          this.gpMsg = "autorize a janela aberta e depois clique em Atualizar";
          window.open(ro.value.OAuthUrl, "_blank");
        } else {
          this.gpMsg = "provider criado; inicie o OAuth manualmente";
        }
      } else {
        this.gpMsg = "";
        this.toastOk(`conta ${label} conectada`);
      }
      this.gpName = "";
      this.gpBaseUrl = "";
      this.gpClientId = "";
      this.gpClientSecret = "";
      this.gpPat = "";
      await this.gpRefresh();
    },

    async gpDelete(id) {
      const r = await this.api.rpcChecked({ GitProviderDelete: { id } });
      this.gpMsg = "";
      this.toastResult(r, "provider removido");
      await this.gpRefresh();
    },

    async iacExport() {
      this.iacExportMsg = "exportando…";
      const r = await this.api.rpcChecked("ManifestExportAll");
      if (!r.ok || !r.value?.ManifestBundle) {
        this.iacExportMsg = "";
        this.toastErr("erro: " + (r.ok ? "resposta inesperada" : r.error));
        return;
      }
      this.iacYaml = r.value.ManifestBundle.yaml;
      this.iacDotenv = r.value.ManifestBundle.dotenv;
      this.iacHasExport = true;
      this.iacExportMsg = "";
      this.toastOk("manifesto exportado");
    },

    /** 3 formas de resposta possíveis (mesma distinção de handlers/
     * settings.luau::iac_import): MissingEnvVars (nada aplicado), Err
     * (rpc-level), ou ManifestReport (sucesso). */
    async iacImport() {
      this.iacHasMissing = false;
      this.iacHasReport = false;
      this.iacMissingVars = "";
      this.iacReportLines = [];

      const yaml = this.iacImportYaml || "";
      if (!yaml.trim()) {
        this.toastWarn("cole o YAML do manifesto");
        return;
      }

      this.iacImportMsg = "importando…";
      const r = await this.api.rpc({
        ManifestImport: {
          yaml,
          dotenv: this.iacImportDotenv || "",
          prune: this.iacPrune,
          deploy: this.iacDeploy,
        },
      });
      if (!r.ok) {
        this.iacImportMsg = "";
        this.toastErr("erro: " + r.error);
        return;
      }
      const v = r.value;
      if (v?.MissingEnvVars) {
        this.iacHasMissing = true;
        this.iacMissingVars = v.MissingEnvVars.join(", ");
        this.iacImportMsg = "faltam variáveis — nada foi aplicado";
        this.toastErr("faltam variáveis — nada foi aplicado");
        return;
      }
      if (v?.Err) {
        this.iacImportMsg = "";
        this.toastErr(`erro: ${v.Err.code}: ${v.Err.message}`);
        return;
      }
      if (!v?.ManifestReport) {
        this.iacImportMsg = "";
        this.toastErr("resposta inesperada do daemon");
        return;
      }
      const lines = (v.ManifestReport.actions || []).map(
        (a) => `[${a.action}] ${a.kind} ${a.name}`
      );
      if ((v.ManifestReport.deployed || []).length > 0) {
        lines.push("deploy disparado: " + v.ManifestReport.deployed.join(", "));
      }
      this.iacReportLines = lines;
      this.iacHasReport = true;
      this.iacImportMsg = "";
      this.toastOk("import concluído");
      await this.refreshNow();
    },

    // ── Settings → Manutenção (limpeza automática de Docker) ────────────
    // Porta de handlers/settings.luau (dc_*) — ver
    // docs/plano-limpeza-automatica-docker.md. Config é um singleton do
    // daemon, carregada/salva inteira a cada Get/Set.

    /** Recorrência (Option<Recurrence>, externally-tagged) → campos do
     * formulário — mesmo formato do unpack usado ao editar um Job (acima,
     * perto de `njobKind`). */
    dcApplyConfig(cfg) {
      this.dcEnabled = !!cfg.enabled;
      this.dcContainers = !!cfg.containers;
      this.dcImages = !!cfg.images;
      this.dcImagesAll = !!cfg.images_all;
      this.dcVolumes = !!cfg.volumes;
      this.dcVolumesAll = !!cfg.volumes_all;
      this.dcNetworks = !!cfg.networks;
      this.dcBuildCache = !!cfg.build_cache;
      const r = cfg.recurrence;
      if (r && r.IntervalHours != null) {
        this.dcKind = "interval";
        this.dcHours = String(r.IntervalHours);
      } else if (r && r.Weekly) {
        this.dcKind = "weekly";
        this.dcTime = hmJoin(r.Weekly.hour, r.Weekly.minute);
        this.dcWeekday = String(r.Weekly.weekday);
      } else if (r && r.Daily) {
        this.dcKind = "daily";
        this.dcTime = hmJoin(r.Daily.hour, r.Daily.minute);
      } else {
        this.dcKind = "daily";
      }
      this.dcNextRunLabel = cfg.next_run_at ? dateDmHm(cfg.next_run_at) : "—";
      this.dcLastRunAtRaw = cfg.last_run_at ?? null;
    },

    async dcLoad() {
      const r = await this.api.rpc("DockerCleanupConfigGet");
      if (r.ok && r.value?.DockerCleanupConfig) {
        this.dcApplyConfig(r.value.DockerCleanupConfig.config);
        this.dcLastRunText = dockerCleanupLastRunSummary(r.value.DockerCleanupConfig.last_run);
      }
    },

    dcBuildRecurrence() {
      if (this.dcKind === "interval") {
        return { IntervalHours: Math.max(1, parseInt(this.dcHours, 10) || 1) };
      }
      const [hora, minuto] = hmSplit(this.dcTime);
      if (this.dcKind === "weekly") {
        return {
          Weekly: {
            weekday: parseInt(this.dcWeekday, 10) || 0,
            hour: hora,
            minute: minuto,
          },
        };
      }
      return {
        Daily: {
          hour: hora,
          minute: minuto,
        },
      };
    },

    async dcSave() {
      this.dcMsg = "salvando…";
      const r = await this.api.rpcChecked({
        DockerCleanupConfigSet: {
          config: {
            enabled: this.dcEnabled,
            recurrence: this.dcBuildRecurrence(),
            containers: this.dcContainers,
            images: this.dcImages,
            images_all: this.dcImagesAll,
            volumes: this.dcVolumes,
            volumes_all: this.dcVolumesAll,
            networks: this.dcNetworks,
            build_cache: this.dcBuildCache,
            last_run_at: this.dcLastRunAtRaw,
          },
        },
      });
      if (r.ok && r.value?.DockerCleanupConfig) {
        this.dcApplyConfig(r.value.DockerCleanupConfig.config);
        this.dcLastRunText = dockerCleanupLastRunSummary(r.value.DockerCleanupConfig.last_run);
        this.dcMsg = "";
        this.toastOk("configurações salvas");
      } else {
        this.dcMsg = "";
        this.toastErr("erro: " + r.error);
      }
    },

    /** Botão "Executar agora": roda os recursos marcados fora do horário
     * agendado, independente do interruptor geral. Roda em background no
     * daemon — `dcRunning` volta a `false` quando `Event::DockerCleanupCompleted`
     * chega (applyBusEvent), não pela resposta deste RPC. */
    async dcRunNow() {
      const anySelected =
        this.dcContainers || this.dcImages || this.dcVolumes || this.dcNetworks || this.dcBuildCache;
      if (!anySelected) {
        this.toastWarn("marque pelo menos um recurso");
        return;
      }
      if (
        !confirm(
          "Roda a limpeza dos recursos marcados imediatamente, fora do horário agendado. Ação irreversível."
        )
      ) {
        return;
      }
      this.dcRunning = true;
      this.dcMsg = "executando…";
      const r = await this.api.rpcChecked("DockerCleanupRunNow");
      if (!r.ok) {
        this.dcRunning = false;
        this.dcMsg = "";
        this.toastErr("erro: " + r.error);
      }
    },

    async serviceStop() {
      const id = this.selectedServiceId;
      const r = await this.api.rpcChecked({ ServiceStop: { service_id: id } });
      this.toastResult(r, "serviço parado");
      await this.fetchServiceDetail(id);
      await this.refreshNow();
    },

    async serviceReload() {
      const id = this.selectedServiceId;
      const r = await this.api.rpcChecked({ ServiceReload: { service_id: id } });
      this.toastResult(r, "serviço recarregado");
      await this.fetchServiceDetail(id);
    },

    // ── Logs (aba Logs do serviço) ───────────────────────────────────
    // Mesmo endpoint SSE dedicado do client iced (crates/daemon/src/api/
    // http_api.rs::service_logs), com o mesmo histórico inicial via LogsGet
    // (ver startServiceLogs).

    /** LogEntry/LogLine cru → { stream, line, timestamp } com ANSI limpo e
     * truncado (defesa contra uma linha absurda — ex. um dump binário sem
     * quebra — quebrar o layout inteiro da aba, como aconteceu antes de
     * filtrar ANSI: a barra de escape crua virava glifos de caixa e o texto
     * "empilhava" visualmente). Mesmo teto de fmt/service_detail.luau::
     * log_rows (LINE_MAX). */
    cleanLogEntry(e) {
      const LINE_MAX = 4000;
      let line = stripAnsi(e.line || "");
      if (line.length > LINE_MAX) line = line.slice(0, LINE_MAX) + "…";
      return { stream: e.stream, line, timestamp: e.timestamp };
    },

    /** Exposta no store (não só no módulo) porque o modal de logs de job é
     * global — ver bloco "Modais globais de Jobs" em index.html. */
    timeHms,

    async startServiceLogs() {
      this.stopServiceLogs();
      const id = this.selectedServiceId;
      // Semeia o histórico ANTES de abrir o stream ao vivo — mesma ordem do
      // client iced (handlers/services.luau::open_logs_window): sem isso, um
      // serviço já rodando há tempo (sem stdout novo desde então) mostra a
      // aba vazia para sempre, mesmo tendo logs de sobra.
      const seed = await this.api.rpc({ LogsGet: { service_id: id, tail: 500 } });
      this.serviceLogLines = ((seed.ok && seed.value?.Logs) || []).map(this.cleanLogEntry);
      // A troca de aba pode ter acontecido enquanto o fetch estava em voo —
      // se o usuário já saiu da aba Logs (ou do serviço), não abre a stream.
      if (this.serviceTab !== "logs" || this.selectedServiceId !== id) return;
      this.serviceLogStream = openStream(
        this.api.baseUrl,
        this.api.token,
        `/api/services/${id}/logs`,
        {
          onEvent: (_kind, data) => {
            if (data?.kind === "bus_batch" && Array.isArray(data.events)) {
              for (const ev of data.events) {
                const line = ev?.LogLine;
                if (line) this.serviceLogLines.push(this.cleanLogEntry(line));
              }
              const MAX = 2000;
              if (this.serviceLogLines.length > MAX) {
                this.serviceLogLines.splice(0, this.serviceLogLines.length - MAX);
              }
            }
          },
        }
      );
    },

    stopServiceLogs() {
      this.serviceLogStream?.close();
      this.serviceLogStream = null;
    },

    setServiceTab(tab) {
      this.serviceTab = tab;
      if (tab === "logs") this.startServiceLogs();
      else this.stopServiceLogs();
    },
  });
});

// Dispara `alpine:init` só agora — todos os listeners acima (login.js,
// dashboard.js, o Alpine.store deste arquivo) já estão registrados.
Alpine.start();

if ("serviceWorker" in navigator) {
  window.addEventListener("load", () => {
    navigator.serviceWorker.register("/sw.js").catch(() => {
      /* PWA opcional — a app funciona normalmente sem o SW */
    });
  });
}