diff --git a/web/src/components/settings/SecretField.test.tsx b/web/src/components/settings/SecretField.test.tsx index 88bc5b3dca..ef8dbea5bb 100644 --- a/web/src/components/settings/SecretField.test.tsx +++ b/web/src/components/settings/SecretField.test.tsx @@ -110,7 +110,7 @@ describe("SecretField", () => { expect(onChange).toHaveBeenCalledWith(""); }); - it("does not treat an empty input as a keep while nothing is saved", async () => { + it("goes back to nothing staged when an input with nothing saved is emptied", async () => { const user = userEvent.setup(); const onChange = vi.fn(); const onKeep = vi.fn(); @@ -119,8 +119,8 @@ describe("SecretField", () => { const input = screen.getByLabelText("Secret key"); await user.type(input, "x"); await user.clear(input); - expect(onKeep).not.toHaveBeenCalled(); - expect(onChange).toHaveBeenCalledWith(""); + expect(onKeep).toHaveBeenCalled(); + expect(onChange).not.toHaveBeenCalledWith(""); }); it("offers no clear action while the field is read-only", () => { diff --git a/web/src/components/settings/SecretField.tsx b/web/src/components/settings/SecretField.tsx index edb25711b1..8c7dbe457e 100644 --- a/web/src/components/settings/SecretField.tsx +++ b/web/src/components/settings/SecretField.tsx @@ -17,10 +17,11 @@ export interface SecretFieldProps { configured: boolean; onChange: (value: string) => void; /** - * Called when the input is emptied while a saved value exists, so a - * settings-form parent can revert the staged draft (`form.resetValue`) - * instead of staging `""` — a dirty `""` would clear the secret on save. - * Draft-based parents that already skip empty values may omit it. + * Called when the input is emptied, so a settings-form parent can revert the + * staged draft (`form.resetValue`) instead of staging `""`: a dirty `""` + * would clear a saved secret on save, and with none saved it would leave an + * empty change behind. Draft-based parents that already skip empty values + * may omit it. */ onKeep?: () => void; /** @@ -99,8 +100,9 @@ export function SecretField({ } function handleChange(next: string) { - if (next === "" && configured) { - // Emptying the field means "keep the saved secret", never "clear it". + if (next === "") { + // Emptying the field goes back to what is saved: it keeps a saved + // secret, never clears it, and with none saved it leaves nothing staged. keepSaved(); return; } diff --git a/web/src/hooks/useSettingsForm.test.ts b/web/src/hooks/useSettingsForm.test.ts index b2cf0f4978..12dc946657 100644 --- a/web/src/hooks/useSettingsForm.test.ts +++ b/web/src/hooks/useSettingsForm.test.ts @@ -7,8 +7,10 @@ import { useHasUnsavedChanges } from "./useUnsavedChanges"; import { useSettingsForm } from "./useSettingsForm"; import { useStepSubmit } from "@/pages/setup-wizard/useStep"; -const { mutateAsync, markDone, snapshot, authority } = vi.hoisted(() => ({ +const { mutateAsync, markDone, snapshot, authority, saveBaseline } = vi.hoisted(() => ({ mutateAsync: vi.fn(), + // The snapshot the next save is guarded against. + saveBaseline: { current: undefined as Record | undefined }, markDone: vi.fn(), snapshot: { loaded: true, values: undefined as Record | undefined }, authority: { profileId: "profile-a" }, @@ -29,7 +31,7 @@ vi.mock("@/api/client", () => ({ // would loop forever. const KEYS = ["branding.server_name", "database.max_connections"]; const settingsData = { "branding.server_name": "Silo", "database.max_connections": "20" }; -const sensitiveData = { configured: [], managed_by_env: [] }; +const sensitiveData = { configured: [] as string[], managed_by_env: [] }; vi.mock("@/hooks/queries/admin/settings", () => ({ useAdminServerSettings: () => ({ @@ -37,7 +39,10 @@ vi.mock("@/hooks/queries/admin/settings", () => ({ isLoading: false, }), useAdminSensitiveStatus: () => ({ data: sensitiveData }), - useUpdateServerSettings: () => ({ mutateAsync, isPending: false }), + useUpdateServerSettings: (baseline: Record | undefined) => { + saveBaseline.current = baseline; + return { mutateAsync, isPending: false }; + }, })); afterEach(() => { @@ -47,6 +52,7 @@ afterEach(() => { snapshot.loaded = true; snapshot.values = undefined; authority.profileId = "profile-a"; + sensitiveData.configured = []; }); describe("useSettingsForm save()", () => { @@ -339,10 +345,42 @@ describe("useSettingsForm unsaved-changes guard", () => { expect(registry.result.current).toBe(false); }); + it("guards the next save with the current snapshot after an edit is undone in place", () => { + const before = { "branding.server_name": "Silo" }; + snapshot.values = before; + const form = renderHook(() => + useSettingsForm({ keys: ["branding.server_name", "branding.accent_color"] }), + ); + + // The Default accent with none saved: nothing to stage. + act(() => { + form.result.current.setValue("branding.accent_color", ""); + }); + expect(form.result.current.dirtyCount).toBe(0); + + // Another write (a branding upload) moves the settings on. + const after = { "branding.server_name": "Silo", "branding.logo_ref": "logo" }; + snapshot.values = after; + form.rerender(); + act(() => { + form.result.current.setValue("branding.server_name", "Casa"); + }); + + expect(saveBaseline.current).toBe(after); + }); + it("releases an edit changed back to its saved value, but not a staged secret clear", () => { + sensitiveData.configured = ["email.smtp_password"]; const registry = renderHook(() => useHasUnsavedChanges()); const form = renderHook(() => - useSettingsForm({ keys: ["branding.server_name", "email.smtp_password"] }), + useSettingsForm({ + keys: [ + "branding.server_name", + "email.smtp_password", + "s3.public_read_endpoint", + "s3.public_token_secret", + ], + }), ); act(() => { @@ -354,7 +392,20 @@ describe("useSettingsForm unsaved-changes guard", () => { expect(form.result.current.dirtyCount).toBe(0); expect(registry.result.current).toBe(false); - // The snapshot leaves secrets out, so an empty secret is a clear to save. + // The snapshot leaves out a setting with nothing saved, secret or not, so + // emptying what was typed into one gets it back to its saved state. + for (const key of ["s3.public_read_endpoint", "s3.public_token_secret"]) { + act(() => { + form.result.current.setValue(key, "typed"); + }); + act(() => { + form.result.current.setValue(key, ""); + }); + } + expect(form.result.current.dirtyCount).toBe(0); + expect(registry.result.current).toBe(false); + + // It leaves out a set secret too, and emptying that is a clear to save. act(() => { form.result.current.setValue("email.smtp_password", ""); }); diff --git a/web/src/hooks/useSettingsForm.ts b/web/src/hooks/useSettingsForm.ts index 43307e3136..c991b05708 100644 --- a/web/src/hooks/useSettingsForm.ts +++ b/web/src/hooks/useSettingsForm.ts @@ -130,17 +130,13 @@ export function useSettingsForm({ keys }: UseSettingsFormOptions) { if (!editBaseline.current) editBaseline.current = settings; editVersions.current.set(key, (editVersions.current.get(key) ?? 0) + 1); setLocalValues((prev) => ({ ...prev, [key]: value })); - // The snapshot leaves secrets out, so a key it lacks (a staged secret - // clear among them) stays dirty. An edit made during a save, or before - // the snapshot that save wrote has arrived, stays dirty too, because the - // snapshot cannot yet say what is saved. + // An edit made during a save, or before the snapshot that save wrote has + // arrived, stays dirty, because the snapshot cannot yet say what is saved. const reverted = !stage && !savePending.current && - settings != null && settings !== savedOver.current && - Object.hasOwn(settings, key) && - settings[key] === value; + savedValue(settings, sensitiveData?.configured, key) === value; setDirty((prev) => { const next = new Set(prev); if (reverted) next.delete(key); @@ -148,7 +144,7 @@ export function useSettingsForm({ keys }: UseSettingsFormOptions) { return next; }); }, - [settings], + [sensitiveData, settings], ); // Revert one staged field without disturbing other edits. This is also how @@ -168,9 +164,12 @@ export function useSettingsForm({ keys }: UseSettingsFormOptions) { ); const dirtyCount = dirty.size; + // With nothing staged, the next edit starts its own baseline. This runs on + // every change of the set, so an edit undone in place (an emptied setting + // with nothing saved) doesn't leave the baseline on the snapshot it began on. useEffect(() => { - if (dirtyCount === 0) editBaseline.current = undefined; - }, [dirtyCount]); + if (dirty.size === 0) editBaseline.current = undefined; + }, [dirty]); const dirtyKeys = useMemo(() => Array.from(dirty), [dirty]); // The shared registry guards tab close and reload. `UnsavedChangesGuard` @@ -358,3 +357,21 @@ export function useSettingsForm({ keys }: UseSettingsFormOptions) { beginSettingsTransition, }; } + +/** + * What is saved for `key`, or undefined when the snapshot and the secret + * status can't say. A key the snapshot lacks has nothing saved, unless it is a + * set secret, which the snapshot leaves out; for that, or before the status + * (`configured`) has arrived, the saved value is unknown, and an empty draft is + * a clear to save. + */ +function savedValue( + settings: Record | undefined, + configured: string[] | undefined, + key: string, +): string | undefined { + if (settings == null) return undefined; + if (Object.hasOwn(settings, key)) return settings[key]; + if (configured == null || configured.includes(key)) return undefined; + return ""; +} diff --git a/web/src/pages/admin-settings/AISettings.tsx b/web/src/pages/admin-settings/AISettings.tsx index ede76aad5b..5207202822 100644 --- a/web/src/pages/admin-settings/AISettings.tsx +++ b/web/src/pages/admin-settings/AISettings.tsx @@ -54,9 +54,10 @@ const SPEECH_AI_KEYS = ["ai.speech_provider_id", "ai.asr_model"] as const; const EMBEDDING_KEYS = ["recommendations.embedding_provider_id", "recommendations.embedding_model"]; /** * Pre-`ai.*` keys still read as a fallback, so a server configured before the - * rename keeps its model and job limit until the modern key is saved. + * rename keeps its model until the modern key is saved. The server already + * reports the job limit under `ai.max_concurrent_jobs`. */ -const LEGACY_AI_KEYS = ["subtitle_ai.chat_model", "subtitle_ai.max_concurrent_jobs"] as const; +const LEGACY_AI_KEYS = ["subtitle_ai.chat_model"] as const; const AI_FEATURE_KEYS = [ "subtitle_ai.enabled", @@ -671,10 +672,6 @@ export default function AISettings() { } const value = (key: string, fallback = "") => form.getValue(key) || fallback; - // Legacy `subtitle_ai.*` values stay authoritative until the modern `ai.*` - // key holds something, exactly as the old AI Services tab read them. - const effectiveValue = (key: string, legacyKey: string, fallback: string) => - value(key, value(legacyKey, fallback)); const providers = providerList.data?.providers ?? []; const providerTypes = providerList.data?.types ?? []; @@ -801,13 +798,19 @@ export default function AISettings() { } async function save() { - const batchSize = parseStrictInteger(value("subtitle_ai.batch_size", "40")); - const contextLines = parseStrictInteger(value("subtitle_ai.context_neighbors", "2")); - const chunkSeconds = parseStrictInteger(value("subtitle_ai.asr_chunk_seconds", "600")); - const quotaJobs = parseStrictInteger(value("subtitle_ai.transcribe_quota_jobs", "0")); - const maxConcurrent = parseStrictInteger( - effectiveValue("ai.max_concurrent_jobs", "subtitle_ai.max_concurrent_jobs", "2"), - ); + // With no settings loaded there is nothing to save over, and the form's + // own save says to reload; checking the fields first would hide that. + if (!form.loaded) { + await form.save(); + return; + } + // Only a value this save sends is checked: an untouched field holds what + // the server has. + const invalidCount = (key: string, min: number, max = Number.MAX_SAFE_INTEGER) => { + if (!form.isDirty(key)) return false; + const parsed = parseStrictInteger(value(key)); + return parsed === null || parsed < min || parsed > max; + }; // None releases the text provider; it saves while nothing translates. const textCleared = authMode !== "chatgpt" && textProviderID === ""; @@ -830,23 +833,23 @@ export default function AISettings() { toast.error(t("web.admin.settings.ai.page.chooseReasoning")); return; } - if (maxConcurrent === null || maxConcurrent < 1) { + if (invalidCount("ai.max_concurrent_jobs", 1)) { toast.error(t("web.admin.settings.ai.page.maxConcurrentInvalid")); return; } - if (batchSize === null || batchSize < 1) { + if (invalidCount("subtitle_ai.batch_size", 1)) { toast.error(t("web.admin.settings.ai.page.batchSizeInvalid")); return; } - if (contextLines === null || contextLines < 0) { + if (invalidCount("subtitle_ai.context_neighbors", 0)) { toast.error(t("web.admin.settings.ai.page.contextLinesInvalid")); return; } - if (chunkSeconds === null || chunkSeconds < 60 || chunkSeconds > 600) { + if (invalidCount("subtitle_ai.asr_chunk_seconds", 60, 600)) { toast.error(t("web.admin.settings.ai.page.chunkInvalid")); return; } - if (quotaJobs === null || quotaJobs < 0) { + if (invalidCount("subtitle_ai.transcribe_quota_jobs", 0)) { toast.error(t("web.admin.settings.ai.page.quotaInvalid")); return; } @@ -1033,11 +1036,7 @@ export default function AISettings() { setValue("ai.max_concurrent_jobs", next)} // Each server process builds its own dispatch semaphore at start // (internal/api/router.go), so a cluster runs this many per process. @@ -1047,14 +1046,14 @@ export default function AISettings() { setValue("subtitle_ai.batch_size", next)} restartRequired={restartKeys.has("subtitle_ai.batch_size")} /> setValue("subtitle_ai.context_neighbors", next)} restartRequired={restartKeys.has("subtitle_ai.context_neighbors")} /> @@ -1062,7 +1061,7 @@ export default function AISettings() { label={t("web.admin.settings.ai.tuning.audioPerRequest")} type="number" unit={t("web.admin.settings.ai.unit.seconds")} - value={value("subtitle_ai.asr_chunk_seconds", "600")} + value={value("subtitle_ai.asr_chunk_seconds")} onChange={(next) => setValue("subtitle_ai.asr_chunk_seconds", next)} description={t("web.admin.settings.ai.tuning.audioPerRequestRange")} restartRequired={restartKeys.has("subtitle_ai.asr_chunk_seconds")} @@ -1074,7 +1073,7 @@ export default function AISettings() { > setValue("subtitle_ai.transcribe_quota_jobs", next)} fallbackValue="10" hint={t("web.admin.settings.ai.tuning.transcriptionsHint")} diff --git a/web/src/pages/admin-settings/GeneralSettings.tsx b/web/src/pages/admin-settings/GeneralSettings.tsx index aa9407e0d3..c864697f6d 100644 --- a/web/src/pages/admin-settings/GeneralSettings.tsx +++ b/web/src/pages/admin-settings/GeneralSettings.tsx @@ -53,6 +53,8 @@ export default function GeneralSettings() { const anyDirty = (keys: string[]) => keys.some((key) => form.isDirty(key)); const [saveInProgress, setSaveInProgress] = useState(false); const saveInProgressRef = useRef(false); + // Each save and discard ends the Use Redis switch's own choice. + const [savesAndDiscards, setSavesAndDiscards] = useState(0); // The Redis URL is a credential: its editors are frozen while a save is in // flight so a late keystroke cannot ride along with it. @@ -80,6 +82,7 @@ export default function GeneralSettings() { ? form.dirtyKeys.filter((key) => !REDIS_KEYS.includes(key)) : undefined, ); + setSavesAndDiscards((count) => count + 1); } finally { saveInProgressRef.current = false; setSaveInProgress(false); @@ -89,6 +92,8 @@ export default function GeneralSettings() { function handleDiscard() { if (saveInProgressRef.current) return; form.discard(); + // Discard clears nothing until the settings have loaded. + if (form.loaded) setSavesAndDiscards((count) => count + 1); } // Redis reads whether a URL is saved from the protected-credential status, @@ -228,7 +233,12 @@ export default function GeneralSettings() { ) : ( - + )} diff --git a/web/src/pages/admin-settings/LibraryMetadataSettings.tsx b/web/src/pages/admin-settings/LibraryMetadataSettings.tsx index da545c2fc0..f451cd2519 100644 --- a/web/src/pages/admin-settings/LibraryMetadataSettings.tsx +++ b/web/src/pages/admin-settings/LibraryMetadataSettings.tsx @@ -440,7 +440,7 @@ export default function LibraryMetadataSettings() { "web.admin.settings.libraryMetadata.subtitleSync.capacity.description", )} dirty={form.isDirty("subtitles.sync_node_capacity")} - value={form.getValue("subtitles.sync_node_capacity") || "1"} + value={form.getValue("subtitles.sync_node_capacity")} onChange={(value) => form.setValue("subtitles.sync_node_capacity", value)} restartRequired={restartKeys.has("subtitles.sync_node_capacity")} /> diff --git a/web/src/pages/admin-settings/NotificationsAdminSettings.tsx b/web/src/pages/admin-settings/NotificationsAdminSettings.tsx index 7d0a74ea9c..ea95322747 100644 --- a/web/src/pages/admin-settings/NotificationsAdminSettings.tsx +++ b/web/src/pages/admin-settings/NotificationsAdminSettings.tsx @@ -877,9 +877,6 @@ export default function NotificationsAdminSettings() { const isOn = (key: string) => toggleValue(key) === "true"; const setToggle = (key: string) => (value: boolean) => form.setValue(key, value ? "true" : "false"); - // Numeric settings fall back to their server-side defaults when unset; - // surface the effective default instead of an empty input. - const numberValue = (key: string, fallback: string) => form.getValue(key) || fallback; const needsRestart = (key: string) => restartKeys.has(key); const anyDirty = (keys: string[]) => keys.some(form.isDirty); @@ -1107,7 +1104,7 @@ export default function NotificationsAdminSettings() { description={t("web.admin.settings.notifications.digestHourDescription")} unit={t("web.admin.common.units.hourRange")} type="number" - value={numberValue("notifications.email.digest_hour", "8")} + value={form.getValue("notifications.email.digest_hour")} onChange={(v) => form.setValue("notifications.email.digest_hour", v)} restartRequired={needsRestart("notifications.email.digest_hour")} /> @@ -1184,7 +1181,7 @@ export default function NotificationsAdminSettings() { description={t("web.admin.settings.notifications.digestHourDescription")} unit={t("web.admin.common.units.hourRange")} type="number" - value={numberValue("notifications.discord.digest_hour", "8")} + value={form.getValue("notifications.discord.digest_hour")} onChange={(v) => form.setValue("notifications.discord.digest_hour", v)} restartRequired={needsRestart("notifications.discord.digest_hour")} /> @@ -1214,7 +1211,7 @@ export default function NotificationsAdminSettings() { form.setValue("notifications.webhooks.max_per_profile", v)} restartRequired={needsRestart("notifications.webhooks.max_per_profile")} /> @@ -1226,10 +1223,7 @@ export default function NotificationsAdminSettings() { description={t("web.admin.settings.notifications.webhooks.deliveriesDescription")} unit={t("web.admin.settings.notifications.webhooks.perMinute")} type="number" - value={numberValue( - "notifications.webhooks.deliveries_per_minute_per_profile", - "60", - )} + value={form.getValue("notifications.webhooks.deliveries_per_minute_per_profile")} onChange={(v) => form.setValue("notifications.webhooks.deliveries_per_minute_per_profile", v) } @@ -1299,7 +1293,7 @@ export default function NotificationsAdminSettings() { )} unit={t("web.admin.settings.notifications.unit.seconds")} type="number" - value={numberValue("notifications.server_channels.batch_seconds", "300")} + value={form.getValue("notifications.server_channels.batch_seconds")} onChange={(v) => form.setValue("notifications.server_channels.batch_seconds", v)} restartRequired={needsRestart("notifications.server_channels.batch_seconds")} /> diff --git a/web/src/pages/admin-settings/RedisGroup.test.tsx b/web/src/pages/admin-settings/RedisGroup.test.tsx index 6795d4f6e6..0d63f05795 100644 --- a/web/src/pages/admin-settings/RedisGroup.test.tsx +++ b/web/src/pages/admin-settings/RedisGroup.test.tsx @@ -7,7 +7,8 @@ import { useSettingsForm } from "@/hooks/useSettingsForm"; import { RedisGroup } from "./RedisGroup"; import { REDIS_KEYS } from "./redisDraft"; -const { sensitiveStatus } = vi.hoisted(() => ({ +const { serverSettings, sensitiveStatus } = vi.hoisted(() => ({ + serverSettings: { current: {} as Record }, sensitiveStatus: { current: {} as { configured: string[]; @@ -20,8 +21,7 @@ const { sensitiveStatus } = vi.hoisted(() => ({ vi.mock("@/hooks/queries/admin/settings", () => ({ // The snapshot never carries the URL; whether one is saved comes from the // protected-credential status. - // The server reports the number in use: 0 when the URL names none. - useAdminServerSettings: () => ({ data: { "redis.db": "0" }, isLoading: false }), + useAdminServerSettings: () => ({ data: serverSettings.current, isLoading: false }), useAdminSensitiveStatus: () => ({ data: sensitiveStatus.current, isError: false }), useUpdateServerSettings: () => ({ mutateAsync: vi.fn(), isPending: false }), useCheckAdminSettingsConnection: () => ({ mutateAsync: vi.fn(), isPending: false }), @@ -37,6 +37,7 @@ function Harness() { form={form} restartKeys={{ has: () => false }} secrets={{ keepSaved: form.resetValue, setSecret: form.setValue, disabled: false }} + savesAndDiscards={0} /> {/* Another setting on the same page, so an edit can stay staged. */} { beforeEach(() => { + // The server reports the number in use: 0 when the URL names none. + serverSettings.current = { "redis.db": "0" }; sensitiveStatus.current = { configured: [], managed_by_env: [] }; }); @@ -65,6 +68,39 @@ describe("RedisGroup", () => { expect(screen.getByText("0 staged")).toBeInTheDocument(); }); + it("keeps Use Redis on while a URL typed with nothing saved is erased", async () => { + render(); + const useRedis = screen.getByRole("switch", { name: "Use Redis" }); + + await userEvent.click(useRedis); + await userEvent.type(screen.getByLabelText("Connection URL"), "redis://cache:6379"); + await userEvent.clear(screen.getByLabelText("Connection URL")); + + // The admin is still in the field; the URL and the number staged with it + // are taken back. + expect(useRedis).toBeChecked(); + expect(screen.getByLabelText("Connection URL")).toHaveFocus(); + expect(screen.getByText("0 staged")).toBeInTheDocument(); + }); + + it.each([ + ["the database number", "Database number"], + ["another setting on the page", "Other setting"], + ])("keeps Use Redis on while %s is typed into and erased", async (_, field) => { + // With no URL and no number saved, the snapshot holds neither. + serverSettings.current = {}; + render(); + const useRedis = screen.getByRole("switch", { name: "Use Redis" }); + + await userEvent.click(useRedis); + await userEvent.type(screen.getByLabelText(field), "3"); + await userEvent.clear(screen.getByLabelText(field)); + + expect(useRedis).toBeChecked(); + expect(screen.getByLabelText("Connection URL")).toBeInTheDocument(); + expect(screen.getByText("0 staged")).toBeInTheDocument(); + }); + it("shows the connection REDIS_URL sets once it takes over a staged switch-off", async () => { sensitiveStatus.current = { configured: ["redis.url"], managed_by_env: [] }; const { rerender } = render(); diff --git a/web/src/pages/admin-settings/RedisGroup.tsx b/web/src/pages/admin-settings/RedisGroup.tsx index 8ae86067f5..272ae92143 100644 --- a/web/src/pages/admin-settings/RedisGroup.tsx +++ b/web/src/pages/admin-settings/RedisGroup.tsx @@ -30,10 +30,13 @@ export function RedisGroup({ form, restartKeys, secrets, + savesAndDiscards, }: { form: ReturnType; restartKeys: RestartKeyMatcher; secrets: RedisUrlEditors; + /** Counts the page's completed saves and its discards. */ + savesAndDiscards: number; }) { const t = useT(); const checkConnection = useCheckAdminSettingsConnection(); @@ -43,12 +46,14 @@ export function RedisGroup({ const configured = form.sensitiveConfigured.includes("redis.url"); const [enabledOverride, setEnabledOverride] = useState(null); // Saving or discarding clears the toggle override so it follows the stored - // URL again. Adjusting during render (rather than in an effect) keeps the - // override alive while the admin is still editing. - const [lastDirtyCount, setLastDirtyCount] = useState(form.dirtyCount); - if (lastDirtyCount !== form.dirtyCount) { - setLastDirtyCount(form.dirtyCount); - if (form.dirtyCount === 0) setEnabledOverride(null); + // URL again. Running out of unsaved changes is not the same: erasing what + // was typed into a field with nothing saved takes back its edit while the + // admin is still working. Adjusting during render (rather than in an effect) + // keeps the override alive while the admin is still editing. + const [lastSavesAndDiscards, setLastSavesAndDiscards] = useState(savesAndDiscards); + if (lastSavesAndDiscards !== savesAndDiscards) { + setLastSavesAndDiscards(savesAndDiscards); + setEnabledOverride(null); } // Once REDIS_URL sets the connection the switch is locked, so a choice // made before it took over no longer applies. diff --git a/web/src/pages/admin-settings/SearchSettings.tsx b/web/src/pages/admin-settings/SearchSettings.tsx index 42d169df05..55af4f5a7d 100644 --- a/web/src/pages/admin-settings/SearchSettings.tsx +++ b/web/src/pages/admin-settings/SearchSettings.tsx @@ -246,7 +246,7 @@ export default function SearchSettings() { <> form.setValue("catalog.search.meilisearch.index", value)} description={t("web.admin.settings.search.meili.index.description")} disabled={!meiliEnabled || connectionUnknown} @@ -257,7 +257,7 @@ export default function SearchSettings() { label={t("web.admin.settings.search.meili.timeout.label")} type="number" unit={t("web.admin.common.units.milliseconds")} - value={form.getValue("catalog.search.meilisearch.timeout_ms") || "800"} + value={form.getValue("catalog.search.meilisearch.timeout_ms")} onChange={(value) => form.setValue("catalog.search.meilisearch.timeout_ms", value) } @@ -268,7 +268,7 @@ export default function SearchSettings() { form.setValue("catalog.search.meilisearch.sync_batch_size", value) } @@ -279,7 +279,7 @@ export default function SearchSettings() { form.setValue("catalog.search.meilisearch.semantic_ratio", value) } diff --git a/web/src/pages/admin-settings/SettingField.tsx b/web/src/pages/admin-settings/SettingField.tsx index 2b31a4c26e..0a127c09eb 100644 --- a/web/src/pages/admin-settings/SettingField.tsx +++ b/web/src/pages/admin-settings/SettingField.tsx @@ -140,19 +140,28 @@ export function SettingFieldRow({ >
- {dirty ? ( - - ) : null} - + {/* The dot stays beside the label's first line when a long label + wraps: its box is one line of the label (text-sm) tall. */} + + {dirty ? ( + + + + ) : null} + + {restartRequired && !groupSaysRestart && }
{description ? ( -

+

{description}

) : null} @@ -197,7 +206,8 @@ interface SettingFieldProps { label: string; /** The field has an unsaved edit; drive it from `form.isDirty(key)`. */ dirty?: boolean; - type?: "text" | "number" | "password" | "toggle" | "duration" | "select"; + /** A secret uses `SecretField`, which keeps the saved value when emptied. */ + type?: "text" | "number" | "toggle" | "duration" | "select"; /** * Placeholder for `text`, description for every other type. Prefer * `description` for new call sites. @@ -212,7 +222,6 @@ interface SettingFieldProps { value: string; onChange: (value: string) => void; options?: SelectOption[]; - sensitiveConfigured?: boolean; disabled?: boolean; /** Marks the field with a restart badge; drive it from `useRestartKeys`. */ restartRequired?: boolean; @@ -234,14 +243,12 @@ export function SettingField({ value, onChange, options, - sensitiveConfigured, disabled: disabledProp, restartRequired, managedByEnv, dir, className, }: SettingFieldProps) { - const t = useT(); const disabled = disabledProp || managedByEnv != null; const controlId = useId(); const hintId = useId(); @@ -303,25 +310,6 @@ export function SettingField({ ); } - if (type === "password") { - return row( - onChange(e.target.value)} - disabled={disabled} - className={cn("border-muted-foreground/25", SETTINGS_CONTROL_WIDTH)} - aria-describedby={describedBy} - />, - ); - } - if (type === "number") { return row( { expect(screen.getByText("1 unsaved change")).toBeInTheDocument(); expect(publicGroup.getByLabelText("Token Secret")).toHaveValue("secret"); }); + + it("lets go of a token secret that was typed and erased again", async () => { + render(); + + const publicGroup = within(screen.getByRole("group", { name: "Public storage" })); + const linkMode = publicGroup.getByRole("combobox", { + name: "How asset links are authorized", + }); + await userEvent.click(linkMode); + await userEvent.click(screen.getByRole("option", { name: "Cloudflare signed token" })); + await userEvent.click(publicGroup.getByRole("button", { name: /Advanced/ })); + await userEvent.type(publicGroup.getByLabelText("Token Secret"), "secret"); + await userEvent.clear(publicGroup.getByLabelText("Token Secret")); + await userEvent.click(linkMode); + await userEvent.click(screen.getByRole("option", { name: "Signed links (recommended)" })); + + expect(screen.queryByText(/unsaved change/)).not.toBeInTheDocument(); + expect(publicGroup.queryByLabelText("Token Secret")).not.toBeInTheDocument(); + }); }); }); diff --git a/web/src/pages/admin-settings/StorageSettings.tsx b/web/src/pages/admin-settings/StorageSettings.tsx index a67a9e953b..e4841adc43 100644 --- a/web/src/pages/admin-settings/StorageSettings.tsx +++ b/web/src/pages/admin-settings/StorageSettings.tsx @@ -478,7 +478,7 @@ function S3Group({ label={t("web.admin.settings.storage.s3.tokenParam")} dirty={keptForEdit("s3.public_token_param")} description={t("web.admin.settings.storage.s3.tokenParamDescription")} - value={form.getValue("s3.public_token_param") || "verify"} + value={form.getValue("s3.public_token_param")} onChange={(v) => form.setValue("s3.public_token_param", v)} restartRequired={restartKeys.has("s3.public_token_param")} managedByEnv={form.envVar("s3.public_token_param")} @@ -490,7 +490,7 @@ function S3Group({ dirty={keptForEdit("s3.public_token_ttl")} type="number" unit={t("web.admin.settings.storage.unitSeconds")} - value={form.getValue("s3.public_token_ttl") || "10800"} + value={form.getValue("s3.public_token_ttl")} onChange={(v) => form.setValue("s3.public_token_ttl", v)} restartRequired={restartKeys.has("s3.public_token_ttl")} managedByEnv={form.envVar("s3.public_token_ttl")} diff --git a/web/src/pages/admin-settings/TrickplayNodeCapacityField.tsx b/web/src/pages/admin-settings/TrickplayNodeCapacityField.tsx index 9b8a2b2c8a..a3aaf162ca 100644 --- a/web/src/pages/admin-settings/TrickplayNodeCapacityField.tsx +++ b/web/src/pages/admin-settings/TrickplayNodeCapacityField.tsx @@ -23,7 +23,7 @@ export function TrickplayNodeCapacityField({ type="number" description={t("web.admin.settings.playback.previews.trickplayNodeCapacityDescription")} dirty={form.isDirty(KEY)} - value={form.getValue(KEY) || "1"} + value={form.getValue(KEY)} onChange={(v) => form.setValue(KEY, v)} restartRequired={restartKeys.has(KEY)} /> diff --git a/web/src/pages/setup-wizard/steps/StorageStep.test.tsx b/web/src/pages/setup-wizard/steps/StorageStep.test.tsx index c364d32cd5..f9a1c8bb71 100644 --- a/web/src/pages/setup-wizard/steps/StorageStep.test.tsx +++ b/web/src/pages/setup-wizard/steps/StorageStep.test.tsx @@ -45,10 +45,13 @@ function setup({ dirtyKeys = [], saved = {}, managedByEnv = {}, + configured = [], }: { dirtyKeys?: string[]; saved?: Record; managedByEnv?: Record; + /** Secrets the server holds, which the snapshot leaves out. */ + configured?: string[]; } = {}) { const values: Record = { ...saved }; const markDone = vi.fn(); @@ -57,6 +60,9 @@ function setup({ const setValue = vi.fn((key: string, value: string) => { values[key] = value; }); + const resetValue = vi.fn((key: string) => { + values[key] = saved[key] ?? ""; + }); const buildConnectionCheckRequest = vi.fn((_keys: string[]) => ({})); wizardMock.mockReturnValue({ markDone, setSummary }); formMock.mockReturnValue({ @@ -65,7 +71,8 @@ function setup({ getValue: (key: string) => values[key] ?? "", getPersistedValue: (key: string) => saved[key] ?? "", setValue, - sensitiveConfigured: [], + resetValue, + sensitiveConfigured: configured, sensitiveManagedByEnv: Object.keys(managedByEnv), envVar: (key: string) => managedByEnv[key], dirtyCount: 1, @@ -73,7 +80,7 @@ function setup({ save, isDirty: (key: string) => dirtyKeys.includes(key), }); - return { markDone, setSummary, save, setValue, buildConnectionCheckRequest }; + return { markDone, setSummary, save, setValue, resetValue, buildConnectionCheckRequest }; } describe("StorageStep", () => { @@ -317,6 +324,31 @@ describe("StorageStep", () => { expect(screen.getByLabelText("Database number")).toHaveValue(3); }); + it("keeps a saved access key when the replacement typed over it is erased", async () => { + const { setValue, resetValue } = setup({ configured: ["s3.public_access_key"] }); + const { rerender } = render(); + await userEvent.click(screen.getAllByRole("button", { name: "Set up" })[1]!); + for (const value of ["n", ""]) { + fireEvent.change(screen.getByLabelText("Access key"), { target: { value } }); + rerender(); + } + + // An empty value would clear the saved key when Continue saves. + expect(setValue).not.toHaveBeenCalledWith("s3.public_access_key", ""); + expect(resetValue).toHaveBeenCalledWith("s3.public_access_key"); + }); + + it("keeps a storage backend holding an unsaved edit open", () => { + setup({ dirtyKeys: ["s3.public_bucket"] }); + render(); + + // Continue saves the edit, so its fields stay in view and can't be hidden. + expect(screen.getByLabelText("Bucket")).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Hide" })).toBeDisabled(); + expect(screen.getByText("Unsaved changes in this group")).toBeInTheDocument(); + expect(screen.getAllByRole("button", { name: "Set up" })).toHaveLength(2); + }); + describe("applying storage that needs a restart", () => { beforeEach(() => { vi.useFakeTimers({ shouldAdvanceTime: true }); diff --git a/web/src/pages/setup-wizard/steps/StorageStep.tsx b/web/src/pages/setup-wizard/steps/StorageStep.tsx index d3de82a10d..6d7b60f9c8 100644 --- a/web/src/pages/setup-wizard/steps/StorageStep.tsx +++ b/web/src/pages/setup-wizard/steps/StorageStep.tsx @@ -5,6 +5,7 @@ import { ConnectionCheckAction, useConnectionCheck, } from "@/components/admin/ConnectionCheckAction"; +import { SecretField } from "@/components/settings/SecretField"; import { Button } from "@/components/ui/button"; import { Switch } from "@/components/ui/switch"; import { fetchAdminServerStatus, useAdminServerStatus } from "@/hooks/queries/admin/settings"; @@ -13,7 +14,7 @@ import { settingsRestartPending } from "@/hooks/admin/useSettingsHealth"; import { useMounted } from "@/hooks/useMounted"; import { useSettingsForm } from "@/hooks/useSettingsForm"; import { useT, type MessageKey, type Translate } from "@/i18n"; -import { stageRedisUrl } from "@/pages/admin-settings/redisDraft"; +import { REDIS_KEYS, keepSavedRedisUrl, stageRedisUrl } from "@/pages/admin-settings/redisDraft"; import { SettingField, SettingFieldRow, @@ -23,8 +24,6 @@ import { import { StepFrame, StepSection, StepSkeleton } from "../StepFrame"; import { useStepSubmit, useStepSummary } from "../useStep"; -const REDIS_KEYS = ["redis.url", "redis.db"]; - const PUBLIC_S3_KEYS = [ "s3.public_endpoint", "s3.public_region", @@ -123,7 +122,9 @@ function redisStatusFor( /** * One storage backend: a summary row that says whether it is configured, and a * disclosure with the fields. A backend an admin does not touch stays folded - * and reads as one line, which is what most single-node installs want. + * and reads as one line, which is what most single-node installs want. One + * holding an unsaved edit is marked changed and stays open, because Continue + * saves it. */ function Backend({ title, @@ -131,6 +132,7 @@ function Backend({ configured, status, open, + edited, onToggle, readOnly = false, children, @@ -141,28 +143,51 @@ function Backend({ /** Overrides the default Configured / Not set up line. */ status?: ReactNode; open: boolean; + /** Whether a field inside holds an unsaved edit. */ + edited: boolean; onToggle: () => void; /** Show the environment-owned values for inspection without offering edits. */ readOnly?: boolean; children: ReactNode; }) { const t = useT(); + const shown = open || edited; return ( <> {t("web.setup.storage.configured")} - ) : ( - {t("web.setup.storage.notSetUp")} - )) +
+ {status ?? + (configured ? ( + + {t("web.setup.storage.configured")} + + ) : ( + + {t("web.setup.storage.notSetUp")} + + ))} + {/* Says why Hide is unavailable. */} + {edited ? ( + + {t("web.admin.settings.fields.groupUnsavedChanges")} + + ) : null} +
} > -
- {open ?
{children}
: null} + {shown ?
{children}
: null} ); } @@ -233,21 +258,22 @@ function S3Fields({ managedByEnv={form.envVar(key("bucket"))} disabled={locationLocked} /> - form.setValue(key("access_key"), v)} + onKeep={() => form.resetValue(key("access_key"))} managedByEnv={form.envVar(key("access_key"))} - sensitiveConfigured={form.sensitiveConfigured.includes(key("access_key"))} /> - form.setValue(key("secret_key"), v)} + onKeep={() => form.resetValue(key("secret_key"))} managedByEnv={form.envVar(key("secret_key"))} - sensitiveConfigured={form.sensitiveConfigured.includes(key("secret_key"))} /> ) : null} {showsLinkSetting("s3.public_token_secret") ? ( - form.setValue("s3.public_token_secret", v)} - sensitiveConfigured={form.sensitiveConfigured.includes("s3.public_token_secret")} + onKeep={() => form.resetValue("s3.public_token_secret")} managedByEnv={form.envVar("s3.public_token_secret")} /> ) : null} @@ -315,7 +341,7 @@ function S3Fields({ label={t("web.setup.storage.tokenParamLabel")} dirty={keptForEdit("s3.public_token_param")} description={t("web.setup.storage.tokenParamDescription")} - value={form.getValue("s3.public_token_param") || "verify"} + value={form.getValue("s3.public_token_param")} onChange={(v) => form.setValue("s3.public_token_param", v)} managedByEnv={form.envVar("s3.public_token_param")} /> @@ -326,7 +352,7 @@ function S3Fields({ dirty={keptForEdit("s3.public_token_ttl")} type="number" unit={t("web.setup.storage.seconds")} - value={form.getValue("s3.public_token_ttl") || "10800"} + value={form.getValue("s3.public_token_ttl")} onChange={(v) => form.setValue("s3.public_token_ttl", v)} managedByEnv={form.envVar("s3.public_token_ttl")} /> @@ -563,17 +589,18 @@ export function StorageStep() { ) : undefined } open={open.redis} + edited={REDIS_KEYS.some(form.isDirty)} onToggle={() => setOpen((o) => ({ ...o, redis: !o.redis }))} readOnly={redisManaged} > - stageRedisUrl(form, v)} - sensitiveConfigured={redisSaved && form.getValue("redis.url") === ""} + onKeep={() => keepSavedRedisUrl(form)} managedByEnv={form.envVar("redis.url")} /> setOpen((o) => ({ ...o, public: !o.public }))} > setOpen((o) => ({ ...o, private: !o.private }))} >