rustploy-gui 0.1.74

Rustploy — desktop client (glacier-ui) for the Rustploy PaaS daemon
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
--!strict
--!nolint FunctionUnused
-- new_job_window.luau — script da JANELA "Novo job", um motor Glacier próprio
-- e ISOLADO do app principal (aberto via open_window por
-- handlers/jobs.luau::open_new_job_window). Recebe a conexão (api_url/
-- api_token) e os catálogos de projetos/serviços JÁ BUSCADOS pela janela
-- principal, semeados via open_window({ data = ... }) — um `fetch` rodado no
-- `init()` é descartado pelo motor (só ações despachadas chegam ao
-- executor), mesma razão de `new_service_window.luau`.
--
-- require resolve relativo a ESTE arquivo (scripts/): "net/api", "helpers" e
-- "format" (só os builders de git_providers/git_repos/git_branches, reusados
-- da aba Gitea de serviço — ver handlers/services.luau).

local Api = require("net/api")
local Helpers = require("helpers")
local format = require("format")
local Core = require("job_env_core")
require("job_env_actions")

local function client(): Api.Client?
    local url = ctx.api_url or ""
    if url == "" then
        return nil
    end
    return Api.new(url, ctx.api_token)
end

local function decode(json_text: string?): { any }
    local json_decode_ok, decoded = Helpers.decode_list(json_text)
    if json_decode_ok and type(decoded) == "table" then
        return decoded
    end
    return {}
end

-- Recorrência (Option<Recurrence>, externally-tagged) → (kind, hours, hour,
-- minute, weekday), pro formulário. Inverso do bloco em new_job_create.
local function unpack_recurrence(
    recurrence: any
): (string, string, string, string, string)
    if recurrence == nil then
        return "manual", "6", "3", "0", "0"
    end
    if recurrence.IntervalHours ~= nil then
        return "interval", tostring(recurrence.IntervalHours), "3", "0", "0"
    end
    if recurrence.Daily ~= nil then
        return "daily",
            "6",
            tostring(recurrence.Daily.hour),
            tostring(recurrence.Daily.minute),
            "0"
    end
    if recurrence.Weekly ~= nil then
        return "weekly",
            "6",
            tostring(recurrence.Weekly.hour),
            tostring(recurrence.Weekly.minute),
            tostring(recurrence.Weekly.weekday)
    end
    return "manual", "6", "3", "0", "0"
end

