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:
1 parent
26e1f41a00
commit
c6babb20e8
34 files changed
+1363
-388
No files matched your search
@@ -5,6 +5,7 @@ import { Button } from "@/components/ui/button";
|
||||
import type { SettingsExitGuard } from "@/components/settings/contracts";
|
||||
import { isCapabilitySection, type SettingsSectionKey } from "@/components/settings/contracts";
|
||||
import { SettingsFeature } from "@/components/settings/shared/SettingsFeature";
|
||||
import type { EditCompletion } from "@/components/settings/shared/useEditCompletion";
|
||||
import { SettingsSectionSkeleton } from "@/components/settings/shared/SettingsSectionSkeleton";
|
||||
|
||||
import { SkillsCatalogSettings } from "@/components/settings/SkillsCatalogSettings";
|
||||
@@ -120,7 +121,7 @@ export function SettingsPage({
|
||||
pendingRestartSections: controllerPendingRestartSections,
|
||||
remoteBrowserAccess,
|
||||
restartViaSettingsSurface,
|
||||
selectSection,
|
||||
selectSection: selectSectionNow,
|
||||
setLocalPrefs,
|
||||
settings,
|
||||
t,
|
||||
@@ -130,10 +131,52 @@ export function SettingsPage({
|
||||
const { providerOAuthFlow } = modelState;
|
||||
|
||||
const restartInProgress = isRestarting || hostEngineApplying;
|
||||
const requestExit = useCallback<SettingsExitGuard>((leave) => {
|
||||
if (settings?.requires_restart && !restartInProgress) setPendingExit(() => leave);
|
||||
else leave();
|
||||
}, [settings?.requires_restart, restartInProgress]);
|
||||
const latestExitState = useRef({ requiresRestart: settings?.requires_restart, restartInProgress });
|
||||
latestExitState.current = { requiresRestart: settings?.requires_restart, restartInProgress };
|
||||
const channelCompletion = useRef<(() => Promise<boolean>) | null>(null);
|
||||
const registerChannelCompletion = useCallback((handler: (() => Promise<boolean>) | null) => {
|
||||
channelCompletion.current = handler;
|
||||
}, []);
|
||||
const editOwners = new Map<SettingsSectionKey, EditCompletion[]>([
|
||||
["models", [controller.modelEdits]],
|
||||
["advanced", [controller.safetyEdits]],
|
||||
["capabilities", [controller.imageEdits, controller.transcriptionEdits, controller.webEdits]],
|
||||
]);
|
||||
const latestEditOwners = useRef(editOwners);
|
||||
latestEditOwners.current = editOwners;
|
||||
const flushEdits = useCallback(async () => {
|
||||
const results = await Promise.all([
|
||||
...[...latestEditOwners.current.values()].flat().map((edits) => edits.commit()),
|
||||
channelCompletion.current?.() ?? true,
|
||||
]);
|
||||
return results.every(Boolean);
|
||||
}, []);
|
||||
const needsCompletion = useCallback(() => {
|
||||
return Boolean(channelCompletion.current) ||
|
||||
[...latestEditOwners.current.values()].flat().some((edits) => edits.needsCompletion());
|
||||
}, []);
|
||||
const selectSection = (section: SettingsSectionKey) => {
|
||||
const owners = editOwners.get(isCapabilitySection(activeSection) ? "capabilities" : activeSection) ?? [];
|
||||
const channel = activeSection === "channels" ? channelCompletion.current : null;
|
||||
if (!channel && !owners.some((edits) => edits.needsCompletion())) {
|
||||
selectSectionNow(section);
|
||||
return;
|
||||
}
|
||||
void Promise.all([...owners.map((edits) => edits.commit()), channel?.() ?? true]).then((results) => {
|
||||
if (results.every(Boolean)) selectSectionNow(section);
|
||||
});
|
||||
};
|
||||
// Credential repair retains the capability draft in this controller rather than discarding it.
|
||||
const configureCapabilityProviders = () => selectSectionNow("models");
|
||||
const requestExit = useCallback<SettingsExitGuard>((leave, { promptRestart = true } = {}) => {
|
||||
const finish = () => {
|
||||
const current = latestExitState.current;
|
||||
if (promptRestart && current.requiresRestart && !current.restartInProgress) setPendingExit(() => leave);
|
||||
else leave();
|
||||
};
|
||||
if (!needsCompletion()) finish();
|
||||
else void flushEdits().then((saved) => { if (saved) finish(); });
|
||||
}, [flushEdits, needsCompletion]);
|
||||
useEffect(() => {
|
||||
registerExitGuard?.(requestExit);
|
||||
return () => registerExitGuard?.(null);
|
||||
@@ -149,6 +192,7 @@ export function SettingsPage({
|
||||
remoteBrowserAccess={remoteBrowserAccess}>
|
||||
{page === "advanced" ? (
|
||||
<AdvancedSettings
|
||||
editCompletion={controller.safetyEdits}
|
||||
error={capabilityState.capabilityErrors.safety}
|
||||
form={capabilityState.networkSafetyForm}
|
||||
dirty={networkSafetyDirty}
|
||||
@@ -180,20 +224,20 @@ export function SettingsPage({
|
||||
{!showSidebar && settings.requires_restart ? <RestartRequiredNotice message={t("settings.status.savedRestartApply")}
|
||||
onRestart={restartViaSettingsSurface} isRestarting={restartInProgress} /> : null}
|
||||
</div>
|
||||
<SettingsFeature title={t("settings.rows.imageGeneration")} enabled={capabilityState.imageGenerationForm.enabled}
|
||||
<SettingsFeature onBeforeClose={controller.imageEdits.needsCompletion() ? controller.imageEdits.commit : undefined} title={t("settings.rows.imageGeneration")} enabled={capabilityState.imageGenerationForm.enabled}
|
||||
error={capabilityState.imageGenerationForm.enabled && !settings.image_generation.providers.find((provider) => provider.name === capabilityState.imageGenerationForm.provider)?.configured
|
||||
? t("settings.image.missingCredential") : capabilityState.capabilityErrors.image}
|
||||
disabled={restartInProgress || capabilityState.imageGenerationSaving} initialOpen={activeSection === "image"}
|
||||
onChange={(enabled) => capabilityState.setImageGenerationForm((prev) => ({ ...prev, enabled }))}>
|
||||
{renderSection("image", true)}
|
||||
</SettingsFeature>
|
||||
<SettingsFeature title={t("settings.rows.transcription")} enabled={capabilityState.transcriptionForm.enabled}
|
||||
<SettingsFeature onBeforeClose={controller.transcriptionEdits.needsCompletion() ? controller.transcriptionEdits.commit : undefined} title={t("settings.rows.transcription")} enabled={capabilityState.transcriptionForm.enabled}
|
||||
error={capabilityState.capabilityErrors.voice}
|
||||
disabled={restartInProgress || capabilityState.transcriptionSaving} initialOpen={activeSection === "voice"}
|
||||
onChange={(enabled) => capabilityState.setTranscriptionForm((prev) => ({ ...prev, enabled }))}>
|
||||
{renderSection("voice", true)}
|
||||
</SettingsFeature>
|
||||
<SettingsFeature title={t("settings.runtimeConfig.groups.web.title")}
|
||||
<SettingsFeature onBeforeClose={controller.webEdits.needsCompletion() ? controller.webEdits.commit : undefined} title={t("settings.runtimeConfig.groups.web.title")}
|
||||
enabled={settings.runtime_config ? state.value("tools.web.enable") === true : settings.web.enable}
|
||||
disabled={restartInProgress || state.saving === "web" || !settings.runtime_config}
|
||||
initialOpen={activeSection === "browser"} error={state.errors.web || capabilityState.capabilityErrors.web}
|
||||
@@ -233,11 +277,13 @@ export function SettingsPage({
|
||||
return (
|
||||
<div className="settings-stack">
|
||||
<ModelsSettings
|
||||
editCompletion={controller.modelEdits}
|
||||
token={token}
|
||||
form={modelState.form}
|
||||
setForm={modelState.setForm}
|
||||
editingPresetName={modelState.modelPresetEditingName}
|
||||
presetNameError={modelState.modelPresetNameError}
|
||||
error={error}
|
||||
settings={settings}
|
||||
dirty={modelDirty}
|
||||
creating={modelState.modelPresetCreating}
|
||||
@@ -329,6 +375,7 @@ export function SettingsPage({
|
||||
return (
|
||||
<div className="settings-stack">
|
||||
<ImageGenerationSettings
|
||||
editCompletion={controller.imageEdits}
|
||||
error={capabilityState.capabilityErrors.image}
|
||||
embedded={embedded}
|
||||
token={token}
|
||||
@@ -339,7 +386,7 @@ export function SettingsPage({
|
||||
onChangeForm={capabilityState.setImageGenerationForm}
|
||||
onSave={capabilityActions.saveImageGenerationSettings}
|
||||
onSaveRequestSettings={capabilityActions.saveImageRequestSettings}
|
||||
onOpenProviders={() => selectSection("models")}
|
||||
onOpenProviders={configureCapabilityProviders}
|
||||
showBrandLogos={localPrefs.brandLogos}
|
||||
onRestart={restartViaSettingsSurface}
|
||||
isRestarting={restartInProgress}
|
||||
@@ -352,6 +399,7 @@ export function SettingsPage({
|
||||
case "voice":
|
||||
return (
|
||||
<TranscriptionSettings
|
||||
editCompletion={controller.transcriptionEdits}
|
||||
error={capabilityState.capabilityErrors.voice}
|
||||
embedded={embedded}
|
||||
settings={settings}
|
||||
@@ -360,7 +408,7 @@ export function SettingsPage({
|
||||
saving={capabilityState.transcriptionSaving}
|
||||
onChangeForm={capabilityState.setTranscriptionForm}
|
||||
onSave={capabilityActions.saveTranscriptionSettings}
|
||||
onOpenProviders={() => selectSection("models")}
|
||||
onOpenProviders={configureCapabilityProviders}
|
||||
showBrandLogos={localPrefs.brandLogos}
|
||||
onRestart={restartViaSettingsSurface}
|
||||
isRestarting={restartInProgress}
|
||||
@@ -372,6 +420,7 @@ export function SettingsPage({
|
||||
<div className="settings-stack">
|
||||
{!embedded ? runtimeConfiguration("browser") : null}
|
||||
<WebSettings
|
||||
editCompletion={controller.webEdits}
|
||||
error={capabilityState.capabilityErrors.web || controller.runtimeConfigState.errors.web}
|
||||
embedded={embedded}
|
||||
enabled={settings.runtime_config
|
||||
@@ -441,6 +490,7 @@ export function SettingsPage({
|
||||
case "channels":
|
||||
return (
|
||||
<ChannelsSettings
|
||||
onBeforeCloseChange={registerChannelCompletion}
|
||||
onConfigureMcp={(name) => {
|
||||
setMcpSetupName(name);
|
||||
systemState.setAppsKindFilter("mcp");
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import { channelValidationMessage } from "./validationMessages";
|
||||
import {
|
||||
Suspense,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useId,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ComponentType,
|
||||
type ReactNode,
|
||||
@@ -21,7 +19,7 @@ import type {
|
||||
ChannelFeatureAction,
|
||||
ChannelPluginConnectFlowProps,
|
||||
} from "@/channel-plugins/types";
|
||||
import { useAutoSave } from "@/components/settings/shared/useAutoSave";
|
||||
import { useEditCompletion } from "@/components/settings/shared/useEditCompletion";
|
||||
import {
|
||||
type ChannelProviderPreset,
|
||||
type ChannelSetupPresentation,
|
||||
@@ -188,10 +186,9 @@ function ChannelSetupSurface({
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [autoSaving, setAutoSaving] = useState(false);
|
||||
const [autoSaveState, setAutoSaveState] = useState<"idle" | "saved">("idle");
|
||||
const autoSavePromiseRef = useRef<Promise<boolean> | null>(null);
|
||||
const [validating, setValidating] = useState(false);
|
||||
const [pendingEnabled, setPendingEnabled] = useState<boolean | null>(null);
|
||||
const actionPending = saving || autoSaving || validating || pendingEnabled !== null;
|
||||
const actionPending = saving || validating || pendingEnabled !== null;
|
||||
const [validation, setValidation] = useState<ChannelValidationPayload | null>(null);
|
||||
const [visibleSecrets, setVisibleSecrets] = useState<Record<string, boolean>>({});
|
||||
const [touchedFields, setTouchedFields] = useState<Set<string>>(() => new Set());
|
||||
@@ -206,10 +203,6 @@ function ChannelSetupSurface({
|
||||
);
|
||||
const mode = setup.mode ?? "credentials";
|
||||
const fields = setup.fields ?? [];
|
||||
const secretFieldKeys = useMemo(
|
||||
() => new Set(fields.filter((field) => field.secret).map((field) => field.key)),
|
||||
[fields],
|
||||
);
|
||||
const requirementKeys = new Set(
|
||||
(setup.requirements ?? []).flatMap((requirement) => requirement.alternatives.flat()),
|
||||
);
|
||||
@@ -239,7 +232,15 @@ function ChannelSetupSurface({
|
||||
setClearedSecrets(new Set());
|
||||
setFieldErrors({});
|
||||
setFieldValues(defaultChannelFieldValues(editableFields, feature.config_values));
|
||||
}, [configValuesKey, feature.name]);
|
||||
}, [feature.name]);
|
||||
|
||||
useEffect(() => {
|
||||
const saved = defaultChannelFieldValues(editableFields, feature.config_values);
|
||||
setFieldValues((current) => ({
|
||||
...saved,
|
||||
...Object.fromEntries(Object.entries(current).filter(([key]) => touchedFields.has(key))),
|
||||
}));
|
||||
}, [configValuesKey]);
|
||||
|
||||
const toggleSecret = (key: string) => {
|
||||
setVisibleSecrets((current) => ({ ...current, [key]: !current[key] }));
|
||||
@@ -263,22 +264,8 @@ function ChannelSetupSurface({
|
||||
setAutoSaveState("idle");
|
||||
};
|
||||
|
||||
const saveConnectionSettings = async () => {
|
||||
if (mode !== "connect" || saving || !touchedFields.size) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const payload = await configureChannel(client, feature.name,
|
||||
channelValuesForSubmit(editableFields, fieldValues, touchedFields, clearedSecrets));
|
||||
setTouchedFields(new Set());
|
||||
if (payload.nanobot_features) onFeaturesUpdate(payload.nanobot_features);
|
||||
} catch (err) {
|
||||
setNotice((err as Error).message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const setSecretCleared = (key: string, clear: boolean) => {
|
||||
edits.complete();
|
||||
setClearedSecrets((current) => {
|
||||
const next = new Set(current);
|
||||
if (clear) next.add(key);
|
||||
@@ -289,6 +276,7 @@ function ChannelSetupSurface({
|
||||
};
|
||||
|
||||
const applyPreset = (preset: ChannelProviderPreset) => {
|
||||
edits.complete();
|
||||
const values = Object.fromEntries(
|
||||
Object.entries(preset.values).filter(([key]) => !(fieldValues[key] ?? "").trim()),
|
||||
);
|
||||
@@ -302,63 +290,35 @@ function ChannelSetupSurface({
|
||||
setAutoSaveState("idle");
|
||||
};
|
||||
|
||||
const credentialDirty = touchedFields.size > 0 || clearedSecrets.size > 0;
|
||||
const touchedSecret = fields.some(
|
||||
(field) => field.secret && touchedFields.has(field.key),
|
||||
);
|
||||
const saveCredentialDraft = useCallback(async (): Promise<boolean> => {
|
||||
const activeSave = autoSavePromiseRef.current;
|
||||
if (activeSave) return activeSave;
|
||||
if (mode !== "credentials" || !credentialDirty) return true;
|
||||
const draftDirty = touchedFields.size > 0 || clearedSecrets.size > 0;
|
||||
const saveChannelDraft = async (): Promise<boolean> => {
|
||||
if (mode !== "credentials" && mode !== "connect") return true;
|
||||
if (saving || validating || pendingEnabled !== null) return false;
|
||||
|
||||
const values = channelValuesForSubmit(fields, fieldValues, touchedFields, clearedSecrets);
|
||||
const save = (async () => {
|
||||
setAutoSaving(true);
|
||||
setAutoSaveState("idle");
|
||||
setNotice(null);
|
||||
try {
|
||||
const payload = await configureChannel(client, feature.name, values);
|
||||
setTouchedFields(new Set());
|
||||
setClearedSecrets(new Set());
|
||||
setAutoSaveState("saved");
|
||||
if (payload.nanobot_features) onFeaturesUpdate(payload.nanobot_features);
|
||||
return true;
|
||||
} catch (err) {
|
||||
setNotice((err as Error).message);
|
||||
return false;
|
||||
} finally {
|
||||
setAutoSaving(false);
|
||||
}
|
||||
})();
|
||||
autoSavePromiseRef.current = save;
|
||||
const saved = await save;
|
||||
if (autoSavePromiseRef.current === save) autoSavePromiseRef.current = null;
|
||||
return saved;
|
||||
}, [
|
||||
clearedSecrets,
|
||||
client,
|
||||
credentialDirty,
|
||||
feature.name,
|
||||
fieldValues,
|
||||
fields,
|
||||
mode,
|
||||
onFeaturesUpdate,
|
||||
pendingEnabled,
|
||||
saving,
|
||||
touchedFields,
|
||||
validating,
|
||||
]);
|
||||
const saveSecretOnBlur = (key: string) => {
|
||||
if (secretFieldKeys.has(key)) void saveCredentialDraft();
|
||||
const values = channelValuesForSubmit(editableFields, fieldValues, touchedFields, clearedSecrets);
|
||||
setAutoSaving(true);
|
||||
setAutoSaveState("idle");
|
||||
setNotice(null);
|
||||
try {
|
||||
const payload = await configureChannel(client, feature.name, values);
|
||||
setTouchedFields((current) => current === touchedFields ? new Set() : current);
|
||||
setClearedSecrets((current) => current === clearedSecrets ? new Set() : current);
|
||||
setAutoSaveState("saved");
|
||||
if (payload.nanobot_features) onFeaturesUpdate(payload.nanobot_features);
|
||||
return true;
|
||||
} catch (err) {
|
||||
setNotice((err as Error).message);
|
||||
return false;
|
||||
} finally {
|
||||
setAutoSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
useAutoSave(
|
||||
const edits = useEditCompletion(
|
||||
{ fieldValues, touchedFields: [...touchedFields], clearedSecrets: [...clearedSecrets] },
|
||||
mode === "credentials" && credentialDirty,
|
||||
actionPending,
|
||||
() => void saveCredentialDraft(),
|
||||
!touchedSecret,
|
||||
(mode === "credentials" || mode === "connect") && draftDirty,
|
||||
saveChannelDraft,
|
||||
true,
|
||||
feature.name,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -369,9 +329,9 @@ function ChannelSetupSurface({
|
||||
|
||||
useEffect(() => {
|
||||
if (!onBeforeCloseChange) return;
|
||||
onBeforeCloseChange(credentialDirty ? saveCredentialDraft : null);
|
||||
onBeforeCloseChange(draftDirty ? edits.commit : null);
|
||||
return () => onBeforeCloseChange(null);
|
||||
}, [credentialDirty, onBeforeCloseChange, saveCredentialDraft]);
|
||||
}, [draftDirty, onBeforeCloseChange, edits.commit]);
|
||||
|
||||
const copyCommand = () => {
|
||||
if (!setup.command) return;
|
||||
@@ -494,24 +454,28 @@ function ChannelSetupSurface({
|
||||
}
|
||||
};
|
||||
|
||||
return <ChannelSetupSurfaceView
|
||||
return <div onChangeCapture={edits.onChangeCapture} onFocusCapture={edits.onFocusCapture} onBlurCapture={edits.onBlurCapture}><ChannelSetupSurfaceView
|
||||
header={header} feature={feature} setup={setup}
|
||||
primaryFields={primaryFields} advancedFields={advancedFields} savedSecretFields={savedSecretFields}
|
||||
availablePresets={availablePresets} configuredFields={configuredFields}
|
||||
fieldValues={fieldValues} visibleSecrets={visibleSecrets} clearedSecrets={clearedSecrets} fieldErrors={fieldErrors}
|
||||
actionPending={actionPending} enabled={enabled} autoSaving={autoSaving} autoSaveState={autoSaveState}
|
||||
advancedOpen={advancedOpen} advancedPanelId={advancedPanelId} validation={validation} validating={validating} notice={notice}
|
||||
onAdvancedOpenChange={setAdvancedOpen} onChangeField={setFieldValue} onFieldBlur={saveSecretOnBlur}
|
||||
onAdvancedOpenChange={(open) => {
|
||||
if (!open && edits.needsCompletion()) {
|
||||
void edits.commit().then((saved) => { if (saved) setAdvancedOpen(false); });
|
||||
} else setAdvancedOpen(open);
|
||||
}} onChangeField={setFieldValue}
|
||||
onToggleSecret={toggleSecret} onClearSecret={setSecretCleared} onApplyPreset={applyPreset}
|
||||
onSubmit={saveCredentialSettings} onCheckConnection={checkCurrentSettings} onToggleEnabled={toggleEnabled}
|
||||
onSaveConnectionSettings={saveConnectionSettings} onCopyCommand={copyCommand} onNotice={setNotice}
|
||||
onCopyCommand={copyCommand} onNotice={setNotice}
|
||||
connectFlow={mode === "connect" && ConnectFlow ? <Suspense fallback={<ChannelPluginLoading compact />}>
|
||||
<ConnectFlow token={token} feature={feature}
|
||||
idleLabel={setup.primaryActionLabel ?? tx("settings.channels.connect", "Connect")}
|
||||
connectRequestId={connectRequestId} onOpenAdvanced={() => setAdvancedOpen(true)}
|
||||
onFeaturesUpdate={onFeaturesUpdate} />
|
||||
</Suspense> : undefined}
|
||||
/>;
|
||||
/></div>;
|
||||
}
|
||||
|
||||
function ChannelPluginLoading({ compact = false }: { compact?: boolean }) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { useRef, type ReactNode } from "react";
|
||||
import { Check, ChevronDown, Clipboard, Loader2 } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
@@ -38,14 +38,12 @@ export interface ChannelSetupSurfaceViewProps {
|
||||
connectFlow?: ReactNode;
|
||||
onAdvancedOpenChange: (open: boolean) => void;
|
||||
onChangeField: (key: string, value: string) => void;
|
||||
onFieldBlur: (key: string) => void;
|
||||
onToggleSecret: (key: string) => void;
|
||||
onClearSecret: (key: string, clear: boolean) => void;
|
||||
onApplyPreset: (preset: ChannelProviderPreset) => void;
|
||||
onSubmit: () => void;
|
||||
onCheckConnection: () => void;
|
||||
onToggleEnabled: (enabled: boolean) => void;
|
||||
onSaveConnectionSettings: () => void;
|
||||
onCopyCommand: () => void;
|
||||
onNotice: (notice: string | null) => void;
|
||||
}
|
||||
@@ -55,14 +53,17 @@ export function ChannelSetupSurfaceView({
|
||||
configuredFields, fieldValues, visibleSecrets, clearedSecrets, fieldErrors, actionPending,
|
||||
enabled, autoSaving, autoSaveState, advancedOpen, advancedPanelId, validation, validating,
|
||||
notice, connectFlow, onAdvancedOpenChange,
|
||||
onChangeField: setFieldValue, onFieldBlur: saveSecretOnBlur, onToggleSecret: toggleSecret,
|
||||
onChangeField: setFieldValue, onToggleSecret: toggleSecret,
|
||||
onClearSecret: setSecretCleared, onApplyPreset: applyPreset, onSubmit: saveCredentialSettings,
|
||||
onCheckConnection: checkCurrentSettings, onToggleEnabled: toggleEnabled,
|
||||
onSaveConnectionSettings: saveConnectionSettings, onCopyCommand: copyCommand, onNotice: setNotice,
|
||||
onCopyCommand: copyCommand, onNotice: setNotice,
|
||||
}: ChannelSetupSurfaceViewProps) {
|
||||
const { t } = useTranslation();
|
||||
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
|
||||
const mode = setup.mode ?? "credentials";
|
||||
// Keep feedback's footprint so blur-save updates cannot move the close target mid-click.
|
||||
const lastNotice = useRef(notice);
|
||||
if (notice) lastNotice.current = notice;
|
||||
const hasAdvanced = advancedFields.length > 0 || savedSecretFields.length > 0 || availablePresets.length > 0;
|
||||
const advancedFormProps = {
|
||||
fields: advancedFields,
|
||||
@@ -70,7 +71,6 @@ export function ChannelSetupSurfaceView({
|
||||
configuredFields,
|
||||
visibleSecrets,
|
||||
onChange: setFieldValue,
|
||||
onFieldBlur: saveSecretOnBlur,
|
||||
onToggleSecret: toggleSecret,
|
||||
errors: fieldErrors,
|
||||
clearedSecrets,
|
||||
@@ -217,7 +217,6 @@ export function ChannelSetupSurfaceView({
|
||||
configuredFields={configuredFields}
|
||||
visibleSecrets={visibleSecrets}
|
||||
onChange={setFieldValue}
|
||||
onFieldBlur={saveSecretOnBlur}
|
||||
onToggleSecret={toggleSecret}
|
||||
errors={fieldErrors}
|
||||
clearedSecrets={clearedSecrets}
|
||||
@@ -255,7 +254,7 @@ export function ChannelSetupSurfaceView({
|
||||
))}
|
||||
</div>
|
||||
{advancedFields.length ? (
|
||||
<div onBlur={() => void saveConnectionSettings()}>
|
||||
<div>
|
||||
{mode === "connect" ? (
|
||||
<ChannelFieldGroups {...advancedFormProps} requirements={[]} sectionLabels={setup.sectionLabels} />
|
||||
) : (
|
||||
@@ -282,10 +281,10 @@ export function ChannelSetupSurfaceView({
|
||||
aria-live="polite"
|
||||
className={cn(
|
||||
"rounded-control bg-muted/55 px-3 py-2.5 text-[12px] leading-5 text-muted-foreground",
|
||||
!notice && "sr-only",
|
||||
!notice && (lastNotice.current ? "invisible" : "sr-only"),
|
||||
)}
|
||||
>
|
||||
{notice ?? ""}
|
||||
{notice ?? lastNotice.current ?? ""}
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { SettingsPayload } from "@/lib/types";
|
||||
|
||||
export type SettingsExitGuard = (leave: () => void) => void;
|
||||
export type SettingsExitGuard = (leave: () => void, options?: { promptRestart?: boolean }) => void;
|
||||
|
||||
export type SettingsSectionKey =
|
||||
| "overview"
|
||||
|
||||
@@ -5,7 +5,7 @@ import { useModelPresetDrag } from "@/components/settings/models/useModelPresetD
|
||||
import { ReasoningEffortPicker } from "@/components/settings/models/ReasoningEffortPicker";
|
||||
import { RemoveActionButton } from "@/components/settings/shared/RemoveActionButton";
|
||||
import { ToggleButton } from "@/components/ui/toggle-button";
|
||||
import { useAutoSave } from "@/components/settings/shared/useAutoSave";
|
||||
import type { EditCompletion } from "@/components/settings/shared/useEditCompletion";
|
||||
import { useEffect, useId, useRef, useState, type Dispatch, type SetStateAction } from "react";
|
||||
import {
|
||||
GripVertical,
|
||||
@@ -197,11 +197,13 @@ export function ModelPresetDeleteDialog({
|
||||
}
|
||||
|
||||
export function ModelsSettings({
|
||||
editCompletion: edits,
|
||||
token,
|
||||
form,
|
||||
setForm,
|
||||
editingPresetName,
|
||||
presetNameError,
|
||||
error,
|
||||
settings,
|
||||
dirty,
|
||||
creating,
|
||||
@@ -226,11 +228,13 @@ export function ModelsSettings({
|
||||
onSelectConfiguration,
|
||||
onDeleteConfiguration,
|
||||
}: {
|
||||
editCompletion: EditCompletion;
|
||||
token: string;
|
||||
form: AgentSettingsDraft;
|
||||
setForm: Dispatch<SetStateAction<AgentSettingsDraft>>;
|
||||
editingPresetName: string;
|
||||
presetNameError: string | null;
|
||||
error?: string | null;
|
||||
settings: SettingsPayload;
|
||||
dirty: boolean;
|
||||
creating: boolean;
|
||||
@@ -256,7 +260,6 @@ export function ModelsSettings({
|
||||
onDeleteConfiguration: (preset: SettingsPayload["model_presets"][number], onDeleted: () => void) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
useAutoSave(form, dirty, saving, onSave, !creating && !!form.model.trim());
|
||||
const tx = (key: string, fallback: string, values?: Record<string, unknown>) =>
|
||||
t(key, { defaultValue: fallback, ...(values ?? {}) });
|
||||
const [editorOpen, setEditorOpen] = useState(false);
|
||||
@@ -315,7 +318,7 @@ export function ModelsSettings({
|
||||
null;
|
||||
useEffect(() => {
|
||||
setAdvancedOpen(false);
|
||||
}, [editorOpen, selectedPreset?.name]);
|
||||
}, [editorOpen, edits.identity]);
|
||||
|
||||
const configuredProviders = settings.providers.filter((provider) => provider.configured);
|
||||
const selectedProvider = settings.providers.find((provider) => provider.name === form.provider);
|
||||
@@ -331,6 +334,7 @@ export function ModelsSettings({
|
||||
? form.provider
|
||||
: "";
|
||||
const selectProvider = (provider: string) => {
|
||||
edits.complete();
|
||||
const clearSuggestedName =
|
||||
creating &&
|
||||
provider !== form.provider &&
|
||||
@@ -364,6 +368,7 @@ export function ModelsSettings({
|
||||
form.maxTokens <= 0 ||
|
||||
!Number.isSafeInteger(form.contextWindowTokens) ||
|
||||
form.contextWindowTokens <= 0 ||
|
||||
!Number.isFinite(form.temperature) ||
|
||||
form.temperature < 0 ||
|
||||
form.temperature > 2;
|
||||
const selectedPresetReferenced = Boolean(
|
||||
@@ -375,7 +380,7 @@ export function ModelsSettings({
|
||||
disabled: callOrderBusy,
|
||||
onReorder: (keys) => onChangeCallOrder(keys.map((key) => presetRows.find((row) => row.key === key)!.name)),
|
||||
});
|
||||
const selectPreset = (
|
||||
const selectPreset = async (
|
||||
preset: SettingsPayload["model_presets"][number],
|
||||
rowKey: string,
|
||||
) => {
|
||||
@@ -383,6 +388,7 @@ export function ModelsSettings({
|
||||
editorTriggerRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
|
||||
const toggleCurrentPreset =
|
||||
!creating && selectedPreset?.name === preset.name && activeEditorRowKey === rowKey;
|
||||
if (edits.needsCompletion() && !(await edits.commit())) return;
|
||||
onSelectConfiguration(preset.name);
|
||||
if (toggleCurrentPreset) {
|
||||
setEditorOpen((open) => !open);
|
||||
@@ -514,6 +520,7 @@ export function ModelsSettings({
|
||||
onProviderOAuthLogin={onProviderOAuthLogin}
|
||||
providerSigningIn={selectedProviderSigningIn}
|
||||
onChange={(model, info) => {
|
||||
edits.complete();
|
||||
const contextWindow = info?.context_window;
|
||||
const initializeContext = creating && !presetContextInitializedRef.current
|
||||
&& typeof contextWindow === "number" && Number.isSafeInteger(contextWindow) && contextWindow > 0;
|
||||
@@ -537,6 +544,7 @@ export function ModelsSettings({
|
||||
</SettingsRow>
|
||||
<SettingsRow title={tx("settings.models.reasoningEffort", "Reasoning effort")}>
|
||||
<ReasoningEffortPicker
|
||||
onSelect={edits.complete}
|
||||
token={token}
|
||||
provider={selectedProvider ?? settings.providers.find((provider) => provider.name === selectedPreset?.resolved_provider)}
|
||||
model={form.model}
|
||||
@@ -546,7 +554,11 @@ export function ModelsSettings({
|
||||
onChange={(reasoningEffort) => setForm((prev) => ({ ...prev, reasoningEffort }))}
|
||||
/>
|
||||
</SettingsRow>
|
||||
<Dialog open={advancedOpen} onOpenChange={setAdvancedOpen}>
|
||||
<Dialog open={advancedOpen} onOpenChange={(open) => {
|
||||
if (!open && !creating && edits.needsCompletion()) {
|
||||
void edits.commit().then((saved) => { if (saved) setAdvancedOpen(false); });
|
||||
} else setAdvancedOpen(open);
|
||||
}}>
|
||||
<DialogTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
@@ -612,6 +624,7 @@ export function ModelsSettings({
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{error ? <p role="alert" className="settings-list-inset pb-4 text-[13px] text-destructive">{error}</p> : null}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
<div className="settings-list-inset flex min-h-[58px] flex-col gap-3 py-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
@@ -911,10 +924,16 @@ export function ModelsSettings({
|
||||
</div>
|
||||
</section>
|
||||
<Dialog open={editorOpen && (creating || selectedPreset !== null)} onOpenChange={(open) => {
|
||||
setEditorOpen(open);
|
||||
if (!open && creating) onCancelCreate();
|
||||
if (!open && !creating && edits.needsCompletion()) {
|
||||
void edits.commit().then((saved) => { if (saved) setEditorOpen(false); });
|
||||
} else {
|
||||
setEditorOpen(open);
|
||||
if (!open && creating) onCancelCreate();
|
||||
}
|
||||
}}>
|
||||
<DialogContent aria-describedby={undefined}
|
||||
onChangeCapture={edits.onChangeCapture} onFocusCapture={edits.onFocusCapture}
|
||||
onBlurCapture={edits.onBlurCapture}
|
||||
onEscapeKeyDown={() => setHideEditorReturnFocus(true)}
|
||||
className="relative max-h-[85dvh] w-[min(calc(100vw-2rem),40rem)] max-w-none gap-0 overflow-y-auto p-0"
|
||||
onCloseAutoFocus={(event) => {
|
||||
@@ -925,6 +944,7 @@ export function ModelsSettings({
|
||||
{creating ? tx("settings.models.newPreset", "New model preset") : selectedPreset?.name}
|
||||
</DialogTitle>
|
||||
<div className="settings-grid !px-0 pt-8">{renderPresetEditor()}</div>
|
||||
{error && !advancedOpen ? <p role="alert" className="settings-list-inset pb-4 text-[13px] text-destructive">{error}</p> : null}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
@@ -951,6 +971,7 @@ function ModelAdvancedFields({
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
|
||||
const [temperatureDraft, setTemperatureDraft] = useState<{ text: string; value: number } | null>(null);
|
||||
return (
|
||||
<>
|
||||
<ModelTokenBudgetRow
|
||||
@@ -965,10 +986,13 @@ function ModelAdvancedFields({
|
||||
min={0}
|
||||
max={2}
|
||||
step={0.1}
|
||||
value={temperature}
|
||||
value={temperatureDraft && Object.is(temperatureDraft.value, temperature) ? temperatureDraft.text : temperature}
|
||||
aria-invalid={!Number.isFinite(temperature) || temperature < 0 || temperature > 2}
|
||||
onChange={(event) => {
|
||||
const value = Number(event.target.value);
|
||||
if (Number.isFinite(value)) onChange({ temperature: value });
|
||||
const text = event.target.value;
|
||||
const value = text.trim() ? Number(text) : Number.NaN;
|
||||
setTemperatureDraft({ text, value });
|
||||
onChange({ temperature: value });
|
||||
}}
|
||||
className="h-9 text-[13px]"
|
||||
/>
|
||||
|
||||
@@ -11,13 +11,14 @@ import type { SettingsPayload } from "@/lib/types";
|
||||
const NO_PROVIDER = {};
|
||||
const DEFAULT_VALUE = ":default";
|
||||
|
||||
export function ReasoningEffortPicker({ token, provider, model, savedValues, value, onChange }: {
|
||||
export function ReasoningEffortPicker({ token, provider, model, savedValues, value, onChange, onSelect }: {
|
||||
token: string;
|
||||
provider: SettingsPayload["providers"][number] | undefined;
|
||||
model: string;
|
||||
savedValues?: string[];
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
onSelect?: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
@@ -37,7 +38,7 @@ export function ReasoningEffortPicker({ token, provider, model, savedValues, val
|
||||
open,
|
||||
values,
|
||||
selectedValue: value || DEFAULT_VALUE,
|
||||
onSelect: (selected) => { onChange(selected === DEFAULT_VALUE ? "" : selected); close(); },
|
||||
onSelect: (selected) => { onSelect?.(); onChange(selected === DEFAULT_VALUE ? "" : selected); close(); },
|
||||
onClose: close,
|
||||
});
|
||||
return (
|
||||
@@ -82,7 +83,11 @@ export function ReasoningEffortPicker({ token, provider, model, savedValues, val
|
||||
onOpenAutoFocus={(event) => event.preventDefault()}
|
||||
onCloseAutoFocus={(event) => {
|
||||
event.preventDefault();
|
||||
if (restoreFocus.current) input.current?.focus({ preventScroll: true });
|
||||
const active = document.activeElement;
|
||||
const owner = input.current?.closest('[role="dialog"]');
|
||||
if (restoreFocus.current && (active === document.body || active === input.current || active === owner)) {
|
||||
input.current?.focus({ preventScroll: true });
|
||||
}
|
||||
restoreFocus.current = false;
|
||||
}}
|
||||
onEscapeKeyDown={() => { restoreFocus.current = true; }}
|
||||
|
||||
@@ -66,7 +66,6 @@ interface ModelSettingsActionsOptions {
|
||||
remoteBrowserAccess: boolean;
|
||||
closeProviderOAuthFlow: (cancelPending?: boolean) => void;
|
||||
installCapabilities: (names: string[]) => Promise<boolean>;
|
||||
modelDirty: boolean;
|
||||
configuredModelProviderOptions: Array<{ name: string; label: string }>;
|
||||
}
|
||||
|
||||
@@ -83,7 +82,6 @@ export function useModelSettingsActions({
|
||||
remoteBrowserAccess,
|
||||
closeProviderOAuthFlow,
|
||||
installCapabilities,
|
||||
modelDirty,
|
||||
configuredModelProviderOptions,
|
||||
}: ModelSettingsActionsOptions) {
|
||||
const oauthMounted = useRef(true);
|
||||
@@ -128,9 +126,20 @@ export function useModelSettingsActions({
|
||||
visibleProviderKeys,
|
||||
} = state;
|
||||
|
||||
const latestSettings = useRef(settings);
|
||||
latestSettings.current = settings;
|
||||
// Renaming changes the server key, not the owner of already queued edits.
|
||||
const editTargetSequence = useRef(0);
|
||||
const editTargetRef = useRef({ name: modelPresetEditingName, identity: 0 });
|
||||
if (editTargetRef.current.name !== modelPresetEditingName) {
|
||||
editTargetSequence.current += 1;
|
||||
editTargetRef.current = { name: modelPresetEditingName, identity: editTargetSequence.current };
|
||||
}
|
||||
const editTarget = editTargetRef.current;
|
||||
|
||||
const presetNameConflict = (name: string, currentName?: string) => {
|
||||
const normalized = name.toLowerCase();
|
||||
return settings?.model_presets.some(
|
||||
return latestSettings.current?.model_presets.some(
|
||||
(preset) =>
|
||||
!preset.is_default &&
|
||||
preset.name !== currentName &&
|
||||
@@ -158,15 +167,15 @@ export function useModelSettingsActions({
|
||||
const saveModelSettings = async () => {
|
||||
if (
|
||||
!settings ||
|
||||
saving ||
|
||||
modelCallOrderSaving ||
|
||||
modelConfigurationSaving ||
|
||||
!Number.isSafeInteger(form.maxTokens) ||
|
||||
form.maxTokens <= 0 ||
|
||||
!Number.isSafeInteger(form.contextWindowTokens) ||
|
||||
form.contextWindowTokens <= 0
|
||||
form.contextWindowTokens <= 0 ||
|
||||
!Number.isFinite(form.temperature) || form.temperature < 0 || form.temperature > 2
|
||||
) {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (modelPresetCreating) {
|
||||
@@ -181,11 +190,11 @@ export function useModelSettingsActions({
|
||||
form.temperature < 0 ||
|
||||
form.temperature > 2
|
||||
) {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
if (presetNameConflict(name)) {
|
||||
showPresetNameConflict();
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
setModelPresetNameError(null);
|
||||
setModelConfigurationSaving(true);
|
||||
@@ -207,7 +216,7 @@ export function useModelSettingsActions({
|
||||
});
|
||||
const createdPreset = payload.created_model_preset;
|
||||
const nextOrder = createdPreset ? [...modelCallOrder, createdPreset] : null;
|
||||
applyPayload(payload);
|
||||
applyPayload(payload, { preserveCapabilityForms: true });
|
||||
if (createdPreset) {
|
||||
setForm(agentDraftFromPayload(payload, createdPreset));
|
||||
setModelPresetEditingName(createdPreset);
|
||||
@@ -216,7 +225,7 @@ export function useModelSettingsActions({
|
||||
let finalPayload = payload;
|
||||
if (nextOrder) {
|
||||
const orderedPayload = await updateModelCallOrder(client, nextOrder);
|
||||
applyPayload(orderedPayload);
|
||||
applyPayload(orderedPayload, { preserveCapabilityForms: true });
|
||||
finalPayload = orderedPayload;
|
||||
}
|
||||
if (createdPreset) {
|
||||
@@ -232,19 +241,19 @@ export function useModelSettingsActions({
|
||||
} finally {
|
||||
setModelConfigurationSaving(false);
|
||||
}
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!modelDirty) return;
|
||||
const selectedPreset = settings.model_presets.find(
|
||||
(preset) => !preset.is_default && preset.name === modelPresetEditingName,
|
||||
const targetName = editTarget.name;
|
||||
const selectedPreset = latestSettings.current?.model_presets.find(
|
||||
(preset) => !preset.is_default && preset.name === targetName,
|
||||
);
|
||||
if (!selectedPreset) return;
|
||||
if (!selectedPreset) return false;
|
||||
const nextName = form.modelPreset.trim();
|
||||
const nameChanged = form.modelPreset !== selectedPreset.name;
|
||||
if (nameChanged && presetNameConflict(nextName, selectedPreset.name)) {
|
||||
showPresetNameConflict();
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
setModelPresetNameError(null);
|
||||
const reasoningEffort = form.reasoningEffort || null;
|
||||
@@ -274,14 +283,20 @@ export function useModelSettingsActions({
|
||||
extraBody: form.extraBody !== providerJsonValue(selectedPreset.extra_body) ? form.extraBody : undefined,
|
||||
} : {}),
|
||||
});
|
||||
applyPayload(payload);
|
||||
setForm(agentDraftFromPayload(payload, nextName));
|
||||
setModelPresetEditingName(nextName);
|
||||
latestSettings.current = payload;
|
||||
editTarget.name = nextName;
|
||||
applyPayload(payload, { preserveAgentForm: true, preserveCapabilityForms: true });
|
||||
setForm((current) => current === form ? agentDraftFromPayload(payload, nextName) : current);
|
||||
if (editTargetRef.current === editTarget) {
|
||||
setModelPresetEditingName(nextName);
|
||||
}
|
||||
onModelNameChange(payload.agent.model || null);
|
||||
setModelPresetNameError(null);
|
||||
setError(null);
|
||||
return true;
|
||||
} catch (err) {
|
||||
handlePresetSaveError(err);
|
||||
return false;
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -294,8 +309,8 @@ export function useModelSettingsActions({
|
||||
name: modelPresetEditingName,
|
||||
...values,
|
||||
});
|
||||
applyPayload(payload);
|
||||
setForm(agentDraftFromPayload(payload, modelPresetEditingName));
|
||||
applyPayload(payload, { preserveAgentForm: true, preserveCapabilityForms: true });
|
||||
setForm((current) => current === form ? agentDraftFromPayload(payload, modelPresetEditingName) : current);
|
||||
setError(null);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
@@ -364,7 +379,7 @@ export function useModelSettingsActions({
|
||||
setModelCallOrderSaving(true);
|
||||
try {
|
||||
const payload = await updateModelCallOrder(client, nextOrder);
|
||||
applyPayload(payload, { preserveAgentForm: true });
|
||||
applyPayload(payload, { preserveAgentForm: true, preserveCapabilityForms: true });
|
||||
onModelNameChange(payload.agent.model || null);
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
@@ -380,7 +395,7 @@ export function useModelSettingsActions({
|
||||
setModelMigrationSaving(true);
|
||||
try {
|
||||
const payload = await migrateModelConfigurations(client);
|
||||
applyPayload(payload);
|
||||
applyPayload(payload, { preserveCapabilityForms: true });
|
||||
onModelNameChange(payload.agent.model || null);
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
@@ -402,7 +417,7 @@ export function useModelSettingsActions({
|
||||
setSaving(true);
|
||||
try {
|
||||
const payload = await deleteModelConfiguration(client, modelPresetPendingDelete.name);
|
||||
applyPayload(payload);
|
||||
applyPayload(payload, { preserveCapabilityForms: true });
|
||||
setModelPresetPendingDelete(null);
|
||||
setError(null);
|
||||
return true;
|
||||
@@ -454,7 +469,7 @@ export function useModelSettingsActions({
|
||||
if (field === "profile") update.profile = providerForm.profile.trim();
|
||||
}
|
||||
const payload = await updateProviderSettings(client, update);
|
||||
applyPayload(payload, { preserveAgentForm: true });
|
||||
applyPayload(payload, { preserveAgentForm: true, preserveCapabilityForms: true });
|
||||
if (payload.requires_restart) {
|
||||
setPendingRestartSections((prev) => ({ ...prev, image: true }));
|
||||
}
|
||||
@@ -491,7 +506,7 @@ export function useModelSettingsActions({
|
||||
extraQuery: draft.extraQuery.trim(),
|
||||
thinkingStyle: draft.thinkingStyle.trim(),
|
||||
});
|
||||
applyPayload(payload, { preserveAgentForm: true });
|
||||
applyPayload(payload, { preserveAgentForm: true, preserveCapabilityForms: true });
|
||||
setError(null);
|
||||
return payload;
|
||||
} catch (err) {
|
||||
@@ -546,7 +561,7 @@ export function useModelSettingsActions({
|
||||
}
|
||||
popup?.close();
|
||||
closeProviderOAuthFlow(false);
|
||||
applyPayload(payload, { preserveAgentForm: true });
|
||||
applyPayload(payload, { preserveAgentForm: true, preserveCapabilityForms: true });
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
popup?.close();
|
||||
@@ -571,7 +586,7 @@ export function useModelSettingsActions({
|
||||
);
|
||||
if (providerOAuthFlowRef.current?.flow_id !== flow.flow_id) return;
|
||||
if (isProviderOAuthPending(payload)) return;
|
||||
applyPayload(payload, { preserveAgentForm: true });
|
||||
applyPayload(payload, { preserveAgentForm: true, preserveCapabilityForms: true });
|
||||
setError(null);
|
||||
closeProviderOAuthFlow(false);
|
||||
} catch (err) {
|
||||
@@ -619,6 +634,7 @@ export function useModelSettingsActions({
|
||||
};
|
||||
|
||||
return {
|
||||
modelEditIdentity: String(editTarget.identity),
|
||||
beginModelPresetCreation,
|
||||
cancelModelPresetCreation,
|
||||
changeModelCallOrder,
|
||||
|
||||
@@ -56,7 +56,7 @@ export function useProviderOAuthPolling({
|
||||
timer = window.setTimeout(() => void poll(), 1000);
|
||||
return;
|
||||
}
|
||||
applyPayload(payload, { preserveAgentForm: true });
|
||||
applyPayload(payload, { preserveAgentForm: true, preserveCapabilityForms: true });
|
||||
setError(null);
|
||||
closeProviderOAuthFlow(false);
|
||||
} catch (err) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { useState, type ReactNode } from "react";
|
||||
import { CircleAlert, Loader2, RotateCcw, X } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
@@ -411,16 +411,20 @@ export function NumberInput({
|
||||
onChange: (value: number) => void;
|
||||
suffix?: string;
|
||||
}) {
|
||||
const [draft, setDraft] = useState<{ text: string; value: number } | null>(null);
|
||||
return (
|
||||
<div className="relative w-full">
|
||||
<Input
|
||||
type="number"
|
||||
min={min}
|
||||
max={max}
|
||||
value={value}
|
||||
aria-invalid={!Number.isFinite(value) || value < min || value > max}
|
||||
value={draft && Object.is(draft.value, value) ? draft.text : Number.isFinite(value) ? value : ""}
|
||||
onChange={(event) => {
|
||||
const parsed = Number(event.target.value);
|
||||
if (Number.isFinite(parsed)) onChange(parsed);
|
||||
const text = event.target.value;
|
||||
const parsed = text.trim() ? Number(text) : Number.NaN;
|
||||
setDraft({ text, value: parsed });
|
||||
onChange(parsed);
|
||||
}}
|
||||
className={cn("h-9 w-full rounded-full text-[13px]", suffix && "pr-12")}
|
||||
/>
|
||||
|
||||
@@ -22,7 +22,7 @@ export function SettingsAdvancedOptions({ children }: { children: ReactNode }) {
|
||||
}
|
||||
|
||||
export function SettingsFeature({
|
||||
title, enabled, onChange, disabled, initialOpen = false, error, children,
|
||||
title, enabled, onChange, disabled, initialOpen = false, error, children, onBeforeClose,
|
||||
}: {
|
||||
title: string;
|
||||
enabled: boolean;
|
||||
@@ -31,6 +31,7 @@ export function SettingsFeature({
|
||||
initialOpen?: boolean;
|
||||
error?: string;
|
||||
children?: ReactNode;
|
||||
onBeforeClose?: () => Promise<boolean>;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(initialOpen && enabled);
|
||||
@@ -43,7 +44,11 @@ export function SettingsFeature({
|
||||
}, [initialOpen, enabled]);
|
||||
return (
|
||||
<section ref={section} aria-label={title}>
|
||||
<Dialog open={Boolean(children) && open} onOpenChange={setOpen}>
|
||||
<Dialog open={Boolean(children) && open} onOpenChange={(next) => {
|
||||
if (!next && onBeforeClose) {
|
||||
void onBeforeClose().then((saved) => { if (saved) setOpen(false); });
|
||||
} else setOpen(next);
|
||||
}}>
|
||||
<SettingsGroup>
|
||||
<SettingsRow title={children ? (
|
||||
<DialogTrigger asChild>
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
/** Save a valid draft once per edit; failures wait for another edit or explicit retry. */
|
||||
export function useAutoSave(value: unknown, dirty: boolean, saving: boolean, onSave: () => void, enabled = true) {
|
||||
const latest = useRef(onSave);
|
||||
latest.current = onSave;
|
||||
const attempted = useRef<string | null>(null);
|
||||
const signature = JSON.stringify(value);
|
||||
useEffect(() => {
|
||||
if (!dirty) { attempted.current = null; return; }
|
||||
if (!enabled || saving || attempted.current === signature) return;
|
||||
const timer = window.setTimeout(() => {
|
||||
attempted.current = signature;
|
||||
latest.current();
|
||||
}, 600);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [signature, dirty, saving, enabled]);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { useEffect, useRef, type FocusEvent, type FormEvent } from "react";
|
||||
|
||||
function isDraftInput(target: EventTarget) {
|
||||
return target instanceof HTMLTextAreaElement ||
|
||||
(target instanceof HTMLInputElement && !["checkbox", "radio", "button", "submit"].includes(target.type));
|
||||
}
|
||||
|
||||
type Draft = {
|
||||
signature: string;
|
||||
identity: string;
|
||||
revision: number;
|
||||
dirty: boolean;
|
||||
enabled: boolean;
|
||||
onSave: () => void | Promise<unknown>;
|
||||
};
|
||||
|
||||
/** Completion belongs to the draft owner; queued saves retain that version and target. */
|
||||
export function useEditCompletion(value: unknown, dirty: boolean, onSave: Draft["onSave"], enabled = true, identity = "") {
|
||||
const signature = JSON.stringify(value);
|
||||
const version = useRef({ signature, identity, revision: 0 });
|
||||
if (version.current.signature !== signature || version.current.identity !== identity) {
|
||||
version.current = { signature, identity, revision: version.current.revision + 1 };
|
||||
}
|
||||
const revision = version.current.revision;
|
||||
const latest = useRef<Draft>({ signature, dirty, enabled, onSave, identity, revision });
|
||||
latest.current = { signature, dirty, enabled, onSave, identity, revision };
|
||||
const focused = useRef(false);
|
||||
const completed = useRef(false);
|
||||
const previousIdentity = useRef(identity);
|
||||
const attempts = useRef(new Map<string, Promise<boolean>>());
|
||||
const tail = useRef(Promise.resolve(true));
|
||||
const outstanding = useRef(0);
|
||||
const queuedDraft = useRef<Draft | null>(null);
|
||||
const commitDraft = (draft: Draft): Promise<boolean> => {
|
||||
const queued = queuedDraft.current;
|
||||
const changedDuringSave = outstanding.current > 0 && queued &&
|
||||
queued.identity === draft.identity && queued.signature !== draft.signature;
|
||||
if (!draft.dirty && !changedDuringSave) return outstanding.current > 0 ? tail.current : Promise.resolve(true);
|
||||
if (!draft.enabled) return Promise.resolve(false);
|
||||
const version = `${draft.identity}:${draft.revision}`;
|
||||
const existing = attempts.current.get(version);
|
||||
if (existing) return existing;
|
||||
const request = tail.current.then(async () => {
|
||||
try {
|
||||
return (await draft.onSave()) !== false;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
outstanding.current += 1;
|
||||
queuedDraft.current = draft;
|
||||
attempts.current.set(version, request);
|
||||
tail.current = request;
|
||||
void request.then((saved) => {
|
||||
outstanding.current -= 1;
|
||||
if (!saved || latest.current.revision !== draft.revision) attempts.current.delete(version);
|
||||
});
|
||||
return request;
|
||||
};
|
||||
const commit = async (): Promise<boolean> => {
|
||||
focused.current = false;
|
||||
const draft = latest.current;
|
||||
const saved = await commitDraft(draft);
|
||||
if (!saved) return false;
|
||||
const current = latest.current;
|
||||
if (current.identity === draft.identity && current.signature !== draft.signature) return commit();
|
||||
return true;
|
||||
};
|
||||
const commitRef = useRef(commit);
|
||||
commitRef.current = commit;
|
||||
const commitDraftRef = useRef(commitDraft);
|
||||
commitDraftRef.current = commitDraft;
|
||||
useEffect(() => {
|
||||
if (!dirty && outstanding.current === 0) attempts.current.clear();
|
||||
if (previousIdentity.current !== identity) {
|
||||
previousIdentity.current = identity;
|
||||
focused.current = false;
|
||||
return;
|
||||
}
|
||||
if ((!focused.current || completed.current) && (dirty || outstanding.current > 0)) void commitDraftRef.current(latest.current);
|
||||
completed.current = false;
|
||||
}, [signature, dirty, enabled, identity]);
|
||||
useEffect(() => () => { void commitRef.current(); }, []);
|
||||
return {
|
||||
identity,
|
||||
commit,
|
||||
complete: () => { completed.current = true; },
|
||||
onChangeCapture: (event: FormEvent<HTMLElement>) => {
|
||||
if (isDraftInput(event.target)) {
|
||||
focused.current = true;
|
||||
completed.current = false;
|
||||
} else completed.current = true;
|
||||
},
|
||||
needsCompletion: () => latest.current.dirty || outstanding.current > 0,
|
||||
onFocusCapture: (event: FocusEvent<HTMLElement>) => {
|
||||
if (isDraftInput(event.target)) focused.current = true;
|
||||
},
|
||||
onBlurCapture: (event: FocusEvent<HTMLElement>) => {
|
||||
if (!isDraftInput(event.target)) return;
|
||||
focused.current = false;
|
||||
void commitDraft(latest.current);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type EditCompletion = ReturnType<typeof useEditCompletion>;
|
||||
@@ -20,7 +20,7 @@ type ChannelFilter = "all" | "enabled";
|
||||
export function ChannelsSettings({
|
||||
token, nanobotFeatures, loading, actionKey, chatAppsDocsUrl, showBrandLogos,
|
||||
error, requiresRestartPending, onAction, onFeaturesUpdate, onDismissStatus,
|
||||
onRestart, isRestarting, onConfigureMcp,
|
||||
onRestart, isRestarting, onConfigureMcp, onBeforeCloseChange,
|
||||
}: {
|
||||
token: string;
|
||||
nanobotFeatures: NanobotFeaturesPayload | null;
|
||||
@@ -34,6 +34,7 @@ export function ChannelsSettings({
|
||||
onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void;
|
||||
onDismissStatus: () => void;
|
||||
onConfigureMcp?: (name: string) => void;
|
||||
onBeforeCloseChange?: (handler: (() => Promise<boolean>) | null) => void;
|
||||
onRestart?: () => void;
|
||||
isRestarting?: boolean;
|
||||
}) {
|
||||
@@ -93,8 +94,11 @@ export function ChannelsSettings({
|
||||
});
|
||||
}, []);
|
||||
const setBeforeChannelClose = useCallback(
|
||||
(handler: (() => Promise<boolean>) | null) => { beforeCloseRef.current = handler; },
|
||||
[],
|
||||
(handler: (() => Promise<boolean>) | null) => {
|
||||
beforeCloseRef.current = handler;
|
||||
onBeforeCloseChange?.(handler);
|
||||
},
|
||||
[onBeforeCloseChange],
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -34,7 +34,7 @@ import { createSystemSettingsActions } from "@/components/settings/system/create
|
||||
import { useSystemSettingsEffects } from "@/components/settings/system/useSystemSettingsEffects";
|
||||
import { useSystemSettingsState } from "@/components/settings/system/useSystemSettingsState";
|
||||
import { usePageVisibility } from "@/hooks/usePageVisibility";
|
||||
import { useAutoSave } from "@/components/settings/shared/useAutoSave";
|
||||
import { useEditCompletion } from "@/components/settings/shared/useEditCompletion";
|
||||
import { cancelProviderOAuth, fetchSettings, fetchSettingsUsage } from "@/lib/api";
|
||||
import {
|
||||
LOCAL_PREFS_CHANGED_EVENT,
|
||||
@@ -107,10 +107,12 @@ export function useSettingsController({
|
||||
} = modelState;
|
||||
const capabilityState = useCapabilitySettingsState(initialSettings);
|
||||
const {
|
||||
imageGenerationForm, imageGenerationSaving, networkSafetyForm,
|
||||
imageGenerationForm, networkSafetyForm,
|
||||
setImageGenerationForm, setNetworkSafetyForm, setTranscriptionForm, setWebSearchForm,
|
||||
transcriptionForm, transcriptionSaving, webSearchForm, webSearchSaving,
|
||||
transcriptionForm, webSearchForm,
|
||||
} = capabilityState;
|
||||
const draftsRef = useRef({ form, imageGenerationForm, networkSafetyForm, transcriptionForm, webSearchForm });
|
||||
draftsRef.current = { form, imageGenerationForm, networkSafetyForm, transcriptionForm, webSearchForm };
|
||||
const systemState = useSystemSettingsState();
|
||||
const featureCatalog = systemState.nanobotFeatures?.features ?? [];
|
||||
|
||||
@@ -136,8 +138,6 @@ export function useSettingsController({
|
||||
setForm(nextForm);
|
||||
setModelPresetEditingName(nextForm.modelPreset);
|
||||
setModelPresetCreating(false);
|
||||
} else {
|
||||
setForm((current) => ({ ...current, timezone: payload.agent.timezone }));
|
||||
}
|
||||
setModelCallOrder(payload.model_call_order ?? []);
|
||||
if (!options.preserveCapabilityForms) {
|
||||
@@ -199,18 +199,25 @@ export function useSettingsController({
|
||||
if (!shouldApplyRestartedSettings || !initialSettings) {
|
||||
return;
|
||||
}
|
||||
applyPayload(initialSettings);
|
||||
applyPayload(initialSettings, { preserveAgentForm: true, preserveCapabilityForms: true });
|
||||
}, [applyPayload, initialSettings, settings]);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const showLoading = settings === null;
|
||||
const requestInitialSettings = latestInitialSettingsRef.current;
|
||||
const requestDrafts = draftsRef.current;
|
||||
if (showLoading) setLoading(true);
|
||||
fetchSettings(getToken())
|
||||
.then((payload) => {
|
||||
if (!cancelled && latestInitialSettingsRef.current === requestInitialSettings) {
|
||||
applyPayload(payload);
|
||||
const current = draftsRef.current;
|
||||
applyPayload(payload, {
|
||||
preserveAgentForm: current.form !== requestDrafts.form,
|
||||
preserveCapabilityForms: current.imageGenerationForm !== requestDrafts.imageGenerationForm ||
|
||||
current.networkSafetyForm !== requestDrafts.networkSafetyForm ||
|
||||
current.transcriptionForm !== requestDrafts.transcriptionForm || current.webSearchForm !== requestDrafts.webSearchForm,
|
||||
});
|
||||
setError(null);
|
||||
}
|
||||
})
|
||||
@@ -357,10 +364,17 @@ export function useSettingsController({
|
||||
onNativeEngineRestart
|
||||
) {
|
||||
setHostEngineApplying(true);
|
||||
const requestDrafts = draftsRef.current;
|
||||
try {
|
||||
const nextToken = await onNativeEngineRestart();
|
||||
const payload = await fetchSettings(nextToken);
|
||||
applyPayload(payload);
|
||||
const current = draftsRef.current;
|
||||
applyPayload(payload, {
|
||||
preserveAgentForm: current.form !== requestDrafts.form,
|
||||
preserveCapabilityForms: current.imageGenerationForm !== requestDrafts.imageGenerationForm ||
|
||||
current.networkSafetyForm !== requestDrafts.networkSafetyForm ||
|
||||
current.transcriptionForm !== requestDrafts.transcriptionForm || current.webSearchForm !== requestDrafts.webSearchForm,
|
||||
});
|
||||
setPendingRestartSections(EMPTY_PENDING_RESTART_SECTIONS);
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
@@ -390,7 +404,7 @@ export function useSettingsController({
|
||||
try {
|
||||
const nextToken = await onNativeEngineRestart();
|
||||
const refreshed = await fetchSettings(nextToken);
|
||||
applyPayload(refreshed);
|
||||
applyPayload(refreshed, { preserveAgentForm: true, preserveCapabilityForms: true });
|
||||
setPendingRestartSections(EMPTY_PENDING_RESTART_SECTIONS);
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
@@ -427,7 +441,6 @@ export function useSettingsController({
|
||||
remoteBrowserAccess,
|
||||
closeProviderOAuthFlow,
|
||||
installCapabilities,
|
||||
modelDirty,
|
||||
configuredModelProviderOptions,
|
||||
});
|
||||
const capabilityActions = useCapabilitySettingsActions({
|
||||
@@ -439,17 +452,17 @@ export function useSettingsController({
|
||||
maybeRestartHostEngine,
|
||||
setPendingRestartSections,
|
||||
installCapabilities,
|
||||
imageGenerationDirty,
|
||||
transcriptionDirty,
|
||||
networkSafetyDirty,
|
||||
});
|
||||
useAutoSave(imageGenerationForm, imageGenerationDirty, imageGenerationSaving, capabilityActions.saveImageGenerationSettings,
|
||||
const modelEdits = useEditCompletion(form, modelDirty, modelActions.saveModelSettings,
|
||||
!modelState.modelPresetCreating && !!form.model.trim(), modelActions.modelEditIdentity);
|
||||
const safetyEdits = useEditCompletion(networkSafetyForm, networkSafetyDirty, capabilityActions.saveNetworkSafetySettings);
|
||||
const imageEdits = useEditCompletion(imageGenerationForm, imageGenerationDirty, capabilityActions.saveImageGenerationSettings,
|
||||
!imageGenerationForm.enabled || Boolean(settings?.image_generation.providers.find(
|
||||
(provider) => provider.name === imageGenerationForm.provider,
|
||||
)?.configured));
|
||||
useAutoSave(transcriptionForm, transcriptionDirty, transcriptionSaving, capabilityActions.saveTranscriptionSettings);
|
||||
const transcriptionEdits = useEditCompletion(transcriptionForm, transcriptionDirty, capabilityActions.saveTranscriptionSettings);
|
||||
const webDraft = settings ? webSearchDraftState(settings, webSearchForm) : null;
|
||||
useAutoSave(webSearchForm, webDraft?.dirty ?? false, webSearchSaving, capabilityActions.saveWebSearch,
|
||||
const webEdits = useEditCompletion(webSearchForm, webDraft?.dirty ?? false, capabilityActions.saveWebSearch,
|
||||
!webDraft?.missingCredential && (webSearchForm.provider !== "olostep" ||
|
||||
featureCatalog.some((feature) => feature.name === "olostep" && feature.installed)));
|
||||
|
||||
@@ -458,6 +471,11 @@ export function useSettingsController({
|
||||
modelActions,
|
||||
capabilityState,
|
||||
capabilityActions,
|
||||
modelEdits,
|
||||
safetyEdits,
|
||||
imageEdits,
|
||||
transcriptionEdits,
|
||||
webEdits,
|
||||
systemState,
|
||||
systemActions,
|
||||
activeSection,
|
||||
|
||||
Reference in new issue
Block a user