diff --git a/web/src/pages/setup-wizard/steps/SubtitlesStep.test.tsx b/web/src/pages/setup-wizard/steps/SubtitlesStep.test.tsx index 81e2323e56..4798071bdf 100644 --- a/web/src/pages/setup-wizard/steps/SubtitlesStep.test.tsx +++ b/web/src/pages/setup-wizard/steps/SubtitlesStep.test.tsx @@ -4,13 +4,14 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import { SubtitlesStep } from "./SubtitlesStep"; -const wizardMock = vi.fn(); -vi.mock("../WizardContext", () => ({ useWizardContext: () => wizardMock() })); +const markDone = vi.fn(); +vi.mock("../WizardContext", () => ({ + useWizardContext: () => ({ markDone, setSummary: vi.fn() }), +})); const updateMock = vi.fn(); -// Keep `data` the same object across renders, as React Query does. A new one -// re-runs the step's load effect, whose cleanup cancels an editor read still -// in flight and leaves the row loading. +// One object for every render, as React Query returns stable data; a new one +// each time would restart the step's editor load on every re-render. const providersQuery = { data: { providers: [ @@ -28,22 +29,26 @@ vi.mock("@/hooks/queries/admin/subtitles", () => ({ useTestSubtitleProvider: () => ({ mutate: vi.fn(), isPending: false }), })); +const editorMock = vi.fn(); vi.mock("@/api/v2/adminSubtitleProviderConfiguration", () => ({ captureProviderEditIntent: (provider: string) => ({ provider }), providerIntentActive: () => true, - getProviderEditor: (intent: { provider: string }) => - Promise.resolve({ - intent, - etag: '"1"', - body: { - provider_name: intent.provider, - enabled: false, - has_api_key: false, - has_credentials: false, - }, - }), + getProviderEditor: (intent: { provider: string }) => editorMock(intent), })); +function editor(intent: { provider: string }, etag: string, enabled: boolean, hasKey: boolean) { + return { + intent, + etag, + body: { + provider_name: intent.provider, + enabled, + has_api_key: hasKey, + has_credentials: false, + }, + }; +} + class ResizeObserverStub { observe() {} unobserve() {} @@ -54,7 +59,7 @@ globalThis.ResizeObserver ??= ResizeObserverStub as unknown as typeof ResizeObse describe("SubtitlesStep", () => { beforeEach(() => { vi.clearAllMocks(); - wizardMock.mockReturnValue({ markDone: vi.fn(), setSummary: vi.fn() }); + editorMock.mockImplementation((intent) => Promise.resolve(editor(intent, '"1"', false, false))); updateMock.mockResolvedValue({ saved_revision: "2", local_apply: "not_configured" }); }); @@ -74,4 +79,49 @@ describe("SubtitlesStep", () => { await waitFor(() => expect(updateMock).toHaveBeenCalledTimes(1)); expect(updateMock.mock.calls[0]![0].config).toStrictEqual({ enabled: false }); }); + + it("keeps a failed save from being sent again until the admin reloads it", async () => { + const user = userEvent.setup(); + render(); + + const toggle = screen.getByRole("switch", { name: "Enable SubDL" }); + await waitFor(() => expect(toggle).toBeEnabled()); + await user.click(toggle); + await user.type(screen.getByLabelText("API key"), "typed-key"); + + // Another admin saves SubDL first, so this save is refused and every + // later read returns their configuration. + updateMock.mockRejectedValueOnce(new Error("precondition failed")); + editorMock.mockImplementation((intent) => Promise.resolve(editor(intent, '"2"', true, true))); + await user.click(screen.getByRole("button", { name: "Continue" })); + await waitFor(() => expect(updateMock).toHaveBeenCalledTimes(1)); + const continueButton = await screen.findByRole("button", { name: "Continue" }); + + // Continuing again must neither re-send the old draft nor finish the step. + await user.click(continueButton); + expect(updateMock).toHaveBeenCalledTimes(1); + expect(markDone).not.toHaveBeenCalled(); + expect(screen.getByLabelText("API key")).toHaveValue("typed-key"); + + // A reload that fails keeps the row locked and leaves the way to try again. + const reload = screen.getByRole("button", { + name: "Reload saved configuration (discard draft)", + }); + editorMock.mockRejectedValueOnce(new Error("load failed")); + await user.click(reload); + await screen.findByText("Unable to load saved configuration. Reload before editing."); + expect(reload).toBeEnabled(); + expect(continueButton).toBeDisabled(); + expect(screen.getByLabelText("API key")).toHaveValue("typed-key"); + + // Reloading discards the draft and shows the other admin's saved state. + await user.click(reload); + await waitFor(() => expect(screen.getByLabelText("API key")).toHaveValue("")); + expect(toggle).toBeChecked(); + expect(toggle).toHaveFocus(); + + await user.click(screen.getByRole("button", { name: "Continue" })); + expect(markDone).toHaveBeenCalledWith("subtitles"); + expect(updateMock).toHaveBeenCalledTimes(1); + }); }); diff --git a/web/src/pages/setup-wizard/steps/SubtitlesStep.tsx b/web/src/pages/setup-wizard/steps/SubtitlesStep.tsx index 6cdcb75a6f..295d6db914 100644 --- a/web/src/pages/setup-wizard/steps/SubtitlesStep.tsx +++ b/web/src/pages/setup-wizard/steps/SubtitlesStep.tsx @@ -20,7 +20,11 @@ import { } from "@/hooks/queries/admin/subtitles"; import { useT, type MessageKey } from "@/i18n"; import { sortSubtitleProviders } from "@/lib/subtitleProviders"; -import { SettingField, SettingFieldRow } from "@/pages/admin-settings/SettingField"; +import { + SettingField, + SettingFieldRow, + SettingFieldStatus, +} from "@/pages/admin-settings/SettingField"; import { StepFrame, StepSection, StepSkeleton } from "../StepFrame"; import { useStepSummary } from "../useStep"; @@ -52,6 +56,8 @@ interface ProviderDraft { username: string; password: string; dirty: boolean; + /** The last save failed: the draft stays on screen, locked, until a reload. */ + saveFailed: boolean; } function draftFor(config: SubtitleProviderConfig): ProviderDraft { @@ -65,6 +71,7 @@ function draftFor(config: SubtitleProviderConfig): ProviderDraft { username: "", password: "", dirty: false, + saveFailed: false, }; } @@ -85,11 +92,13 @@ function ProviderRow({ config, draft, onChange, + onReload, disabled, }: { config: SubtitleProviderConfig; draft: ProviderDraft; onChange: (next: ProviderDraft) => void; + onReload: () => void; disabled: boolean; }) { const t = useT(); @@ -100,19 +109,20 @@ function ProviderRow({ const canonical = draft.editor?.body ?? config; const hasCredentials = isOpenSubtitles ? canonical.has_credentials : canonical.has_api_key; const test = useTestSubtitleProvider(); - // The result is kept with the exact credentials it tested and shown only - // while the draft still matches them, so editing a field clears it and a - // late response for an older draft is never shown against the new one. + // The result is kept with the exact credentials it tested, and the saved + // revision behind them, and shown only while both still match. Editing a + // field or reloading another admin's save clears it, and a late response + // for an older draft is never shown against the new one. const [tested, setTested] = useState<{ signature: string; result: { success: boolean; error?: string }; } | null>(null); - const signature = JSON.stringify(providerBody(name, draft)); + const signature = JSON.stringify([draft.editor?.etag ?? null, providerBody(name, draft)]); const testResult = tested?.signature === signature ? tested.result : null; function runTest() { const body = providerBody(name, draft); - const testedSignature = JSON.stringify(body); + const testedSignature = signature; test.mutate( { provider: name, config: body }, { @@ -133,31 +143,81 @@ function ProviderRow({ ); } - const rowDisabled = disabled || draft.loading || draft.loadFailed; + const rowDisabled = disabled || draft.loading || draft.loadFailed || draft.saveFailed; + + // Reload disappears once the saved state is back, so focus moves to the + // provider's switch instead of dropping to the page. Focus the admin moved + // elsewhere meanwhile stays where it is. + const switchRef = useRef(null); + const refocusAfterReload = useRef(false); + useEffect(() => { + if (!refocusAfterReload.current || draft.saveFailed) return; + refocusAfterReload.current = false; + if (document.activeElement !== document.body) return; + switchRef.current?.focus(); + }, [draft.saveFailed]); + + let description = meta ? t(meta.description) : ""; + if (draft.loadFailed && !draft.saveFailed) description = t("web.setup.subtitles.loadFailed"); + + let status = null; + if (draft.saveFailed) { + // A locked row says why it is locked, and Continue waits on it. + status = ( + + {/* A live region, so a failed reload's new message is announced. */} + + {draft.loadFailed + ? t("web.admin.settings.providers.subtitles.loadFailed") + : t("web.admin.settings.providers.subtitles.saveNotConfirmed")} + + + ); + } else if (hasCredentials && !draft.dirty) { + status = ( + + {t("web.setup.subtitles.credentialsSaved")} + + ); + } + + const reloadButton = draft.saveFailed ? ( + // Its own key, so React doesn't turn this node into Test connection (and + // carry focus over) when the row unlocks. + + ) : null; return ( <> - - {t("web.setup.subtitles.credentialsSaved")} - - ) : undefined - } - > + onChange({ ...draft, enabled: v, dirty: true })} /> - {draft.enabled && !draft.loadFailed ? ( + {draft.enabled && (draft.saveFailed || !draft.loadFailed) ? (
{isOpenSubtitles ? ( <> @@ -186,36 +246,46 @@ function ProviderRow({ /> )}
- - {testResult !== null ? ( - - {testResult.success - ? t("web.setup.wizard.connected") - : (testResult.error ?? t("web.setup.subtitles.failed"))} - - ) : null} + {/* A locked row can only be reloaded, so Reload takes Test's place. */} + {reloadButton ?? ( + <> + + {testResult !== null ? ( + + {testResult.success + ? t("web.setup.wizard.connected") + : (testResult.error ?? t("web.setup.subtitles.failed"))} + + ) : null} + + )}
+ ) : reloadButton ? ( + // A provider switched off has no fields, so Reload gets its own row. +
{reloadButton}
) : null} ); } +const SAVE_ERROR_TOAST = "setup-subtitles-save-failed"; + export function SubtitlesStep() { const { markDone } = useWizardContext(); const t = useT(); @@ -232,9 +302,9 @@ export function SubtitlesStep() { // Editing a provider needs its strong validator, which only the per-provider // read returns. Each one is loaded once when the list arrives so the switch - // can be flipped straight away, and reloaded after a failed save so a retry - // never carries a stale validator. A row whose editor fails to load stays - // read-only. + // can be flipped straight away, and again after a save or when the admin + // reloads a failed one. A load always shows the saved state and drops any + // draft. A row whose editor fails to load stays read-only. const loadEditor = useCallback( (config: SubtitleProviderConfig, isCancelled: () => boolean) => { const name = config.provider_name; @@ -256,18 +326,10 @@ export function SubtitlesStep() { loaded.current.delete(name); return; } - setDrafts((prev) => { - const current = prev[name] ?? draftFor(config); - return { - ...prev, - [name]: { - ...current, - editor, - loading: false, - enabled: current.dirty ? current.enabled : editor.body.enabled, - }, - }; - }); + setDrafts((prev) => ({ + ...prev, + [name]: { ...draftFor(editor.body), editor, loading: false }, + })); }) .catch(() => { if (isCancelled()) { @@ -322,8 +384,9 @@ export function SubtitlesStep() { } setSubmitting(true); // Each provider is its own resource with its own validator, so the saves - // are independent and run together. A failed one keeps its draft but - // reloads its validator, so the retry cannot send a stale If-Match. + // are independent and run together. A failed one may still have been + // written, or lost to another admin's save, so its draft is never sent + // again: the row locks until the admin reloads it and sees what is saved. const results = await Promise.allSettled( changed.map(async (config) => { const name = config.provider_name; @@ -362,15 +425,25 @@ export function SubtitlesStep() { ...prev, [failure.config.provider_name]: { ...prev[failure.config.provider_name]!, - editor: null, - loading: true, - loadFailed: false, + saveFailed: true, }, })); - loadEditor(failure.config, () => false); } const reason = failures[0]!.reason; - toast.error(reason instanceof Error ? reason.message : t("web.setup.subtitles.saveFailed")); + toast.error(reason instanceof Error ? reason.message : t("web.setup.subtitles.saveFailed"), { + id: SAVE_ERROR_TOAST, + }); + } + + function reloadEditor(config: SubtitleProviderConfig) { + const name = config.provider_name; + // The failed save's toast says to fetch again and retry; a reload does that. + toast.dismiss(SAVE_ERROR_TOAST); + setDrafts((prev) => ({ + ...prev, + [name]: { ...prev[name]!, loading: true, loadFailed: false }, + })); + loadEditor(config, () => false); } if (providers.isLoading) return ; @@ -381,10 +454,15 @@ export function SubtitlesStep() { lede={t("web.setup.subtitles.lede")} onSubmit={handleSubmit} busy={submitting} + // A failed save must be reloaded first, so the step never finishes with + // that change unsaved. Skip still leaves without saving. + disabled={providerList.some((p) => drafts[p.provider_name]?.saveFailed)} onSkip={() => markDone("subtitles")} footnote={t("web.setup.subtitles.footnote")} > + {/* A failed refresh shows its error above the rows it already has, + so a locked row's Reload stays reachable. */} {providers.isError ? (

{t("web.setup.subtitles.listLoadFailed")}

@@ -403,7 +481,8 @@ export function SubtitlesStep() { {t("common.tryAgain")}
- ) : providerList.length === 0 ? ( + ) : null} + {!providers.data ? null : providerList.length === 0 ? (

{t("web.setup.subtitles.none")}

) : ( providerList.map((config) => ( @@ -412,6 +491,7 @@ export function SubtitlesStep() { config={config} draft={drafts[config.provider_name] ?? draftFor(config)} onChange={(next) => setDrafts((prev) => ({ ...prev, [config.provider_name]: next }))} + onReload={() => reloadEditor(config)} disabled={submitting} /> ))