function init(): ()
    -- ctx.new_job_projects/new_job_services já chegam como JSON (semeados via
    -- data).
    ctx.new_job_projects = ctx.new_job_projects or json.array({})
    ctx.new_job_services_all = ctx.new_job_services or json.array({})
    ctx.new_job_services_filtered = json.array({})

    ctx.new_job_step = "pick_project"
    ctx.new_job_project_id = ""
    ctx.new_job_project_name = ""
    ctx.new_job_service_id = ""
    ctx.new_job_service_name = ""
    ctx.new_job_name = ""
    ctx.new_job_compose = ""
    ctx.new_job_main_service = ""
    -- Variáveis do job novo (lista local, ver draft_env_start): publicadas já
    -- aqui para o markup nunca ler chave inexistente.
    ctx.new_job_env_key = ""
    ctx.new_job_env_value = ""
    ctx.new_job_env_is_secret = "false"
    ctx.new_job_env_secret_options = json.array({})
    ctx.new_job_env_rows = json.array({})
    ctx.new_job_env_count = "0"

    -- Fonte do compose: "compose" (colado, default) | "git" (clona um repo
    -- a cada execução — mesmo picker conta→repo→branch da aba Gitea de
    -- serviço). Ver
    -- new_job_source/new_job_git_provider_pick/new_job_git_repo_pick. Os
    -- campos de picker usam `or` (não sobrescrevem à força): em modo edição de
    -- job git-sourced, open_edit_job_window já resolveu e semeou esses valores
    -- (não dá pra buscar aqui dentro, ver docstring do topo).
    ctx.new_job_source = "compose"
    ctx.new_job_git_providers = ctx.new_job_git_providers or json.array({})
    ctx.new_job_git_provider_id = ""
    ctx.new_job_git_repos = ctx.new_job_git_repos or json.array({})
    ctx.new_job_git_repo = ctx.new_job_git_repo or ""
    ctx.new_job_git_branches = ctx.new_job_git_branches or json.array({})
    ctx.new_job_git_branch = ""
    ctx.new_job_compose_path = "docker-compose.yml"
    ctx.new_job_git_message = ""
    ctx.new_job_git_busy = ""
    ctx.new_job_busy = ""

    -- Envs e secrets do job: no passo "env" (painel compartilhado,
    -- scripts/job_env_core.luau), que mexe direto no daemon por `job_id` — por
    -- isso só existe com o job criado (na edição, já está; na criação, aparece
    -- logo depois de "Criar job").
    ctx.new_job_created_id = ""
    ctx.new_job_env_seed = ""

    ctx.new_job_kind = "manual"
    ctx.new_job_hours = "6"
    -- Uma chave só, "HH:MM": quem edita o horário agora é o <timeedit> do
    -- .gv. `unpack_recurrence` segue devolvendo hora/minuto separados (é o
    -- formato do daemon) e format.hour_minute_join/hour_minute_split fazem a
    -- ponte.
    ctx.new_job_time = "03:00"
    ctx.new_job_weekday = "0"
    -- Coleção fixa do <radiogroup> de dia da semana (recorrência Semanal).
    ctx.weekdays = format.weekdays()
    ctx.new_job_error = ""
    ctx.new_job_message = ""

    -- ── Modo edição: open_edit_job_window semeia new_job_edit_job (Job cru em
    -- JSON) — pula os passos 1/2 (projeto/serviço gatilho não são editáveis
    -- via JobUpdate) e preenche o passo 3 inteiro com o job existente.
    ctx.new_job_edit_id = ""
    ctx.new_job_enabled = "true"
    if ctx.new_job_edit_job and ctx.new_job_edit_job ~= "" then
        local json_decode_ok, job = pcall(json.decode, ctx.new_job_edit_job)
        if json_decode_ok and type(job) == "table" then
            ctx.new_job_edit_id = job.id
            ctx.new_job_project_id = job.project_id or ""
            -- Envs do Job como vieram (o painel as relê do daemon); o "Salvar"
            -- do formulário as reenvia no JobUpdate, então precisa delas — não
            -- pode apagar o que o painel gravou.
            ctx.new_job_env_seed = json.encode({
                env_vars = job.env_vars or json.array({}),
                env_comments = job.env_comments or json.array({}),
            })
            ctx.new_job_step = "form"
            ctx.new_job_name = job.name or ""
            ctx.new_job_main_service = job.main_service or ""
            ctx.new_job_enabled = job.enabled and "true" or "false"

            if job.git_source then
                ctx.new_job_source = "git"
                ctx.new_job_git_provider_id = job.git_source.provider_id or ""
                ctx.new_job_git_branch = job.git_source.branch or ""
                ctx.new_job_compose_path = job.git_source.compose_path
                    or "docker-compose.yml"
                -- new_job_git_repo já vem semeado (resolvido por
                -- open_edit_job_window a partir de git_source.url).
            else
                ctx.new_job_compose = job.compose or ""
            end

            local kind, hours, hour, minute, weekday =
                unpack_recurrence(job.recurrence)
            ctx.new_job_kind = kind
            ctx.new_job_hours = hours
            ctx.new_job_time = format.hour_minute_join(hour, minute)
            ctx.new_job_weekday = weekday
        end
    end
end

-- ── Variáveis do job já na criação ──────────────────────────────────────────
-- O job ainda não existe, então as variáveis ficam numa lista local e vão no
-- próprio JobCreate (`env_vars`). A chave e o valor de cada linha são campos
-- sem borda que mudam a lista na hora — nada é gravado até "Criar job". "usar
-- secret" escolhe um secret do serviço gatilho ou do projeto (os do próprio
-- job só existem depois de criado: o passo seguinte cuida deles).

type DraftEnv = { key: string, value: string, secret: string? }
local draft_env: { DraftEnv } = {}

