feat(ui): per-service config in the deploy wizard's CONFIGURATION step

Setting a password, banner or TLS material AFTER deployment forces a
container recreate on every change. The deploy wizard now lets the
operator set service config up-front so the initial build has the
right env from the start.

Mechanics:
- Extracted the schema-driven field rendering out of ServiceConfigForm
  into a standalone ServiceConfigFields component (no API/buttons,
  just inputs + onChange).  ServiceConfigForm now delegates to it.
- Wizard step 2 (CONFIGURATION) renders one accordion block per
  selected service; clicking a service reveals its schema-driven
  inputs and a 'N set' badge tracks how many overrides are populated.
  Removing a service (back to step 1) drops its config so the INI
  doesn't carry orphans.
- _buildIni emits one [<prefix>.<svc>] group subsection per service
  with at least one override.  The INI loader's prefix-matcher
  applies it to every ${prefix}-NN decky in the batch, so one block
  covers all clones.
- Multi-line string values (PEM textareas etc.) are escaped as \n
  on the way into INI; downstream consumers re-expand.
This commit is contained in:
2026-04-29 12:08:17 -04:00
parent 97260daf8d
commit d8fa7cc73d
4 changed files with 400 additions and 206 deletions

View File

@@ -1,25 +1,16 @@
import React, { useEffect, useMemo, useState } from 'react';
import React, { useMemo, useState } from 'react';
import api from '../utils/api';
import { useToast } from './Toasts/useToast';
import ServiceConfigFields, {
type FormState,
type SchemaResponse,
buildInitial,
compactPayload,
fmtSchemaError,
} from './ServiceConfigFields';
import './ServiceConfigForm.css';
export interface ServiceConfigFieldDTO {
key: string;
label: string;
type: 'string' | 'password' | 'int' | 'bool' | 'textarea' | 'enum';
default?: unknown;
secret?: boolean;
help?: string | null;
enum?: string[] | null;
placeholder?: string | null;
}
interface SchemaResponse {
name: string;
ports: number[];
fleet_singleton: boolean;
fields: ServiceConfigFieldDTO[];
}
export type { ServiceConfigFieldDTO } from './ServiceConfigFields';
interface Props {
/** Decky the service runs on. */
@@ -34,67 +25,19 @@ interface Props {
onApplied?: (cfg: Record<string, unknown>, recreated: boolean) => void;
}
type FormValue = string | number | boolean;
type FormState = Record<string, FormValue>;
function toFormValue(field: ServiceConfigFieldDTO, raw: unknown): FormValue {
if (raw === undefined || raw === null) {
if (field.type === 'bool') return Boolean(field.default);
if (field.type === 'int') return field.default == null ? '' as unknown as number : Number(field.default);
return (field.default as string | undefined) ?? '';
}
if (field.type === 'bool') return Boolean(raw);
if (field.type === 'int') return Number(raw);
return String(raw);
}
function buildInitial(
fields: ServiceConfigFieldDTO[], current: Record<string, unknown>,
): FormState {
const out: FormState = {};
for (const f of fields) out[f.key] = toFormValue(f, current[f.key]);
return out;
}
const fmtError = (err: unknown, fallback: string): string =>
(err as { response?: { data?: { detail?: string } } })?.response?.data?.detail
?? fallback;
const ServiceConfigForm: React.FC<Props> = ({
deckyName, serviceSlug, topologyId, currentConfig, onApplied,
}) => {
const { push } = useToast();
const [schema, setSchema] = useState<SchemaResponse | null>(null);
const [loadErr, setLoadErr] = useState<string | null>(null);
const [form, setForm] = useState<FormState>({});
const [initial, setInitial] = useState<FormState>({});
const [busy, setBusy] = useState<'save' | 'apply' | null>(null);
const [revealed, setRevealed] = useState<Record<string, boolean>>({});
// Fetch schema only when the slug changes. currentConfig is a fresh
// object literal from the parent on every render — depending on it
// here would re-fetch the schema on every render.
useEffect(() => {
let cancelled = false;
setSchema(null);
setLoadErr(null);
api.get<SchemaResponse>(`/topologies/services/${encodeURIComponent(serviceSlug)}/schema`)
.then(({ data }) => {
if (cancelled) return;
setSchema(data);
})
.catch((err) => {
if (cancelled) return;
setLoadErr(fmtError(err, 'Schema load failed.'));
});
return () => { cancelled = true; };
}, [serviceSlug]);
// Seed form values from currentConfig once the schema is in hand.
// Keyed on JSON of the current cfg so a real change reseeds, but a
// referentially-new-but-equal object doesn't.
// Reseed form values when currentConfig changes meaningfully (by JSON
// identity, not reference — parents pass fresh `{}` literals).
const seedKey = useMemo(() => JSON.stringify(currentConfig ?? {}), [currentConfig]);
useEffect(() => {
React.useEffect(() => {
if (!schema) return;
const init = buildInitial(schema.fields, currentConfig ?? {});
setForm(init);
@@ -108,45 +51,31 @@ const ServiceConfigForm: React.FC<Props> = ({
return false;
}, [form, initial]);
const buildPayload = (): Record<string, unknown> => {
if (!schema) return {};
const out: Record<string, unknown> = {};
for (const f of schema.fields) {
const v = form[f.key];
// Skip empty strings on optional fields — server-side validate_cfg
// drops them anyway, but sending them risks surprising users when
// the round-trip echoes a missing key.
if (v === '' || v === undefined || v === null) continue;
out[f.key] = v;
}
return out;
};
const baseUrl = topologyId
? `/topologies/${encodeURIComponent(topologyId)}/deckies/${encodeURIComponent(deckyName)}/services/${encodeURIComponent(serviceSlug)}`
: `/deckies/${encodeURIComponent(deckyName)}/services/${encodeURIComponent(serviceSlug)}`;
const save = async () => {
if (busy) return;
if (busy || !schema) return;
setBusy('save');
try {
const { data } = await api.put<{ config: Record<string, unknown>; recreated: boolean }>(
`${baseUrl}/config`, { config: buildPayload() },
`${baseUrl}/config`, { config: compactPayload(schema.fields, form) },
);
const next = buildInitial(schema!.fields, data.config);
const next = buildInitial(schema.fields, data.config);
setForm(next);
setInitial(next);
onApplied?.(data.config, false);
push({ text: `${serviceSlug} config saved (no restart).`, tone: 'matrix' });
} catch (err) {
push({ text: fmtError(err, 'Save failed.'), tone: 'alert' });
push({ text: fmtSchemaError(err, 'Save failed.'), tone: 'alert' });
} finally {
setBusy(null);
}
};
const apply = async () => {
if (busy) return;
if (busy || !schema) return;
const ok = window.confirm(
`Apply ${serviceSlug} config on ${deckyName}?\n\n` +
`This force-recreates the ${deckyName}-${serviceSlug} container so the new ` +
@@ -156,130 +85,51 @@ const ServiceConfigForm: React.FC<Props> = ({
setBusy('apply');
try {
const { data } = await api.post<{ config: Record<string, unknown>; recreated: boolean }>(
`${baseUrl}/apply`, { config: buildPayload() },
`${baseUrl}/apply`, { config: compactPayload(schema.fields, form) },
);
const next = buildInitial(schema!.fields, data.config);
const next = buildInitial(schema.fields, data.config);
setForm(next);
setInitial(next);
onApplied?.(data.config, true);
push({ text: `${serviceSlug} applied — container recreated.`, tone: 'matrix' });
} catch (err) {
push({ text: fmtError(err, 'Apply failed.'), tone: 'alert' });
push({ text: fmtSchemaError(err, 'Apply failed.'), tone: 'alert' });
} finally {
setBusy(null);
}
};
if (loadErr) {
return <div className="svc-cfg-status alert-text">{loadErr}</div>;
}
if (!schema) {
return <div className="svc-cfg-status">Loading schema</div>;
}
if (schema.fields.length === 0) {
return (
<div className="svc-cfg-status">
No customizable fields for {schema.name}.
</div>
);
}
return (
<div className="service-config-form">
{schema.fields.map((f) => {
const id = `svc-cfg-${deckyName}-${serviceSlug}-${f.key}`;
const value = form[f.key];
const setVal = (v: FormValue) => setForm((s) => ({ ...s, [f.key]: v }));
const help = f.help ? <div className="dim svc-cfg-help">{f.help}</div> : null;
return (
<div key={f.key} className="svc-cfg-row">
<label htmlFor={id} className="svc-cfg-label">
{f.label}
{f.secret && <span className="dim svc-cfg-secret-tag"> · secret</span>}
</label>
{f.type === 'bool' ? (
<input
id={id}
type="checkbox"
checked={Boolean(value)}
onChange={(e) => setVal(e.target.checked)}
/>
) : f.type === 'enum' ? (
<select
id={id}
value={String(value ?? '')}
onChange={(e) => setVal(e.target.value)}
className="svc-cfg-input"
>
<option value=""></option>
{(f.enum ?? []).map((opt) => (
<option key={opt} value={opt}>{opt}</option>
))}
</select>
) : f.type === 'textarea' ? (
<textarea
id={id}
value={String(value ?? '')}
onChange={(e) => setVal(e.target.value)}
placeholder={f.placeholder ?? ''}
rows={3}
className="svc-cfg-input"
/>
) : f.type === 'password' ? (
<div className="svc-cfg-pw-wrap">
<input
id={id}
type={revealed[f.key] ? 'text' : 'password'}
value={String(value ?? '')}
onChange={(e) => setVal(e.target.value)}
placeholder={f.placeholder ?? ''}
className="svc-cfg-input"
/>
<button
type="button"
className="svc-cfg-pw-toggle"
onClick={() => setRevealed((s) => ({ ...s, [f.key]: !s[f.key] }))}
>
{revealed[f.key] ? 'HIDE' : 'SHOW'}
</button>
</div>
) : (
<input
id={id}
type={f.type === 'int' ? 'number' : 'text'}
value={String(value ?? '')}
onChange={(e) =>
setVal(f.type === 'int' && e.target.value !== ''
? Number(e.target.value)
: e.target.value)}
placeholder={f.placeholder ?? ''}
className="svc-cfg-input"
/>
)}
{help}
</div>
);
})}
<div className="svc-cfg-actions">
{dirty && <span className="svc-cfg-dirty-tag">UNSAVED</span>}
<button
type="button"
className="svc-cfg-btn"
disabled={!dirty || !!busy}
onClick={save}
>
{busy === 'save' ? 'SAVING…' : 'SAVE'}
</button>
<button
type="button"
className="svc-cfg-btn violet"
disabled={!!busy}
onClick={apply}
title="Persist + force-recreate the service container."
>
{busy === 'apply' ? 'APPLYING…' : 'APPLY'}
</button>
</div>
<ServiceConfigFields
serviceSlug={serviceSlug}
value={form}
onChange={setForm}
idScope={`${deckyName}-${serviceSlug}`}
onSchema={setSchema}
/>
{schema && schema.fields.length > 0 && (
<div className="svc-cfg-actions">
{dirty && <span className="svc-cfg-dirty-tag">UNSAVED</span>}
<button
type="button"
className="svc-cfg-btn"
disabled={!dirty || !!busy}
onClick={save}
>
{busy === 'save' ? 'SAVING…' : 'SAVE'}
</button>
<button
type="button"
className="svc-cfg-btn violet"
disabled={!!busy}
onClick={apply}
title="Persist + force-recreate the service container."
>
{busy === 'apply' ? 'APPLYING…' : 'APPLY'}
</button>
</div>
)}
</div>
);
};