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) | 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 [validating, setValidating] = useState(false); const [pendingEnabled, setPendingEnabled] = useState(null); const actionPending = saving || 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 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>(() => 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 => { 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
{ 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 ? }> setAdvancedOpen(true)} onFeaturesUpdate={onFeaturesUpdate} /> : undefined} />
; } function ChannelPluginLoading({ compact = false }: { compact?: boolean }) { const { t } = useTranslation(); return (
{t("settings.status.loading")}
); }