import { channelValidationMessage } from "./validationMessages"; import { Suspense, useCallback, useEffect, useId, useMemo, useRef, useState, type ComponentType, type ReactNode, } from "react"; import { Check, ChevronDown, Clipboard, 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 { ToggleButton } from "@/components/settings/ToggleButton"; import { useAutoSave } from "@/components/settings/shared/useAutoSave"; import { type ChannelProviderPreset, type ChannelSetupPresentation, } from "@/channel-plugins/catalog"; import { ChannelFieldGroups, channelRequirementErrors, channelServerValidationErrors, focusFirstChannelFieldError, } from "@/components/settings/channels/ChannelCredentialFields"; import { CredentialForm, channelValuesForSubmit, defaultChannelFieldValues, } from "@/components/settings/channels/CredentialForm"; import { ChannelLogo, ChannelRuntimeError, CHANNEL_SETUP_PANEL_CLASS_NAME, channelSetup, channelToggleChecked, localizedChannelDisplayName, } from "@/components/settings/channels/ChannelIdentity"; import { ChannelProviderPresets, ChannelSetupActions, } from "@/components/settings/channels/ChannelSetupParts"; import { ChannelValidationProgress } from "@/components/settings/channels/ChannelValidationProgress"; 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) | 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 ( }> ); } if (feature.instances !== undefined && !missingSupport) { return ( ); } const enableBusy = actionKey === `enable:${feature.name}` || actionKey === `install:${feature.name}`; const anyActionBusy = Boolean(actionKey); const installSupportLabel = tx("settings.channels.install", "Install"); const header = (

{displayName}

{missingSupport && feature.install_supported ? ( ) : null}
); return ( ); } function ChannelSetupSurface({ header, token, feature, setup, connectRequestId, ConnectFlow, onFeaturesUpdate, onBeforeCloseChange, }: { header: ReactNode; token: string; feature: NanobotFeatureInfo; setup: ChannelSetupPresentation; connectRequestId: number; ConnectFlow?: ComponentType; onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void; onBeforeCloseChange?: (handler: (() => Promise) | null) => void; }) { const { client } = useClient(); const { t } = useTranslation(); const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback }); const [notice, setNotice] = useState(null); const [saving, setSaving] = useState(false); const [autoSaving, setAutoSaving] = useState(false); const [autoSaveState, setAutoSaveState] = useState<"idle" | "saved">("idle"); const autoSavePromiseRef = useRef | null>(null); const [validating, setValidating] = useState(false); const [pendingEnabled, setPendingEnabled] = useState(null); const actionPending = saving || autoSaving || validating || pendingEnabled !== null; const [validation, setValidation] = useState(null); const [visibleSecrets, setVisibleSecrets] = useState>({}); const [touchedFields, setTouchedFields] = useState>(() => new Set()); const [clearedSecrets, setClearedSecrets] = useState>(() => new Set()); const [fieldErrors, setFieldErrors] = useState>({}); 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 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()), ); 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 hasAdvanced = advancedFields.length > 0 || savedSecretFields.length > 0 || availablePresets.length > 0; const [fieldValues, setFieldValues] = useState>(() => 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)); }, [configValuesKey, feature.name]); 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 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) => { setClearedSecrets((current) => { const next = new Set(current); if (clear) next.add(key); else next.delete(key); return next; }); setAutoSaveState("idle"); }; const applyPreset = (preset: ChannelProviderPreset) => { 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 credentialDirty = touchedFields.size > 0 || clearedSecrets.size > 0; const touchedSecret = fields.some( (field) => field.secret && touchedFields.has(field.key), ); const saveCredentialDraft = useCallback(async (): Promise => { const activeSave = autoSavePromiseRef.current; if (activeSave) return activeSave; if (mode !== "credentials" || !credentialDirty) 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(); }; useAutoSave( { fieldValues, touchedFields: [...touchedFields], clearedSecrets: [...clearedSecrets] }, mode === "credentials" && credentialDirty, actionPending, () => void saveCredentialDraft(), !touchedSecret, ); useEffect(() => { if (autoSaveState !== "saved") return; const timeout = window.setTimeout(() => setAutoSaveState("idle"), 1500); return () => window.clearTimeout(timeout); }, [autoSaveState]); useEffect(() => { if (!onBeforeCloseChange) return; onBeforeCloseChange(credentialDirty ? saveCredentialDraft : null); return () => onBeforeCloseChange(null); }, [credentialDirty, onBeforeCloseChange, saveCredentialDraft]); 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); } }; const inlineActions = mode === "credentials" && primaryFields.length === 1 && !advancedOpen && !setup.presets?.length && !setup.actions?.length; const credentialActions = mode === "credentials" ? (
{feature.setup?.verifies_connection ? ( ) : null} void toggleEnabled(next)} />
) : null; return (
{ event.preventDefault(); if (mode === "credentials") void saveCredentialSettings(); }} >
{header}
{autoSaving ? ( <> {tx("settings.actions.saving", "Saving")} ) : autoSaveState === "saved" ? ( <> {tx("settings.channels.savedSettings", "Settings saved.")} ) : null} {hasAdvanced ? ( ) : null}
{mode === "webui" ? ( {tx("settings.channels.managedByWebui", "Managed by WebUI")} ) : null}
{mode === "connect" && ConnectFlow ? ( }> ) : mode === "connect" ? ( <>
{setup.command ? ( ) : null}
{setup.command ? ( {setup.command} ) : null} ) : mode === "credentials" ? ( <> {primaryFields.length ? ( ) : null} ) : null}
{hasAdvanced ? ( ) : null} {credentialActions}
{mode === "credentials" && feature.setup?.verifies_connection && (validation || validating) ? (
) : null}
{notice ?? ""}
); } function ChannelPluginLoading({ compact = false }: { compact?: boolean }) { const { t } = useTranslation(); return (
{t("settings.status.loading")}
); }