fix(webui): save settings when editing completes (NAN-323) (#6384)

* fix(webui): save settings when editing completes (NAN-323)

* fix(webui): close settings completion and verification gaps

* refactor(webui): simplify settings edit ownership
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-22 13:39:46 +08:00
1 parent 26e1f41a00
commit c6babb20e8
34 files changed
+1363 -388

No files matched your search

@@ -1,4 +1,4 @@
import { useAutoSave } from "@/components/settings/shared/useAutoSave";
import { useEditCompletion, type EditCompletion } from "@/components/settings/shared/useEditCompletion";
import { ProviderParameterFields } from "@/components/settings/models/ProviderParameterFields";
import { providerJsonValue } from "@/components/settings/models/providerForm";
import type { Dispatch, SetStateAction, ReactNode } from "react";
@@ -48,6 +48,7 @@ export function imageGenerationFormFromPayload(payload: SettingsPayload): ImageG
export function ImageGenerationSettings({
embedded = false,
editCompletion,
error,
children,
token,
@@ -65,6 +66,7 @@ export function ImageGenerationSettings({
requiresRestartPending,
}: {
embedded?: boolean;
editCompletion?: EditCompletion;
error?: string;
children?: ReactNode;
token: string;
@@ -87,7 +89,8 @@ export function ImageGenerationSettings({
settings.image_generation.providers.find((provider) => provider.name === form.provider);
const providerConfigured = !!selectedProvider?.configured;
const missingCredential = form.enabled && !providerConfigured;
useAutoSave(form, dirty, saving, onSave, !embedded && !missingCredential);
const localEdits = useEditCompletion(form, dirty, onSave, !editCompletion && !missingCredential);
const edits = editCompletion ?? localEdits;
const aspectOptions = optionRowsWithCurrent(
IMAGE_ASPECT_RATIO_OPTIONS.map((value) => ({ name: value, label: value })),
form.defaultAspectRatio,
@@ -97,6 +100,7 @@ export function ImageGenerationSettings({
form.defaultImageSize,
);
const selectProvider = (provider: string) => {
edits.complete();
const nextProvider = settings.image_generation.providers.find((row) => row.name === provider);
onChangeForm((prev) => ({
...prev,
@@ -108,7 +112,7 @@ export function ImageGenerationSettings({
};
return (
<div className="settings-stack">
<div className="settings-stack" onChangeCapture={edits.onChangeCapture} onFocusCapture={edits.onFocusCapture} onBlurCapture={edits.onBlurCapture}>
<section>
{!embedded ? <SettingsSectionTitle>{tx("settings.sections.imageGeneration", "Image generation")}</SettingsSectionTitle> : null}
<SettingsGroup>
@@ -116,7 +120,7 @@ export function ImageGenerationSettings({
<SettingsRow title={tx("settings.rows.imageGeneration", "Image generation")}>
<ToggleButton
checked={form.enabled}
onChange={(enabled) => onChangeForm((prev) => ({ ...prev, enabled }))}
onChange={(enabled) => { edits.complete(); onChangeForm((prev) => ({ ...prev, enabled })); }}
ariaLabel={tx("settings.rows.imageGeneration", "Image generation")}
label={form.enabled ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}
/>
@@ -172,7 +176,7 @@ export function ImageGenerationSettings({
"settings.image.typeModelId",
"Type the model ID supported by this provider.",
)}
onChange={(model) => onChangeForm((prev) => ({ ...prev, model }))}
onChange={(model) => { edits.complete(); onChangeForm((prev) => ({ ...prev, model })); }}
/>
</SettingsRow>
<SettingsRow title={tx("settings.rows.defaultAspectRatio", "Default aspect ratio")}>
@@ -180,9 +184,10 @@ export function ImageGenerationSettings({
providers={aspectOptions}
value={form.defaultAspectRatio}
emptyLabel={tx("settings.image.selectAspect", "Select aspect")}
onChange={(defaultAspectRatio) =>
onChangeForm((prev) => ({ ...prev, defaultAspectRatio }))
}
onChange={(defaultAspectRatio) => {
edits.complete();
onChangeForm((prev) => ({ ...prev, defaultAspectRatio }));
}}
/>
</SettingsRow>
<SettingsRow title={tx("settings.rows.defaultImageSize", "Default size")}>
@@ -190,9 +195,10 @@ export function ImageGenerationSettings({
providers={sizeOptions}
value={form.defaultImageSize}
emptyLabel={tx("settings.image.selectSize", "Select size")}
onChange={(defaultImageSize) =>
onChangeForm((prev) => ({ ...prev, defaultImageSize }))
}
onChange={(defaultImageSize) => {
edits.complete();
onChangeForm((prev) => ({ ...prev, defaultImageSize }));
}}
/>
</SettingsRow>
<SettingsAdvancedOptions>
@@ -1,4 +1,4 @@
import { useAutoSave } from "@/components/settings/shared/useAutoSave";
import { useEditCompletion, type EditCompletion } from "@/components/settings/shared/useEditCompletion";
import type { Dispatch, SetStateAction } from "react";
import { useTranslation } from "react-i18next";
@@ -38,6 +38,7 @@ export function visibleWebuiDefaultAccessMode(mode: string | null | undefined):
}
export function AdvancedSettings({
editCompletion,
error,
form,
dirty,
@@ -49,6 +50,7 @@ export function AdvancedSettings({
onRestart,
isRestarting,
}: {
editCompletion?: EditCompletion;
error?: string;
form: NetworkSafetySettingsUpdate;
dirty: boolean;
@@ -61,10 +63,11 @@ export function AdvancedSettings({
isRestarting?: boolean;
}) {
const { t } = useTranslation();
useAutoSave(form, dirty, saving, onSave);
const localEdits = useEditCompletion(form, dirty, onSave, !editCompletion);
const edits = editCompletion ?? localEdits;
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
return (
<div className="settings-stack">
<div className="settings-stack" onChangeCapture={edits.onChangeCapture} onFocusCapture={edits.onFocusCapture} onBlurCapture={edits.onBlurCapture}>
<section>
<SettingsSectionTitle>
{isNativeHostSurface
@@ -1,4 +1,4 @@
import { useAutoSave } from "@/components/settings/shared/useAutoSave";
import { useEditCompletion, type EditCompletion } from "@/components/settings/shared/useEditCompletion";
import { SettingsAdvancedOptions } from "@/components/settings/shared/SettingsFeature";
import type { Dispatch, SetStateAction } from "react";
import { useTranslation } from "react-i18next";
@@ -51,6 +51,7 @@ export function transcriptionFormFromPayload(payload: SettingsPayload): Transcri
export function TranscriptionSettings({
embedded = false,
editCompletion,
error,
settings,
form,
@@ -65,6 +66,7 @@ export function TranscriptionSettings({
requiresRestartPending,
}: {
embedded?: boolean;
editCompletion?: EditCompletion;
error?: string;
settings: SettingsPayload;
form: TranscriptionSettingsUpdate;
@@ -79,7 +81,8 @@ export function TranscriptionSettings({
requiresRestartPending: boolean;
}) {
const { t } = useTranslation();
useAutoSave(form, dirty, saving, onSave, !embedded);
const localEdits = useEditCompletion(form, dirty, onSave, !editCompletion);
const edits = editCompletion ?? localEdits;
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
const transcription = settings.transcription ?? DEFAULT_TRANSCRIPTION_SETTINGS;
const selectedProvider =
@@ -88,7 +91,7 @@ export function TranscriptionSettings({
const providerConfigured = !!selectedProvider?.configured;
return (
<section>
<section onChangeCapture={edits.onChangeCapture} onFocusCapture={edits.onFocusCapture} onBlurCapture={edits.onBlurCapture}>
{!embedded ? <SettingsSectionTitle>{tx("settings.sections.voiceInput", "Voice input")}</SettingsSectionTitle> : null}
<SettingsGroup>
{!embedded ? (
@@ -98,7 +101,7 @@ export function TranscriptionSettings({
>
<ToggleButton
checked={form.enabled}
onChange={(enabled) => onChangeForm((prev) => ({ ...prev, enabled }))}
onChange={(enabled) => { edits.complete(); onChangeForm((prev) => ({ ...prev, enabled })); }}
ariaLabel={tx("settings.rows.transcription", "Transcription")}
label={form.enabled ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}
/>
@@ -111,7 +114,7 @@ export function TranscriptionSettings({
value={form.provider}
emptyLabel={tx("settings.voice.selectProvider", "Select provider")}
showProviderLogos={showBrandLogos}
onChange={(provider) => onChangeForm((prev) => ({ ...prev, provider }))}
onChange={(provider) => { edits.complete(); onChangeForm((prev) => ({ ...prev, provider })); }}
/>
</SettingsRow>
<SettingsRow
@@ -1,4 +1,4 @@
import { useAutoSave } from "@/components/settings/shared/useAutoSave";
import { useEditCompletion, type EditCompletion } from "@/components/settings/shared/useEditCompletion";
import { SettingsAdvancedOptions } from "@/components/settings/shared/SettingsFeature";
import type { Dispatch, ReactNode, SetStateAction } from "react";
import { Eye, EyeOff, Pencil } from "lucide-react";
@@ -76,6 +76,7 @@ export function webSearchDraftState(settings: SettingsPayload, form: WebSearchSe
export function WebSettings({
embedded = false,
editCompletion,
error,
enabled = true,
settings,
@@ -99,6 +100,7 @@ export function WebSettings({
children,
}: {
embedded?: boolean;
editCompletion?: EditCompletion;
error?: string;
enabled?: boolean;
settings: SettingsPayload;
@@ -130,10 +132,11 @@ export function WebSettings({
const effectiveJinaReader = form.useJinaReader ?? settings.web.fetch.use_jina_reader;
const showKeyInput = webSearchProviderAcceptsApiKey(selectedProvider) && (!hasExistingSecret || keyEditing);
useAutoSave(form, dirty, saving, onSave, !embedded && !missingCredential && (form.provider !== "olostep" || olostepFeature?.installed === true));
const localEdits = useEditCompletion(form, dirty, onSave, !editCompletion && !missingCredential && (form.provider !== "olostep" || olostepFeature?.installed === true));
const edits = editCompletion ?? localEdits;
return (
<div className="settings-stack">
<div className="settings-stack" onChangeCapture={edits.onChangeCapture} onFocusCapture={edits.onFocusCapture} onBlurCapture={edits.onBlurCapture}>
<section>
{enabled && !embedded ? <SettingsSectionTitle>{tx("settings.sections.webSearch", "Web search")}</SettingsSectionTitle> : null}
<div hidden={!embedded && !enabled}>
@@ -161,7 +164,7 @@ export function WebSettings({
value={form.provider}
emptyLabel={t("settings.byok.webSearch.selectProvider")}
showProviderLogos={showBrandLogos}
onChange={onChangeProvider}
onChange={(provider) => { edits.complete(); onChangeProvider(provider); }}
/>
</SettingsRow>
@@ -1,4 +1,4 @@
import { useCallback, type Dispatch, type SetStateAction } from "react";
import { useCallback, useRef, type Dispatch, type SetStateAction } from "react";
import type { TFunction } from "i18next";
import {
@@ -32,9 +32,6 @@ interface CapabilitySettingsActionsOptions {
maybeRestartHostEngine: MaybeRestartHostEngine;
setPendingRestartSections: Dispatch<SetStateAction<PendingRestartSections>>;
installCapabilities: (names: string[]) => Promise<boolean>;
imageGenerationDirty: boolean;
transcriptionDirty: boolean;
networkSafetyDirty: boolean;
}
export function useCapabilitySettingsActions({
@@ -46,15 +43,10 @@ export function useCapabilitySettingsActions({
maybeRestartHostEngine,
setPendingRestartSections,
installCapabilities,
imageGenerationDirty,
transcriptionDirty,
networkSafetyDirty,
}: CapabilitySettingsActionsOptions) {
const {
imageGenerationForm,
imageGenerationSaving,
networkSafetyForm,
networkSafetySaving,
setImageGenerationSaving,
setNetworkSafetySaving,
setTranscriptionSaving,
@@ -63,11 +55,11 @@ export function useCapabilitySettingsActions({
setWebSearchKeyVisible,
setWebSearchSaving,
transcriptionForm,
transcriptionSaving,
webSearchForm,
webSearchKeyEditing,
webSearchSaving,
} = state;
const latestWebSearchForm = useRef(webSearchForm);
latestWebSearchForm.current = webSearchForm;
const setError = (section: "image" | "voice" | "web" | "safety", message?: string) =>
state.setCapabilityErrors((prev) => ({ ...prev, [section]: message }));
@@ -76,8 +68,8 @@ export function useCapabilitySettingsActions({
setImageGenerationSaving(true);
try {
const payload = await updateImageGenerationSettings(client, values);
applyPayload(payload, { preserveCapabilityForms: true });
state.setImageGenerationForm(imageGenerationFormFromPayload(payload));
applyPayload(payload, { preserveAgentForm: true, preserveCapabilityForms: true });
state.setImageGenerationForm((current) => current === imageGenerationForm ? imageGenerationFormFromPayload(payload) : current);
if (!payload.restart_required_sections && payload.requires_restart) {
setPendingRestartSections((prev) => ({ ...prev, image: true }));
}
@@ -92,71 +84,78 @@ export function useCapabilitySettingsActions({
persistImageSettings({ ...imageGenerationForm, ...values });
const saveImageGenerationSettings = async () => {
if (!settings || !imageGenerationDirty || imageGenerationSaving) return;
if (!settings || !Number.isFinite(imageGenerationForm.maxImagesPerTurn)) return false;
if (imageGenerationForm.enabled && !settings.image_generation.providers.find(
(provider) => provider.name === imageGenerationForm.provider,
)?.configured) return;
)?.configured) return false;
try {
await persistImageSettings(imageGenerationForm);
return true;
} catch (err) {
const message = (err as Error).message;
setError("image", message === "image generation provider is not configured"
? t("settings.image.missingCredential") : message);
return false;
}
};
const saveTranscriptionSettings = async () => {
if (!settings || !transcriptionDirty || transcriptionSaving) return;
if (!settings || !Number.isFinite(transcriptionForm.maxDurationSec) || !Number.isFinite(transcriptionForm.maxUploadMb)) return false;
setError("voice");
setTranscriptionSaving(true);
try {
const payload = await updateTranscriptionSettings(client, transcriptionForm);
applyPayload(payload, { preserveCapabilityForms: true });
state.setTranscriptionForm(transcriptionFormFromPayload(payload));
applyPayload(payload, { preserveAgentForm: true, preserveCapabilityForms: true });
state.setTranscriptionForm((current) => current === transcriptionForm ? transcriptionFormFromPayload(payload) : current);
if (!payload.restart_required_sections && payload.requires_restart) {
setPendingRestartSections((prev) => ({ ...prev, browser: true }));
}
await maybeRestartHostEngine(payload);
setError("voice");
return true;
} catch (err) {
setError("voice", (err as Error).message);
return false;
} finally {
setTranscriptionSaving(false);
}
};
const saveNetworkSafetySettings = async () => {
if (!settings || !networkSafetyDirty || networkSafetySaving) return;
if (!settings) return false;
setError("safety");
setNetworkSafetySaving(true);
try {
const payload = await updateNetworkSafetySettings(client, networkSafetyForm);
applyPayload(payload, { preserveCapabilityForms: true });
state.setNetworkSafetyForm(networkSafetyFormFromPayload(payload));
applyPayload(payload, { preserveAgentForm: true, preserveCapabilityForms: true });
state.setNetworkSafetyForm((current) => current === networkSafetyForm ? networkSafetyFormFromPayload(payload) : current);
if (!payload.restart_required_sections && payload.requires_restart) {
setPendingRestartSections((prev) => ({ ...prev, runtime: true }));
}
await maybeRestartHostEngine(payload);
setError("safety");
return true;
} catch (err) {
setError("safety", (err as Error).message);
return false;
} finally {
setNetworkSafetySaving(false);
}
};
const saveWebSearch = async () => {
if (!settings || webSearchSaving) return;
if (!settings || !Number.isFinite(webSearchForm.maxResults ?? settings.web_search.max_results) ||
!Number.isFinite(webSearchForm.timeout ?? settings.web_search.timeout)) return false;
const provider = settings.web_search.providers.find((item) => item.name === webSearchForm.provider);
if (!provider) return;
if (!provider) return false;
const apiKey = webSearchForm.apiKey?.trim() ?? "";
const baseUrl = webSearchForm.baseUrl?.trim() ?? "";
if (webSearchDraftState(settings, webSearchForm).missingCredential) return;
if (webSearchDraftState(settings, webSearchForm).missingCredential) return false;
setError("web");
setWebSearchSaving(true);
try {
if (provider.name === "olostep" && !(await installCapabilities(["olostep"]))) return;
if (provider.name === "olostep" && !(await installCapabilities(["olostep"]))) return false;
const webFetchRestartRequired =
(webSearchForm.useJinaReader ?? settings.web.fetch.use_jina_reader) !==
settings.web.fetch.use_jina_reader;
@@ -174,12 +173,12 @@ export function useCapabilitySettingsActions({
}
if (provider.credential === "base_url") update.baseUrl = baseUrl;
const payload = await updateWebSearchSettings(client, update);
applyPayload(payload, { preserveCapabilityForms: true });
applyPayload(payload, { preserveAgentForm: true, preserveCapabilityForms: true });
if (!payload.restart_required_sections && (payload.requires_restart || webFetchRestartRequired)) {
setPendingRestartSections((prev) => ({ ...prev, browser: true }));
}
await maybeRestartHostEngine(payload);
setWebSearchForm((prev) => ({
setWebSearchForm((prev) => prev !== webSearchForm ? prev : ({
provider: payload.web_search.provider,
apiKey: "",
baseUrl: payload.web_search.base_url ?? prev.baseUrl ?? "",
@@ -187,11 +186,15 @@ export function useCapabilitySettingsActions({
timeout: payload.web_search.timeout,
useJinaReader: payload.web.fetch.use_jina_reader,
}));
setWebSearchKeyVisible(false);
setWebSearchKeyEditing(false);
if (latestWebSearchForm.current === webSearchForm) {
setWebSearchKeyVisible(false);
setWebSearchKeyEditing(false);
}
setError("web");
return true;
} catch (err) {
setError("web", (err as Error).message);
return false;
} finally {
setWebSearchSaving(false);
}