* fix(webui): save settings when editing completes (NAN-323) * fix(webui): close settings completion and verification gaps * refactor(webui): simplify settings edit ownership
498 lines
17 KiB
TypeScript
498 lines
17 KiB
TypeScript
import { channelValidationMessage } from "./validationMessages";
|
|
import {
|
|
Suspense,
|
|
useEffect,
|
|
useId,
|
|
useMemo,
|
|
useState,
|
|
type ComponentType,
|
|
type ReactNode,
|
|
} from "react";
|
|
import {
|
|
Loader2,
|
|
Plus,
|
|
} from "lucide-react";
|
|
import { useTranslation } from "react-i18next";
|
|
|
|
import { channelUiContribution } from "@/channel-plugins/registry";
|
|
import type {
|
|
ChannelFeatureAction,
|
|
ChannelPluginConnectFlowProps,
|
|
} from "@/channel-plugins/types";
|
|
import { useEditCompletion } from "@/components/settings/shared/useEditCompletion";
|
|
import {
|
|
type ChannelProviderPreset,
|
|
type ChannelSetupPresentation,
|
|
} from "@/channel-plugins/catalog";
|
|
import {
|
|
channelRequirementErrors,
|
|
channelServerValidationErrors,
|
|
focusFirstChannelFieldError,
|
|
} from "@/components/settings/channels/ChannelCredentialFields";
|
|
import {
|
|
channelValuesForSubmit,
|
|
defaultChannelFieldValues,
|
|
} from "@/components/settings/channels/CredentialForm";
|
|
import {
|
|
ChannelLogo,
|
|
ChannelRuntimeError,
|
|
CHANNEL_SETUP_PANEL_CLASS_NAME,
|
|
channelSetup,
|
|
channelToggleChecked,
|
|
localizedChannelDisplayName,
|
|
} from "@/components/settings/channels/ChannelIdentity";
|
|
import { ChannelSetupSurfaceView } from "@/components/settings/channels/ChannelSetupSurfaceView";
|
|
import { ChannelInstancesPanel } from "@/components/settings/channels/ChannelInstancesPanel";
|
|
import { Button } from "@/components/ui/button";
|
|
import {
|
|
configureChannel,
|
|
disableNanobotFeature,
|
|
validateChannel,
|
|
} from "@/lib/api";
|
|
import { copyTextToClipboard } from "@/lib/clipboard";
|
|
import type {
|
|
ChannelValidationPayload,
|
|
NanobotFeatureInfo,
|
|
NanobotFeaturesPayload,
|
|
} from "@/lib/types";
|
|
import { cn } from "@/lib/utils";
|
|
import { useClient } from "@/providers/ClientProvider";
|
|
|
|
export function ChannelSetupPanel({
|
|
token,
|
|
feature,
|
|
actionKey,
|
|
showBrandLogos,
|
|
onAction,
|
|
onFeaturesUpdate,
|
|
connectRequestId = 0,
|
|
onBeforeCloseChange,
|
|
onConfigureMcp,
|
|
}: {
|
|
token: string;
|
|
feature: NanobotFeatureInfo;
|
|
actionKey: string | null;
|
|
showBrandLogos: boolean;
|
|
onAction: ChannelFeatureAction;
|
|
onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void;
|
|
connectRequestId?: number;
|
|
onConfigureMcp?: (name: string) => void;
|
|
onBeforeCloseChange?: (handler: (() => Promise<boolean>) | null) => void;
|
|
}) {
|
|
const { t, i18n } = useTranslation();
|
|
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
|
|
const displayName = localizedChannelDisplayName(feature, t);
|
|
const uiContribution = channelUiContribution(feature.name, feature.webui);
|
|
const PluginPanel = uiContribution?.Panel;
|
|
const setup = channelSetup(feature, i18n.resolvedLanguage ?? i18n.language);
|
|
const missingSupport = !feature.installed;
|
|
if (PluginPanel && !missingSupport) {
|
|
return (
|
|
<Suspense fallback={<ChannelPluginLoading />}>
|
|
<PluginPanel
|
|
connectRequestId={connectRequestId}
|
|
token={token}
|
|
feature={feature}
|
|
actionKey={actionKey}
|
|
showBrandLogos={showBrandLogos}
|
|
onAction={onAction}
|
|
onFeaturesUpdate={onFeaturesUpdate}
|
|
onBeforeCloseChange={onBeforeCloseChange}
|
|
onConfigureMcp={onConfigureMcp}
|
|
/>
|
|
</Suspense>
|
|
);
|
|
}
|
|
if (feature.instances !== undefined && !missingSupport) {
|
|
return (
|
|
<ChannelInstancesPanel
|
|
feature={feature}
|
|
showBrandLogos={showBrandLogos}
|
|
onFeaturesUpdate={onFeaturesUpdate}
|
|
/>
|
|
);
|
|
}
|
|
const enableBusy = actionKey === `enable:${feature.name}` || actionKey === `install:${feature.name}`;
|
|
const anyActionBusy = Boolean(actionKey);
|
|
const installSupportLabel = tx("settings.channels.install", "Install");
|
|
|
|
const header = (
|
|
<div className="flex min-w-0 items-center gap-3">
|
|
<ChannelLogo feature={feature} showBrandLogos={showBrandLogos} />
|
|
<h3 className="text-ui-heading">{displayName}</h3>
|
|
{missingSupport && feature.install_supported ? (
|
|
<Button
|
|
type="button"
|
|
size="sm"
|
|
variant="secondary"
|
|
disabled={anyActionBusy}
|
|
onClick={() => onAction("enable", feature.name, { installOnly: true, confirmed: true })}
|
|
className="h-8 rounded-full px-3 text-[12px] font-semibold"
|
|
>
|
|
{enableBusy ? (
|
|
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />
|
|
) : (
|
|
<Plus className="mr-1.5 h-3.5 w-3.5" aria-hidden />
|
|
)}
|
|
{installSupportLabel}
|
|
</Button>
|
|
) : null}
|
|
</div>
|
|
);
|
|
|
|
return (
|
|
<aside className={CHANNEL_SETUP_PANEL_CLASS_NAME}>
|
|
{missingSupport ? <>
|
|
<div className="pe-20">{header}</div>
|
|
<ChannelRuntimeError message={feature.runtime_error} className="mt-4" />
|
|
</> : <ChannelSetupSurface
|
|
key={feature.name}
|
|
header={header}
|
|
token={token}
|
|
feature={feature}
|
|
setup={setup}
|
|
connectRequestId={connectRequestId}
|
|
ConnectFlow={uiContribution?.ConnectFlow}
|
|
onFeaturesUpdate={onFeaturesUpdate}
|
|
onBeforeCloseChange={onBeforeCloseChange}
|
|
/>}
|
|
</aside>
|
|
);
|
|
}
|
|
|
|
function ChannelSetupSurface({
|
|
header,
|
|
token,
|
|
feature,
|
|
setup,
|
|
connectRequestId,
|
|
ConnectFlow,
|
|
onFeaturesUpdate,
|
|
onBeforeCloseChange,
|
|
}: {
|
|
header: ReactNode;
|
|
token: string;
|
|
feature: NanobotFeatureInfo;
|
|
setup: ChannelSetupPresentation;
|
|
connectRequestId: number;
|
|
ConnectFlow?: ComponentType<ChannelPluginConnectFlowProps>;
|
|
onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void;
|
|
onBeforeCloseChange?: (handler: (() => Promise<boolean>) | null) => void;
|
|
}) {
|
|
const { client } = useClient();
|
|
const { t } = useTranslation();
|
|
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
|
|
const [notice, setNotice] = useState<string | null>(null);
|
|
const [saving, setSaving] = useState(false);
|
|
const [autoSaving, setAutoSaving] = useState(false);
|
|
const [autoSaveState, setAutoSaveState] = useState<"idle" | "saved">("idle");
|
|
const [validating, setValidating] = useState(false);
|
|
const [pendingEnabled, setPendingEnabled] = useState<boolean | null>(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());
|
|
const [clearedSecrets, setClearedSecrets] = useState<Set<string>>(() => new Set());
|
|
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
|
|
const [advancedOpen, setAdvancedOpen] = useState(false);
|
|
const advancedPanelId = useId();
|
|
const configValuesKey = JSON.stringify(feature.config_values ?? {});
|
|
const configuredFields = useMemo(
|
|
() => new Set(feature.configured_fields ?? []),
|
|
[feature.configured_fields],
|
|
);
|
|
const mode = setup.mode ?? "credentials";
|
|
const fields = setup.fields ?? [];
|
|
const requirementKeys = new Set(
|
|
(setup.requirements ?? []).flatMap((requirement) => requirement.alternatives.flat()),
|
|
);
|
|
const primaryFields = fields.filter(
|
|
(field) => !field.optional || requirementKeys.has(field.key),
|
|
);
|
|
const manualFields = setup.manualFields ?? [];
|
|
const advancedFields = mode === "connect"
|
|
? manualFields
|
|
: fields.filter((field) => !primaryFields.includes(field));
|
|
const editableFields = mode === "credentials" ? fields : mode === "connect" ? manualFields : [];
|
|
const savedSecretFields = editableFields.filter(
|
|
(field) => field.secret && configuredFields.has(field.key),
|
|
);
|
|
const availablePresets = feature.configured ? [] : setup.presets ?? [];
|
|
const [fieldValues, setFieldValues] = useState<Record<string, string>>(() =>
|
|
defaultChannelFieldValues(editableFields, feature.config_values),
|
|
);
|
|
|
|
useEffect(() => {
|
|
setNotice(null);
|
|
setVisibleSecrets({});
|
|
setSaving(false);
|
|
setValidating(false);
|
|
setValidation(null);
|
|
setTouchedFields(new Set());
|
|
setClearedSecrets(new Set());
|
|
setFieldErrors({});
|
|
setFieldValues(defaultChannelFieldValues(editableFields, feature.config_values));
|
|
}, [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] }));
|
|
};
|
|
|
|
const setFieldValue = (key: string, value: string) => {
|
|
setFieldValues((current) => ({ ...current, [key]: value }));
|
|
setTouchedFields((current) => new Set(current).add(key));
|
|
setClearedSecrets((current) => {
|
|
if (!current.has(key)) return current;
|
|
const next = new Set(current);
|
|
next.delete(key);
|
|
return next;
|
|
});
|
|
setFieldErrors((current) => {
|
|
if (!current[key]) return current;
|
|
const next = { ...current };
|
|
delete next[key];
|
|
return next;
|
|
});
|
|
setAutoSaveState("idle");
|
|
};
|
|
|
|
const setSecretCleared = (key: string, clear: boolean) => {
|
|
edits.complete();
|
|
setClearedSecrets((current) => {
|
|
const next = new Set(current);
|
|
if (clear) next.add(key);
|
|
else next.delete(key);
|
|
return next;
|
|
});
|
|
setAutoSaveState("idle");
|
|
};
|
|
|
|
const applyPreset = (preset: ChannelProviderPreset) => {
|
|
edits.complete();
|
|
const values = Object.fromEntries(
|
|
Object.entries(preset.values).filter(([key]) => !(fieldValues[key] ?? "").trim()),
|
|
);
|
|
if (!Object.keys(values).length) return;
|
|
setFieldValues((current) => ({ ...current, ...values }));
|
|
setTouchedFields((current) => {
|
|
const next = new Set(current);
|
|
for (const key of Object.keys(values)) next.add(key);
|
|
return next;
|
|
});
|
|
setAutoSaveState("idle");
|
|
};
|
|
|
|
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(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);
|
|
}
|
|
};
|
|
const edits = useEditCompletion(
|
|
{ fieldValues, touchedFields: [...touchedFields], clearedSecrets: [...clearedSecrets] },
|
|
(mode === "credentials" || mode === "connect") && draftDirty,
|
|
saveChannelDraft,
|
|
true,
|
|
feature.name,
|
|
);
|
|
|
|
useEffect(() => {
|
|
if (autoSaveState !== "saved") return;
|
|
const timeout = window.setTimeout(() => setAutoSaveState("idle"), 1500);
|
|
return () => window.clearTimeout(timeout);
|
|
}, [autoSaveState]);
|
|
|
|
useEffect(() => {
|
|
if (!onBeforeCloseChange) return;
|
|
onBeforeCloseChange(draftDirty ? edits.commit : null);
|
|
return () => onBeforeCloseChange(null);
|
|
}, [draftDirty, onBeforeCloseChange, edits.commit]);
|
|
|
|
const copyCommand = () => {
|
|
if (!setup.command) return;
|
|
void copyTextToClipboard(setup.command).then((ok) => {
|
|
setNotice(
|
|
ok
|
|
? tx("settings.channels.commandCopied", "Command copied.")
|
|
: tx("settings.channels.commandCopyFailed", "Could not copy command."),
|
|
);
|
|
});
|
|
};
|
|
|
|
const saveCredentialSettings = async () => {
|
|
if (actionPending) return;
|
|
const errors = channelRequirementErrors(
|
|
fields,
|
|
setup.requirements ?? [],
|
|
fieldValues,
|
|
configuredFields,
|
|
clearedSecrets,
|
|
tx("settings.channels.fieldRequired", "Required to complete setup."),
|
|
);
|
|
if (Object.keys(errors).length) {
|
|
setFieldErrors(errors);
|
|
setNotice(tx("settings.channels.validationFailed", "Check the required setup before enabling."));
|
|
focusFirstChannelFieldError(errors);
|
|
return;
|
|
}
|
|
setPendingEnabled(true);
|
|
setSaving(true);
|
|
setValidating(true);
|
|
setNotice(null);
|
|
const values = channelValuesForSubmit(fields, fieldValues, touchedFields, clearedSecrets);
|
|
try {
|
|
const validationPayload = await validateChannel(client, feature.name, values);
|
|
setValidation(validationPayload);
|
|
if (!validationPayload.can_enable) {
|
|
const errors = channelServerValidationErrors(
|
|
fields,
|
|
validationPayload.missing_fields,
|
|
tx("settings.channels.fieldRequired", "Required to complete setup."),
|
|
);
|
|
setFieldErrors(errors);
|
|
if (advancedFields.some((field) => errors[field.key])) setAdvancedOpen(true);
|
|
focusFirstChannelFieldError(errors);
|
|
setNotice(
|
|
(validationPayload.message ? channelValidationMessage(validationPayload.message, t) : undefined)
|
|
?? tx("settings.channels.validationFailed", "Check the required setup before enabling."),
|
|
);
|
|
return;
|
|
}
|
|
const payload = await configureChannel(
|
|
client,
|
|
feature.name,
|
|
values,
|
|
{ enable: true },
|
|
);
|
|
if (payload.nanobot_features) {
|
|
onFeaturesUpdate(payload.nanobot_features);
|
|
}
|
|
setNotice(tx("settings.channels.checkedAndEnabled", "Checked and enabled."));
|
|
} catch (err) {
|
|
setNotice((err as Error).message);
|
|
} finally {
|
|
setSaving(false);
|
|
setValidating(false);
|
|
setPendingEnabled(null);
|
|
}
|
|
};
|
|
|
|
const checkCurrentSettings = async () => {
|
|
if (actionPending) return;
|
|
setValidating(true);
|
|
setValidation(null);
|
|
setNotice(null);
|
|
try {
|
|
const payload = await validateChannel(
|
|
client,
|
|
feature.name,
|
|
channelValuesForSubmit(fields, fieldValues, touchedFields, clearedSecrets),
|
|
);
|
|
setValidation(payload);
|
|
const failedCheck = payload.checks.find((check) => check.status === "fail");
|
|
const resultMessage = failedCheck?.message ?? payload.message;
|
|
const localizedResult = resultMessage ? channelValidationMessage(resultMessage, t) : null;
|
|
const localizedRuntimeError = feature.runtime_error
|
|
? channelValidationMessage(feature.runtime_error, t)
|
|
: null;
|
|
setNotice(
|
|
payload.status !== "connected"
|
|
&& localizedResult
|
|
&& localizedResult !== localizedRuntimeError
|
|
? localizedResult
|
|
: null,
|
|
);
|
|
} catch (err) {
|
|
setNotice((err as Error).message);
|
|
} finally {
|
|
setValidating(false);
|
|
}
|
|
};
|
|
|
|
const enabled = pendingEnabled ?? channelToggleChecked(feature);
|
|
const toggleEnabled = async (next: boolean) => {
|
|
if (actionPending) return;
|
|
if (next) {
|
|
await saveCredentialSettings();
|
|
return;
|
|
}
|
|
setPendingEnabled(false);
|
|
setSaving(true);
|
|
setNotice(null);
|
|
try {
|
|
onFeaturesUpdate(await disableNanobotFeature(client, feature.name));
|
|
} catch (err) {
|
|
setNotice((err as Error).message);
|
|
} finally {
|
|
setSaving(false);
|
|
setPendingEnabled(null);
|
|
}
|
|
};
|
|
|
|
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={(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}
|
|
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 }) {
|
|
const { t } = useTranslation();
|
|
return (
|
|
<div
|
|
role="status"
|
|
className={cn(
|
|
"flex items-center justify-center gap-2 text-sm text-muted-foreground",
|
|
compact
|
|
? "min-h-12"
|
|
: `${CHANNEL_SETUP_PANEL_CLASS_NAME} min-h-48`,
|
|
)}
|
|
>
|
|
<Loader2 className="h-4 w-4 animate-spin motion-reduce:animate-none" aria-hidden />
|
|
{t("settings.status.loading")}
|
|
</div>
|
|
);
|
|
}
|