local function draft_env_publish(): ()
    local rows = {}
    for index, env_var in ipairs(draft_env) do
        local base = "new_job_env_row_" .. tostring(index)
        ctx[base .. "_key"] = env_var.key
        ctx[base .. "_value"] = env_var.value
        table.insert(rows, {
            index = tostring(index),
            key = env_var.key,
            secret = env_var.secret or "",
            is_secret = env_var.secret ~= nil and "true" or "false",
            bind_key = base .. "_key",
            bind_value = base .. "_value",
        })
    end
    ctx.new_job_env_rows = json.encode(json.array(rows))
    ctx.new_job_env_count = tostring(#draft_env)
end

-- Os secrets que a variável pode usar, na ordem em que o daemon procura:
-- serviço gatilho, projeto.
local function draft_env_secret_options(): ()
    local api = client()
    local options = {}
    local seen: { [string]: boolean } = {}
    local function add(service_id: string?, suffix: string): ()
        if not api then
            return
        end
        local ok, response = api:rpc {
            SecretList = {
                project_id = ctx.new_job_project_id,
                service_id = service_id,
            },
        }
        if
            ok
            and type(response) == "table"
            and type(response.SecretNames) == "table"
        then
            for _, name in ipairs(response.SecretNames) do
                if not seen[name] then
                    seen[name] = true
                    table.insert(
                        options,
                        { name = name, label = name .. suffix }
                    )
                end
            end
        end
    end
    if (ctx.new_job_service_id or "") ~= "" then
        add(ctx.new_job_service_id, i18n.tr(" (serviço)"))
    end
    add(nil, i18n.tr(" (projeto)"))
    ctx.new_job_env_secret_options = json.encode(json.array(options))
end

function draft_env_start(): ()
    draft_env = {}
    ctx.new_job_env_key = ""
    ctx.new_job_env_value = ""
    ctx.new_job_env_is_secret = "false"
    draft_env_publish()
    draft_env_secret_options()
end

function new_job_env_use_secret(value: any): ()
    ctx.new_job_env_is_secret = Helpers.is_true(value) and "true" or "false"
    ctx.new_job_env_value = ""
end

function new_job_env_add(): ()
    local key = Helpers.trim(ctx.new_job_env_key)
    local value = ctx.new_job_env_value or ""
    if key == "" then
        toast { message = i18n.tr("Informe a chave (KEY)"), kind = "warning" }
        return
    end
    local secret: string? = nil
    if Helpers.is_true(ctx.new_job_env_is_secret) then
        secret = Helpers.trim(value)
        if secret == "" then
            toast { message = i18n.tr("escolha um secret"), kind = "warning" }
            return
        end
        value = ""
    end
    -- A mesma chave duas vezes: a nova substitui a antiga, como no painel de
    -- um job já criado.
    local kept: { DraftEnv } = {}
    for _, env_var in ipairs(draft_env) do
        if env_var.key ~= key then
            table.insert(kept, env_var)
        end
    end
    table.insert(kept, { key = key, value = value, secret = secret })
    draft_env = kept
    ctx.new_job_env_key = ""
    ctx.new_job_env_value = ""
    ctx.new_job_env_is_secret = "false"
    draft_env_publish()
end

function new_job_env_delete(index: string): ()
    local position = tonumber(index)
    if position and draft_env[position] then
        table.remove(draft_env, position)
        draft_env_publish()
    end
end

function new_job_env_row_key(index: string, value: string): ()
    local env_var = draft_env[tonumber(index) or 0]
    if env_var then
        env_var.key = value or ""
        ctx["new_job_env_row_" .. index .. "_key"] = env_var.key
    end
end

function new_job_env_row_value(index: string, value: string): ()
    local env_var = draft_env[tonumber(index) or 0]
    if env_var then
        env_var.value = value or ""
        ctx["new_job_env_row_" .. index .. "_value"] = env_var.value
    end
end

-- As linhas como o JobCreate as quer (`{ key, value = { Plain } | { Secret }
-- }`); chave vazia sai.
local function draft_env_vars(): any
    local vars = json.array({})
    for _, env_var in ipairs(draft_env) do
        local key = Helpers.trim(env_var.key)
        if key ~= "" then
            table.insert(vars, {
                key = key,
                value = env_var.secret and { Secret = env_var.secret }
                    or { Plain = env_var.value },
            })
        end
    end
    return vars
end

-- onChange dos inputs (mesma convenção `field:<chave>` do app principal).
function field(key: string?, value: string?): ()
    if key then
        ctx[key] = value or ""
    end
end

-- ── Fonte do compose: Compose (colado) x Git (picker conta→repo→branch) ──
-- Idêntico a gitea_provider_pick/gitea_repo_pick de handlers/services.luau,
-- só que dentro desta janela isolada (não pode buscar no init(), mas ações
-- despachadas por clique/on_change chegam ao executor normalmente).

function new_job_source(kind: string): ()
    ctx.new_job_source = kind
    if kind == "git" and Helpers.list_is_empty(ctx.new_job_git_providers) then
        local api = client()
        if not api then
            return
        end
        ctx.new_job_git_message = i18n.tr("carregando contas…")
        ctx.new_job_git_busy = "true"
        local git_provider_list_ok, git_provider_list_response =
            api:rpc("GitProviderList")
        ctx.new_job_git_busy = ""
        if
            git_provider_list_ok and git_provider_list_response.GitProviders
        then
            ctx.new_job_git_providers =
                format.git_providers(git_provider_list_response.GitProviders)
            ctx.new_job_git_message = ""
        else
            ctx.new_job_git_message =
                i18n.tr("erro ao listar contas conectadas")
        end
    end
end

function new_job_git_provider_pick(provider_id: string): ()
    ctx.new_job_git_provider_id = provider_id or ""
    ctx.new_job_git_repo = ""
    ctx.new_job_git_repos = json.array({})
    ctx.new_job_git_branches = json.array({})
    local api = client()
    if not api or ctx.new_job_git_provider_id == "" then
        return
    end
    ctx.new_job_git_message = i18n.tr("carregando repositórios…")
    ctx.new_job_git_busy = "true"
    local git_repo_list_ok, git_repo_list_response = api:rpc {
        GitRepoList = { provider_id = ctx.new_job_git_provider_id },
    }
    ctx.new_job_git_busy = ""
    if git_repo_list_ok and git_repo_list_response.GitRepos then
        ctx.new_job_git_repos =
            format.git_repos(git_repo_list_response.GitRepos)
        ctx.new_job_git_message = tostring(#git_repo_list_response.GitRepos)
            .. i18n.tr(" repositório(s)")
    else
        ctx.new_job_git_message = i18n.tr("erro ao listar repositórios")
    end
end

function new_job_git_repo_pick(full_name: string): ()
    if not full_name then
        return
    end
    ctx.new_job_git_repo = full_name
    local json_decode_ok, repos = Helpers.decode_list(ctx.new_job_git_repos)
    if json_decode_ok and type(repos) == "table" then
        for _, repo in ipairs(repos) do
            if
                repo.full_name == full_name
                and repo.default_branch
                and repo.default_branch ~= ""
            then
                ctx.new_job_git_branch = repo.default_branch
                break
            end
        end
    end
    ctx.new_job_git_branches = json.array({})
    local provider_id = ctx.new_job_git_provider_id or ""
    local api = client()
    if not api or provider_id == "" then
        return
    end
    ctx.new_job_git_message = i18n.tr("carregando branches…")
    ctx.new_job_git_busy = "true"
    local git_branch_list_ok, git_branch_list_response = api:rpc {
        GitBranchList = {
            provider_id = provider_id,
            repo_full_name = full_name,
        },
    }
    ctx.new_job_git_busy = ""
    if git_branch_list_ok and git_branch_list_response.GitBranches then
        ctx.new_job_git_branches =
            format.git_branches(git_branch_list_response.GitBranches)
        ctx.new_job_git_message = ""
    else
        ctx.new_job_git_message = i18n.tr("erro ao listar branches")
    end
end

function new_job_pick_project(project_id: string): ()
    ctx.new_job_project_id = project_id
    local name = ""
    for _, new_job_project in ipairs(decode(ctx.new_job_projects)) do
        if new_job_project.id == project_id then
            name = new_job_project.name
        end
    end
    ctx.new_job_project_name = name

    local filtered = {}
    for _, service in ipairs(decode(ctx.new_job_services_all)) do
        if service.project_id == project_id then
            table.insert(filtered, service)
        end
    end
    -- `json.array`: sem ele um projeto sem serviços sairia como `{}` (objeto),
    -- e o for-each do passo seguinte espera um array (ver Util.encode_array).
    ctx.new_job_services_filtered = json.encode(json.array(filtered))
    ctx.new_job_step = "pick_service"
end

function new_job_pick_service(service_id: string): ()
    ctx.new_job_service_id = service_id
    local name = ""
    for _, service in ipairs(decode(ctx.new_job_services_filtered)) do
        if service.id == service_id then
            name = service.name
        end
    end
    ctx.new_job_service_name = name
    ctx.new_job_step = "form"
    draft_env_start()
end

-- Job 100% autônomo: sem serviço gatilho, só as env vars do projeto.
function new_job_pick_no_service(): ()
    ctx.new_job_service_id = ""
    ctx.new_job_service_name = i18n.tr("nenhum (autônomo)")
    ctx.new_job_step = "form"
    draft_env_start()
end

function new_job_back(): ()
    -- Modo edição: não há passos 1/2 pra voltar (projeto/serviço gatilho não
    -- são editáveis via JobUpdate) — "Voltar" fecha a janela.
    if ctx.new_job_edit_id ~= "" then
        close_window()
        return
    end
    if ctx.new_job_step == "form" then
        ctx.new_job_step = "pick_service"
    elseif ctx.new_job_step == "pick_service" then
        ctx.new_job_step = "pick_project"
    end
end

function new_job_kind(kind_choice: string): ()
    ctx.new_job_kind = kind_choice
end

-- Órfão desde que o seletor de dia da semana virou um <radiogroup> — mesma
-- história do `docker_cleanup_weekday` em handlers/settings.luau.
-- function new_job_weekday(w: string): ()
--     ctx.new_job_weekday = w
-- end

function new_job_create(): ()
    local api = client()
    if not api then
        ctx.new_job_error =
            i18n.tr("sem conexão — reabra a janela pelo app")
        return
    end
    local name = Helpers.trim(ctx.new_job_name)
    if name == "" then
        ctx.new_job_error = i18n.tr("informe um nome")
        return
    end
    local main_service = Helpers.trim(ctx.new_job_main_service)
    if main_service == "" then
        ctx.new_job_error = i18n.tr(
            "informe o main_service (nome do serviço dentro do compose)"
        )
        return
    end

    local compose = ""
    local git_source: any = nil
    if ctx.new_job_source == "git" then
        local branch = Helpers.trim(ctx.new_job_git_branch)
        if ctx.new_job_git_repo == "" or branch == "" then
            ctx.new_job_error = i18n.tr("selecione repositório e branch")
            return
        end
        local compose_path = Helpers.trim(ctx.new_job_compose_path)
        if compose_path == "" then
            compose_path = "docker-compose.yml"
        end
        -- URL de clone vem da lista de repos já carregada (mesma resolução
        -- de gitea_repo_pick em handlers/services.luau).
        local url = ""
        local json_decode_ok, repos =
            Helpers.decode_list(ctx.new_job_git_repos)
        if json_decode_ok and type(repos) == "table" then
            for _, repo in ipairs(repos) do
                if repo.full_name == ctx.new_job_git_repo then
                    url = repo.clone_url or ""
                    break
                end
            end
        end
        if url == "" then
            ctx.new_job_error = i18n.tr(
                "não foi possível resolver a URL do repositório — selecione "
                    .. "de novo"
            )
            return
        end
        git_source = {
            provider_id = ctx.new_job_git_provider_id ~= ""
                    and ctx.new_job_git_provider_id
                or nil,
            url = url,
            branch = branch,
            username = nil,
            credentials = nil,
            compose_path = compose_path,
        }
    else
        compose = ctx.new_job_compose or ""
        if Helpers.trim(compose) == "" then
            ctx.new_job_error = i18n.tr("cole o docker-compose.yml do job")
            return
        end
    end
    ctx.new_job_error = ""

    -- O caminho de volta do <timeedit>: a chave única "HH:MM" vira os dois
    -- campos que Recurrence::Daily/Weekly declaram no daemon.
    local hour, minute = format.hour_minute_split(ctx.new_job_time)
    local recurrence: any = nil
    if ctx.new_job_kind == "interval" then
        recurrence =
            { IntervalHours = math.max(1, tonumber(ctx.new_job_hours) or 1) }
    elseif ctx.new_job_kind == "daily" then
        recurrence = {
            Daily = {
                hour = hour,
                minute = minute,
            },
        }
    elseif ctx.new_job_kind == "weekly" then
        recurrence = {
            Weekly = {
                weekday = tonumber(ctx.new_job_weekday) or 0,
                hour = hour,
                minute = minute,
            },
        }
    end

    local editing = ctx.new_job_edit_id ~= ""
    -- Envs: na criação, as da lista local (o passo seguinte cuida dos secrets
    -- do job); na edição, as mais recentes (do painel, se foi aberto; senão,
    -- as do job como vieram).
    local env_vars: any = json.array({})
    local env_comments: any = json.array({})
    if not editing then
        env_vars = draft_env_vars()
    end
    if editing then
        local current = Core.job()
        if current then
            env_vars = current.env_vars or env_vars
            env_comments = current.env_comments or env_comments
        else
            local seed_ok, seed =
                pcall(json.decode, ctx.new_job_env_seed or "")
            if seed_ok and type(seed) == "table" then
                env_vars = seed.env_vars or env_vars
                env_comments = seed.env_comments or env_comments
            end
        end
    end

    ctx.new_job_message = editing and i18n.tr("salvando…")
        or i18n.tr("criando…")
    ctx.new_job_busy = "true"
    local save_ok, save_response
    if editing then
        save_ok, save_response = api:rpc_checked {
            JobUpdate = {
                id = ctx.new_job_edit_id,
                name = name,
                compose = compose,
                git_source = git_source,
                main_service = main_service,
                env_vars = env_vars,
                env_comments = env_comments,
                enabled = Helpers.is_true(ctx.new_job_enabled),
                recurrence = recurrence,
            },
        }
    else
        save_ok, save_response = api:rpc_checked {
            JobCreate = {
                project_id = ctx.new_job_project_id,
                trigger_service_id = ctx.new_job_service_id,
                name = name,
                compose = compose,
                git_source = git_source,
                main_service = main_service,
                env_vars = env_vars,
                env_comments = env_comments,
                recurrence = recurrence,
            },
        }
    end
    ctx.new_job_busy = ""
    if not save_ok then
        ctx.new_job_message = ""
        ctx.new_job_error = "erro: " .. tostring(save_response)
        return
    end

    local job = (type(save_response) == "table" and save_response.Job) or {}
    broadcast(
        editing and "job_updated" or "job_created",
        { id = job.id, name = job.name or name }
    )
    if not editing and job.id then
        -- Criado: segue para as variáveis e secrets do job (o `job_id` agora
        -- existe).
        ctx.new_job_message = ""
        ctx.new_job_created_id = job.id
        open_env_step(job.id, ctx.new_job_project_id)
        return
    end
    close_window()
end

-- ── Passo "env": variáveis e secrets do job (painel compartilhado) ──────────

function open_env_step(job_id: string, project_id: string): ()
    Core.setup { api = client(), project_id = project_id, job_id = job_id }
    Core.reset_forms()
    ctx.job_env_job_id = job_id
    ctx.job_env_project_id = project_id
    ctx.new_job_step = "env"
    Core.load()
end

-- "🔑 Variáveis e secrets" no formulário de EDIÇÃO.
function new_job_open_env(): ()
    if ctx.new_job_edit_id == "" then
        return
    end
    open_env_step(ctx.new_job_edit_id, ctx.new_job_project_id)
end

-- Do painel de volta ao formulário (só na edição; na criação o job já foi
-- salvo e só resta fechar).
function new_job_env_back(): ()
    Core.reset_forms()
    ctx.new_job_step = "form"
end

function cancel(): ()
    close_window()
end

-- Trava de ação em andamento (ver busy.luau): por último, com todas as funções
-- já definidas.
require("busy").install(require("busy_actions"))