refactor(webui): split channel setup responsibilities

This commit is contained in:
chengyongru authored and chengyongru committed 2026-09-11 16:04:51 +08:00
1 parent e8a29a0087
commit ccbdf56eb3
8 files changed
+523 -507

No files matched your search

@@ -0,0 +1,128 @@
import { useEffect, useRef, useState } from "react";
import { Download, Loader2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import type { ChannelFeatureAction } from "@/channel-plugins/types";
import { ToggleButton } from "@/components/settings/ToggleButton";
import {
ChannelLogo,
ChannelStatusBadge,
channelStatusLabel,
channelToggleChecked,
localizedChannelDisplayName,
} from "@/components/settings/channels/ChannelIdentity";
import { Button } from "@/components/ui/button";
import type { NanobotFeatureInfo } from "@/lib/types";
import { cn } from "@/lib/utils";
export function ChannelCatalogRow({
feature,
showBrandLogos,
onSelect,
actionKey,
actionsDisabled = false,
onAction,
}: {
feature: NanobotFeatureInfo;
showBrandLogos: boolean;
onSelect: (connect?: boolean) => void;
actionKey: string | null;
actionsDisabled?: boolean;
onAction: ChannelFeatureAction;
}) {
const { t } = useTranslation();
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
const displayName = localizedChannelDisplayName(feature, t);
const alwaysEnabled = feature.capabilities?.includes("always_enabled") ?? false;
const pendingChecked = actionKey === `enable:${feature.name}` ? true
: actionKey === `disable:${feature.name}` ? false : null;
const ownActionBusy = pendingChecked !== null || actionKey === `install:${feature.name}`;
const checked = alwaysEnabled || (pendingChecked ?? channelToggleChecked(feature));
const anyActionBusy = Boolean(actionKey);
const installButtonRef = useRef<HTMLButtonElement | null>(null);
const [installHint, setInstallHint] = useState(false);
useEffect(() => {
if (!installHint) return;
const timeout = window.setTimeout(() => setInstallHint(false), 1400);
return () => window.clearTimeout(timeout);
}, [installHint]);
const pointToInstall = () => {
setInstallHint(true);
installButtonRef.current?.focus();
};
const channelIdentity = (
<>
<ChannelLogo feature={feature} showBrandLogos={showBrandLogos} />
<div className="min-w-0 flex-1">
<h3 className="truncate text-[14px] font-semibold leading-5 text-foreground">
{displayName}
</h3>
</div>
</>
);
return (
<div className={cn(
"settings-list-row flex min-w-0 items-center gap-3 py-2.5 transition-colors",
!alwaysEnabled && "settings-hover",
)}>
{alwaysEnabled ? (
<div className="flex min-w-0 flex-1 select-none items-center gap-3">
{channelIdentity}
</div>
) : (
<button
type="button"
aria-label={t("settings.channels.selectChannel", {
name: displayName,
defaultValue: "View {{name}} settings",
})}
aria-haspopup="dialog"
disabled={actionsDisabled}
onClick={() => feature.installed ? onSelect() : pointToInstall()}
className="group flex min-w-0 flex-1 select-none items-center gap-3 rounded-control text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border/80"
>
{channelIdentity}
</button>
)}
{feature.runtime_status === "failed" ? (
<div className="min-w-0 shrink truncate">
<ChannelStatusBadge status={feature.runtime_status}>
{channelStatusLabel(feature, tx)}
</ChannelStatusBadge>
</div>
) : null}
<div className="flex w-16 shrink-0 items-center justify-center">
{!feature.installed ? (
<Button ref={installButtonRef} type="button" variant="outline" size="icon"
className={cn(
"h-[22px] w-[38px] min-w-0 shrink-0 rounded-full border-border/70 bg-background p-0 shadow-sm settings-hover active:scale-[0.96]",
installHint && "border-[#2997FF]/60 bg-[#2997FF]/10 text-[#087FE7] ring-2 ring-[#2997FF]/25 ring-offset-2",
)}
disabled={actionsDisabled || anyActionBusy || !feature.install_supported}
aria-label={t("settings.channels.installChannel", { name: displayName })}
onClick={() => {
setInstallHint(false);
onAction("enable", feature.name, { installOnly: true, confirmed: true });
}}>
{ownActionBusy
? <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
: <Download className="h-3.5 w-3.5" aria-hidden />}
<span className="sr-only">{tx("settings.channels.install", "Install")}</span>
</Button>
) : (
<ToggleButton checked={checked}
label={checked ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}
disabled={alwaysEnabled || actionsDisabled || anyActionBusy}
ariaLabel={t("settings.channels.toggleChannel", { name: displayName, defaultValue: "{{name}} channel" })}
onChange={(enabled) => {
if (enabled && feature.configured === false) onSelect(true);
else onAction(enabled ? "enable" : "disable", feature.name);
}} />
)}
</div>
</div>
);
}
@@ -0,0 +1,169 @@
import { useTranslation } from "react-i18next";
import type {
ChannelConfigField,
ChannelFieldSection,
ChannelSetupRequirement,
} from "@/components/settings/channels/catalog";
import {
CredentialForm,
channelFieldInputId,
type CredentialFormProps,
} from "@/components/settings/channels/CredentialForm";
const CHANNEL_FIELD_SECTION_ORDER: ChannelFieldSection[] = [
"account",
"credentials",
"connection",
"access",
"behavior",
"security",
];
type ChannelFieldGroupsProps = Omit<CredentialFormProps, "fields" | "compact"> & {
fields: ChannelConfigField[];
requirements: ChannelSetupRequirement[];
sectionLabels?: Record<string, string>;
};
export function ChannelFieldGroups({
fields,
requirements,
sectionLabels,
...formProps
}: ChannelFieldGroupsProps) {
const { t } = useTranslation();
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
const labels = new Map(fields.map((field) => [field.key, field.label]));
const compositeRequirements = requirements.filter(
(requirement) => requirement.alternatives.length > 1,
);
const groups = new Map<string, ChannelConfigField[]>();
for (const field of fields) {
const section = field.section ?? "credentials";
const current = groups.get(section) ?? [];
current.push(field);
groups.set(section, current);
}
const orderedSections = [
...CHANNEL_FIELD_SECTION_ORDER,
...[...groups.keys()].filter(
(section) => !CHANNEL_FIELD_SECTION_ORDER.includes(section as ChannelFieldSection),
),
];
return (
<div className="space-y-5">
{compositeRequirements.map((requirement, index) => (
<div
key={index}
className="rounded-control border border-border/60 bg-background/55 px-3 py-2.5"
>
<div className="text-[11px] font-semibold text-foreground">
{tx("settings.channels.chooseCredentialMethod", "Choose one credential method")}
</div>
<div className="mt-1 flex flex-wrap items-center gap-1.5 text-[11px] text-muted-foreground">
{requirement.alternatives.map((alternative, alternativeIndex) => (
<span key={alternative.join("|")} className="contents">
{alternativeIndex ? <span aria-hidden>{tx("settings.channels.or", "or")}</span> : null}
<span className="rounded-full bg-muted px-2 py-0.5 text-foreground/85">
{alternative.map((key) => labels.get(key) ?? key.split(".").at(-1)).join(" + ")}
</span>
</span>
))}
</div>
</div>
))}
{orderedSections.map((section) => {
const sectionFields = groups.get(section);
if (!sectionFields?.length) return null;
return (
<fieldset key={section} className="min-w-0">
<legend className={groups.size === 1 ? "sr-only" : "mb-2 text-[12px] font-medium text-muted-foreground"}>
{channelFieldSectionLabel(section, tx, sectionLabels)}
</legend>
<div>
<CredentialForm fields={sectionFields} {...formProps} compact />
</div>
</fieldset>
);
})}
</div>
);
}
function channelFieldSectionLabel(
section: string,
tx: (key: string, fallback: string) => string,
sectionLabels?: Record<string, string>,
): string {
const customLabel = sectionLabels?.[section];
if (customLabel) return customLabel;
const fallbacks: Record<ChannelFieldSection, string> = {
account: "Account",
credentials: "Credentials",
connection: "Connection",
access: "Access",
behavior: "Behavior",
security: "Security",
advanced: "Advanced",
};
const fallback = fallbacks[section as ChannelFieldSection];
if (fallback) return tx(`settings.channels.sections.${section}`, fallback);
return section
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
.replace(/[_-]+/g, " ")
.replace(/\b\w/g, (letter) => letter.toUpperCase());
}
export function channelRequirementErrors(
fields: ChannelConfigField[],
requirements: ChannelSetupRequirement[],
values: Record<string, string>,
configuredFields: Set<string>,
clearedSecrets: Set<string>,
message: string,
): Record<string, string> {
const fieldByKey = new Map(fields.map((field) => [field.key, field]));
const present = (key: string) => {
const field = fieldByKey.get(key);
if (!field || clearedSecrets.has(key)) return false;
const value = (values[key] ?? "").trim();
if (field.kind === "bool") return value === "true";
if (value) return true;
return Boolean(field.secret && configuredFields.has(key));
};
const errors: Record<string, string> = {};
for (const requirement of requirements) {
if (requirement.alternatives.some((alternative) => alternative.every(present))) continue;
const closest = [...requirement.alternatives].sort(
(left, right) => left.filter((key) => !present(key)).length - right.filter((key) => !present(key)).length,
)[0] ?? [];
for (const key of closest) {
if (!present(key) && fieldByKey.has(key)) errors[key] = message;
}
}
return errors;
}
export function channelServerValidationErrors(
fields: ChannelConfigField[],
missingFields: string[],
message: string,
): Record<string, string> {
const missing = new Set(missingFields);
return Object.fromEntries(
fields
.filter((field) => missing.has(field.key) || missing.has(field.key.split(".").at(-1) ?? ""))
.map((field) => [field.key, message]),
);
}
export function focusFirstChannelFieldError(errors: Record<string, string>) {
const key = Object.keys(errors)[0];
if (!key) return;
window.requestAnimationFrame(() => {
document.getElementById(channelFieldInputId(key))?.focus();
});
}
@@ -7,11 +7,13 @@ import { ToggleButton } from "@/components/settings/ToggleButton";
import type { ChannelConfigField } from "@/components/settings/channels/catalog";
import {
CredentialForm,
channelValidationStatusClass,
channelValidationStatusIcon,
channelValuesForSave,
defaultChannelFieldValues,
} from "@/components/settings/channels/CredentialForm";
import {
channelValidationStatusClass,
channelValidationStatusIcon,
} from "@/components/settings/channels/ChannelValidationProgress";
import {
CHANNEL_SETUP_PANEL_CLASS_NAME,
ChannelLogo,
@@ -14,7 +14,6 @@ import {
Check,
ChevronDown,
Clipboard,
Download,
Loader2,
Plus,
} from "lucide-react";
@@ -28,12 +27,15 @@ import type {
import { ToggleButton } from "@/components/settings/ToggleButton";
import { useAutoSave } from "@/components/settings/shared/useAutoSave";
import {
type ChannelConfigField,
type ChannelFieldSection,
type ChannelProviderPreset,
type ChannelSetupPresentation,
type ChannelSetupRequirement,
} from "@/components/settings/channels/catalog";
import {
ChannelFieldGroups,
channelRequirementErrors,
channelServerValidationErrors,
focusFirstChannelFieldError,
} from "@/components/settings/channels/ChannelCredentialFields";
import {
CredentialForm,
channelValuesForSubmit,
@@ -43,17 +45,15 @@ import {
ChannelLogo,
ChannelRuntimeError,
CHANNEL_SETUP_PANEL_CLASS_NAME,
ChannelStatusBadge,
channelSetup,
channelStatusLabel,
channelToggleChecked,
localizedChannelDisplayName,
} from "@/components/settings/channels/ChannelIdentity";
import {
ChannelProviderPresets,
ChannelSetupActions,
ChannelValidationProgress,
} 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 {
@@ -70,118 +70,6 @@ import type {
import { cn } from "@/lib/utils";
import { useClient } from "@/providers/ClientProvider";
export function ChannelCatalogRow({
feature,
showBrandLogos,
onSelect,
actionKey,
actionsDisabled = false,
onAction,
}: {
feature: NanobotFeatureInfo;
showBrandLogos: boolean;
onSelect: (connect?: boolean) => void;
actionKey: string | null;
actionsDisabled?: boolean;
onAction: ChannelFeatureAction;
}) {
const { t } = useTranslation();
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
const displayName = localizedChannelDisplayName(feature, t);
const alwaysEnabled = feature.capabilities?.includes("always_enabled") ?? false;
const pendingChecked = actionKey === `enable:${feature.name}` ? true
: actionKey === `disable:${feature.name}` ? false : null;
const ownActionBusy = pendingChecked !== null || actionKey === `install:${feature.name}`;
const checked = alwaysEnabled || (pendingChecked ?? channelToggleChecked(feature));
const anyActionBusy = Boolean(actionKey);
const installButtonRef = useRef<HTMLButtonElement | null>(null);
const [installHint, setInstallHint] = useState(false);
useEffect(() => {
if (!installHint) return;
const timeout = window.setTimeout(() => setInstallHint(false), 1400);
return () => window.clearTimeout(timeout);
}, [installHint]);
const pointToInstall = () => {
setInstallHint(true);
installButtonRef.current?.focus();
};
const channelIdentity = (
<>
<ChannelLogo feature={feature} showBrandLogos={showBrandLogos} />
<div className="min-w-0 flex-1">
<h3 className="truncate text-[14px] font-semibold leading-5 text-foreground">
{displayName}
</h3>
</div>
</>
);
return (
<div className={cn(
"settings-list-row flex min-w-0 items-center gap-3 py-2.5 transition-colors",
!alwaysEnabled && "settings-hover",
)}>
{alwaysEnabled ? (
<div className="flex min-w-0 flex-1 select-none items-center gap-3">
{channelIdentity}
</div>
) : (
<button
type="button"
aria-label={t("settings.channels.selectChannel", {
name: displayName,
defaultValue: "View {{name}} settings",
})}
aria-haspopup="dialog"
disabled={actionsDisabled}
onClick={() => feature.installed ? onSelect() : pointToInstall()}
className="group flex min-w-0 flex-1 select-none items-center gap-3 rounded-control text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border/80"
>
{channelIdentity}
</button>
)}
{feature.runtime_status === "failed" ? (
<div className="min-w-0 shrink truncate">
<ChannelStatusBadge status={feature.runtime_status}>
{channelStatusLabel(feature, tx)}
</ChannelStatusBadge>
</div>
) : null}
<div className="flex w-16 shrink-0 items-center justify-center">
{!feature.installed ? (
<Button ref={installButtonRef} type="button" variant="outline" size="icon"
className={cn(
"h-[22px] w-[38px] min-w-0 shrink-0 rounded-full border-border/70 bg-background p-0 shadow-sm settings-hover active:scale-[0.96]",
installHint && "border-[#2997FF]/60 bg-[#2997FF]/10 text-[#087FE7] ring-2 ring-[#2997FF]/25 ring-offset-2",
)}
disabled={actionsDisabled || anyActionBusy || !feature.install_supported}
aria-label={t("settings.channels.installChannel", { name: displayName })}
onClick={() => {
setInstallHint(false);
onAction("enable", feature.name, { installOnly: true, confirmed: true });
}}>
{ownActionBusy
? <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
: <Download className="h-3.5 w-3.5" aria-hidden />}
<span className="sr-only">{tx("settings.channels.install", "Install")}</span>
</Button>
) : (
<ToggleButton checked={checked}
label={checked ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}
disabled={alwaysEnabled || actionsDisabled || anyActionBusy}
ariaLabel={t("settings.channels.toggleChannel", { name: displayName, defaultValue: "{{name}} channel" })}
onChange={(enabled) => {
if (enabled && feature.configured === false) onSelect(true);
else onAction(enabled ? "enable" : "disable", feature.name);
}} />
)}
</div>
</div>
);
}
export function ChannelSetupPanel({
token,
feature,
@@ -272,7 +160,7 @@ export function ChannelSetupPanel({
feature={feature}
setup={setup}
connectRequestId={connectRequestId}
ConnectFlow={feature.installed ? uiContribution?.ConnectFlow : undefined}
ConnectFlow={uiContribution?.ConnectFlow}
onFeaturesUpdate={onFeaturesUpdate}
onBeforeCloseChange={onBeforeCloseChange}
/>}
@@ -324,6 +212,10 @@ 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()),
);
@@ -466,6 +358,9 @@ function ChannelSetupSurface({
touchedFields,
validating,
]);
const saveSecretOnBlur = (key: string) => {
if (secretFieldKeys.has(key)) void saveCredentialDraft();
};
useAutoSave(
{ fieldValues, touchedFields: [...touchedFields], clearedSecrets: [...clearedSecrets] },
@@ -694,7 +589,7 @@ function ChannelSetupSurface({
</div>
<ChannelSetupActions feature={feature} setup={setup} onNotice={setNotice} />
{mode === "connect" && !feature.installed ? null : mode === "connect" && ConnectFlow ? (
{mode === "connect" && ConnectFlow ? (
<Suspense fallback={<ChannelPluginLoading compact />}>
<ConnectFlow
token={token}
@@ -751,11 +646,7 @@ function ChannelSetupSurface({
configuredFields={configuredFields}
visibleSecrets={visibleSecrets}
onChange={setFieldValue}
onFieldBlur={(key) => {
if (fields.some((field) => field.key === key && field.secret)) {
void saveCredentialDraft();
}
}}
onFieldBlur={saveSecretOnBlur}
onToggleSecret={toggleSecret}
errors={fieldErrors}
clearedSecrets={clearedSecrets}
@@ -800,11 +691,7 @@ function ChannelSetupSurface({
configuredFields={configuredFields}
visibleSecrets={visibleSecrets}
onChange={setFieldValue}
onFieldBlur={(key) => {
if (fields.some((field) => field.key === key && field.secret)) {
void saveCredentialDraft();
}
}}
onFieldBlur={saveSecretOnBlur}
onToggleSecret={toggleSecret}
errors={fieldErrors}
clearedSecrets={clearedSecrets}
@@ -842,171 +729,6 @@ function ChannelSetupSurface({
);
}
const CHANNEL_FIELD_SECTION_ORDER: ChannelFieldSection[] = [
"account",
"credentials",
"connection",
"access",
"behavior",
"security",
];
function ChannelFieldGroups({
fields,
requirements,
sectionLabels,
...formProps
}: {
fields: ChannelConfigField[];
requirements: ChannelSetupRequirement[];
sectionLabels?: Record<string, string>;
values: Record<string, string>;
configuredFields: Set<string>;
visibleSecrets: Record<string, boolean>;
onChange: (key: string, value: string) => void;
onFieldBlur?: (key: string) => void;
onToggleSecret: (key: string) => void;
errors: Record<string, string>;
clearedSecrets: Set<string>;
onClearSecret: (key: string, clear: boolean) => void;
disabled?: boolean;
}) {
const { t } = useTranslation();
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
const labels = new Map(fields.map((field) => [field.key, field.label]));
const compositeRequirements = requirements.filter(
(requirement) => requirement.alternatives.length > 1,
);
const groups = new Map<string, ChannelConfigField[]>();
for (const field of fields) {
const section = field.section ?? "credentials";
const current = groups.get(section) ?? [];
current.push(field);
groups.set(section, current);
}
const orderedSections = [
...CHANNEL_FIELD_SECTION_ORDER,
...[...groups.keys()].filter(
(section) => !CHANNEL_FIELD_SECTION_ORDER.includes(section as ChannelFieldSection),
),
];
return (
<div className="space-y-5">
{compositeRequirements.map((requirement, index) => (
<div
key={index}
className="rounded-control border border-border/60 bg-background/55 px-3 py-2.5"
>
<div className="text-[11px] font-semibold text-foreground">
{tx("settings.channels.chooseCredentialMethod", "Choose one credential method")}
</div>
<div className="mt-1 flex flex-wrap items-center gap-1.5 text-[11px] text-muted-foreground">
{requirement.alternatives.map((alternative, alternativeIndex) => (
<span key={alternative.join("|")} className="contents">
{alternativeIndex ? <span aria-hidden>{tx("settings.channels.or", "or")}</span> : null}
<span className="rounded-full bg-muted px-2 py-0.5 text-foreground/85">
{alternative.map((key) => labels.get(key) ?? key.split(".").at(-1)).join(" + ")}
</span>
</span>
))}
</div>
</div>
))}
{orderedSections.map((section) => {
const sectionFields = groups.get(section);
if (!sectionFields?.length) return null;
return (
<fieldset key={section} className="min-w-0">
<legend className={groups.size === 1 ? "sr-only" : "mb-2 text-[12px] font-medium text-muted-foreground"}>
{channelFieldSectionLabel(section, tx, sectionLabels)}
</legend>
<div>
<CredentialForm fields={sectionFields} {...formProps} compact />
</div>
</fieldset>
);
})}
</div>
);
}
function channelFieldSectionLabel(
section: string,
tx: (key: string, fallback: string) => string,
sectionLabels?: Record<string, string>,
): string {
const customLabel = sectionLabels?.[section];
if (customLabel) return customLabel;
const fallbacks: Record<ChannelFieldSection, string> = {
account: "Account",
credentials: "Credentials",
connection: "Connection",
access: "Access",
behavior: "Behavior",
security: "Security",
advanced: "Advanced",
};
const fallback = fallbacks[section as ChannelFieldSection];
if (fallback) return tx(`settings.channels.sections.${section}`, fallback);
return section
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
.replace(/[_-]+/g, " ")
.replace(/\b\w/g, (letter) => letter.toUpperCase());
}
function channelRequirementErrors(
fields: ChannelConfigField[],
requirements: ChannelSetupRequirement[],
values: Record<string, string>,
configuredFields: Set<string>,
clearedSecrets: Set<string>,
message: string,
): Record<string, string> {
const fieldByKey = new Map(fields.map((field) => [field.key, field]));
const present = (key: string) => {
const field = fieldByKey.get(key);
if (!field || clearedSecrets.has(key)) return false;
const value = (values[key] ?? "").trim();
if (field.kind === "bool") return value === "true";
if (value) return true;
return Boolean(field.secret && configuredFields.has(key));
};
const errors: Record<string, string> = {};
for (const requirement of requirements) {
if (requirement.alternatives.some((alternative) => alternative.every(present))) continue;
const closest = [...requirement.alternatives].sort(
(left, right) => left.filter((key) => !present(key)).length - right.filter((key) => !present(key)).length,
)[0] ?? [];
for (const key of closest) {
if (!present(key) && fieldByKey.has(key)) errors[key] = message;
}
}
return errors;
}
function channelServerValidationErrors(
fields: ChannelConfigField[],
missingFields: string[],
message: string,
): Record<string, string> {
const missing = new Set(missingFields);
return Object.fromEntries(
fields
.filter((field) => missing.has(field.key) || missing.has(field.key.split(".").at(-1) ?? ""))
.map((field) => [field.key, message]),
);
}
function focusFirstChannelFieldError(errors: Record<string, string>) {
const key = Object.keys(errors)[0];
if (!key) return;
window.requestAnimationFrame(() => {
document.getElementById(`channel-field-${key.replace(/[^a-zA-Z0-9_-]/g, "-")}`)?.focus();
});
}
function ChannelPluginLoading({ compact = false }: { compact?: boolean }) {
const { t } = useTranslation();
return (
@@ -1,6 +1,4 @@
import { channelValidationMessage } from "./validationMessages";
import { useEffect, useMemo, useState } from "react";
import { Clipboard, ExternalLink, Loader2 } from "lucide-react";
import { Clipboard } from "lucide-react";
import { useTranslation } from "react-i18next";
import { channelUiPresentation } from "@/channel-plugins/registry";
@@ -9,19 +7,8 @@ import {
type ChannelProviderPreset,
type ChannelSetupPresentation,
} from "@/components/settings/channels/catalog";
import {
channelValidationCheckIcon,
channelValidationCheckIconClass,
channelValidationStatusClass,
channelValidationStatusIcon,
channelValidationStatusLabel,
} from "@/components/settings/channels/CredentialForm";
import { copyTextToClipboard } from "@/lib/clipboard";
import type {
ChannelValidationPayload,
NanobotFeatureInfo,
} from "@/lib/types";
import { cn } from "@/lib/utils";
import type { NanobotFeatureInfo } from "@/lib/types";
export function ChannelSetupActions({
feature,
@@ -71,7 +58,6 @@ export function ChannelSetupActions({
</div>
);
}
export function ChannelProviderPresets({
presets,
onApply,
@@ -108,126 +94,3 @@ export function ChannelProviderPresets({
</fieldset>
);
}
function visibleValidationChecks(validation: ChannelValidationPayload | null) {
return (validation?.checks ?? []).filter(
(check) => check.id !== "manual_review"
&& !(check.id.startsWith("field:") && check.status === "pass"),
).slice(0, 6);
}
export function ChannelValidationProgress({
validation,
validating,
feature,
}: {
validation: ChannelValidationPayload | null;
validating: boolean;
feature: NanobotFeatureInfo;
}) {
const { t } = useTranslation();
const checks = useMemo(() => visibleValidationChecks(validation), [validation]);
const [reveal, setReveal] = useState<{
validation: ChannelValidationPayload | null;
settledCheckCount: number;
}>({ validation: null, settledCheckCount: 0 });
const settledCheckCount = reveal.validation === validation ? reveal.settledCheckCount : 0;
useEffect(() => {
if (validating || !validation) {
setReveal({ validation: null, settledCheckCount: 0 });
return;
}
setReveal({ validation, settledCheckCount: 0 });
const timers = checks.map((_, index) => window.setTimeout(
() => setReveal((current) => (
current.validation === validation
? { validation, settledCheckCount: index + 1 }
: current
)),
(index + 1) * 260,
));
return () => timers.forEach((timer) => window.clearTimeout(timer));
}, [checks, validating, validation]);
if (!validating && !validation) return null;
const finished = Boolean(validation) && !validating && settledCheckCount >= checks.length;
const shownChecks = finished ? checks : checks.slice(0, settledCheckCount + 1);
const status = validation?.status ?? (feature.configured ? "configured" : "needs_setup");
const presentation = channelUiPresentation(feature.name, feature.webui);
const identity = validation?.identity?.name
? validation.identity.workspace
? `${validation.identity.name} · ${validation.identity.workspace}`
: validation.identity.name
: presentation?.displayName ?? feature.display_name;
return (
<div
role="status"
aria-live="polite"
aria-atomic="true"
className="rounded-control border border-border/60 bg-muted/25 px-3 py-3"
>
<div className="space-y-2.5">
{validating ? (
<div className="flex items-center gap-2 px-2.5 text-[12px] font-medium text-foreground/85">
<Loader2 className="h-3.5 w-3.5 animate-spin text-muted-foreground" aria-hidden />
{t("settings.channels.checking", { defaultValue: "Checking..." })}
</div>
) : null}
{!validating ? shownChecks.map((check, index) => {
const pending = !finished && index === settledCheckCount;
return (
<div
key={check.id}
className="flex animate-in gap-2 px-2.5 fade-in-0 slide-in-from-top-1 text-[12px] leading-5 duration-200 motion-reduce:animate-none"
>
<span className={cn(
"mt-0.5",
pending ? "text-muted-foreground" : channelValidationCheckIconClass(check.status),
)}>
{pending
? <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
: channelValidationCheckIcon(check.status)}
</span>
<div className="min-w-0 flex-1">
<div className="flex min-w-0 items-center gap-x-2 font-medium text-foreground/85">
<span className="min-w-0 truncate">{channelValidationMessage(check.label, t)}</span>
{!pending && check.action_url ? (
<a
href={check.action_url}
target="_blank"
rel="noreferrer"
className="inline-flex shrink-0 items-center gap-1 whitespace-nowrap text-foreground underline decoration-border underline-offset-4"
>
{t("settings.channels.open")}
<ExternalLink className="h-3 w-3" aria-hidden />
</a>
) : null}
</div>
{!pending && check.status !== "pass" && check.message ? (
<div className="text-muted-foreground">
{channelValidationMessage(check.message, t)}
</div>
) : null}
</div>
</div>
);
}) : null}
{finished ? (
<div
className={cn(
"flex animate-in items-center gap-2 rounded-control px-2.5 py-2 text-[12px] font-medium fade-in-0 duration-200 motion-reduce:animate-none",
channelValidationStatusClass(status),
)}
>
{channelValidationStatusIcon(status)}
<span className="min-w-0 truncate font-semibold">{identity}</span>
<span className="lowercase">{channelValidationStatusLabel(status, t)}</span>
</div>
) : null}
</div>
</div>
);
}
@@ -0,0 +1,183 @@
import { useEffect, useMemo, useState, type ReactNode } from "react";
import { Check, CircleAlert, ExternalLink, Loader2, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import { channelUiPresentation } from "@/channel-plugins/registry";
import { channelValidationMessage } from "@/components/settings/channels/validationMessages";
import type { ChannelValidationPayload, NanobotFeatureInfo } from "@/lib/types";
import { cn } from "@/lib/utils";
export function channelValidationStatusLabel(
status: string,
t: ReturnType<typeof useTranslation>["t"],
): string {
const labels: Record<string, string> = {
connected: "Connected",
configured: "Not verified",
needs_setup: "Needs setup",
invalid: "Invalid",
unsupported: "Manual setup",
};
return t(`settings.channels.validation.${status}`, {
defaultValue: labels[status] ?? "Checked",
});
}
export function channelValidationStatusClass(status: string): string {
if (status === "connected") {
return "bg-emerald-500/10 text-emerald-700 dark:text-emerald-200";
}
if (status === "configured") {
return "bg-blue-500/10 text-blue-700 dark:text-blue-200";
}
if (status === "invalid") {
return "bg-destructive/10 text-destructive";
}
return "bg-muted text-muted-foreground";
}
export function channelValidationStatusIcon(status: string): ReactNode {
if (status === "connected") {
return <Check className="h-3.5 w-3.5" aria-hidden />;
}
if (status === "invalid") {
return <X className="h-3.5 w-3.5" aria-hidden />;
}
return <CircleAlert className="h-3.5 w-3.5" aria-hidden />;
}
function channelValidationCheckIcon(status: string): ReactNode {
if (status === "pass") return <Check className="h-3.5 w-3.5" aria-hidden />;
if (status === "fail") return <X className="h-3.5 w-3.5" aria-hidden />;
return <CircleAlert className="h-3.5 w-3.5" aria-hidden />;
}
function channelValidationCheckIconClass(status: string): string {
if (status === "pass") return "text-emerald-600";
if (status === "fail") return "text-destructive";
if (status === "warn") return "text-amber-600";
return "text-muted-foreground";
}
function visibleValidationChecks(validation: ChannelValidationPayload | null) {
return (validation?.checks ?? []).filter(
(check) => check.id !== "manual_review"
&& !(check.id.startsWith("field:") && check.status === "pass"),
).slice(0, 6);
}
export function ChannelValidationProgress({
validation,
validating,
feature,
}: {
validation: ChannelValidationPayload | null;
validating: boolean;
feature: NanobotFeatureInfo;
}) {
const { t } = useTranslation();
const checks = useMemo(() => visibleValidationChecks(validation), [validation]);
const [reveal, setReveal] = useState<{
validation: ChannelValidationPayload | null;
settledCheckCount: number;
}>({ validation: null, settledCheckCount: 0 });
const settledCheckCount = reveal.validation === validation ? reveal.settledCheckCount : 0;
useEffect(() => {
if (validating || !validation) {
setReveal({ validation: null, settledCheckCount: 0 });
return;
}
setReveal({ validation, settledCheckCount: 0 });
const timers = checks.map((_, index) => window.setTimeout(
() => setReveal((current) => (
current.validation === validation
? { validation, settledCheckCount: index + 1 }
: current
)),
(index + 1) * 260,
));
return () => timers.forEach((timer) => window.clearTimeout(timer));
}, [checks, validating, validation]);
if (!validating && !validation) return null;
const finished = Boolean(validation) && !validating && settledCheckCount >= checks.length;
const shownChecks = finished ? checks : checks.slice(0, settledCheckCount + 1);
const status = validation?.status ?? (feature.configured ? "configured" : "needs_setup");
const presentation = channelUiPresentation(feature.name, feature.webui);
const identity = validation?.identity?.name
? validation.identity.workspace
? `${validation.identity.name} · ${validation.identity.workspace}`
: validation.identity.name
: presentation?.displayName ?? feature.display_name;
return (
<div
role="status"
aria-live="polite"
aria-atomic="true"
className="rounded-control border border-border/60 bg-muted/25 px-3 py-3"
>
<div className="space-y-2.5">
{validating ? (
<div className="flex items-center gap-2 px-2.5 text-[12px] font-medium text-foreground/85">
<Loader2 className="h-3.5 w-3.5 animate-spin text-muted-foreground" aria-hidden />
{t("settings.channels.checking", { defaultValue: "Checking..." })}
</div>
) : null}
{!validating ? shownChecks.map((check, index) => {
const pending = !finished && index === settledCheckCount;
return (
<div
key={check.id}
className="flex animate-in gap-2 px-2.5 fade-in-0 slide-in-from-top-1 text-[12px] leading-5 duration-200 motion-reduce:animate-none"
>
<span className={cn(
"mt-0.5",
pending ? "text-muted-foreground" : channelValidationCheckIconClass(check.status),
)}>
{pending
? <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
: channelValidationCheckIcon(check.status)}
</span>
<div className="min-w-0 flex-1">
<div className="flex min-w-0 items-center gap-x-2 font-medium text-foreground/85">
<span className="min-w-0 truncate">{channelValidationMessage(check.label, t)}</span>
{!pending && check.action_url ? (
<a
href={check.action_url}
target="_blank"
rel="noreferrer"
className="inline-flex shrink-0 items-center gap-1 whitespace-nowrap text-foreground underline decoration-border underline-offset-4"
>
{t("settings.channels.open")}
<ExternalLink className="h-3 w-3" aria-hidden />
</a>
) : null}
</div>
{!pending && check.status !== "pass" && check.message ? (
<div className="text-muted-foreground">
{channelValidationMessage(check.message, t)}
</div>
) : null}
</div>
</div>
);
}) : null}
{finished ? (
<div
className={cn(
"flex animate-in items-center gap-2 rounded-control px-2.5 py-2 text-[12px] font-medium fade-in-0 duration-200 motion-reduce:animate-none",
channelValidationStatusClass(status),
)}
>
{channelValidationStatusIcon(status)}
<span className="min-w-0 truncate font-semibold">{identity}</span>
<span className="lowercase">{channelValidationStatusLabel(status, t)}</span>
</div>
) : null}
</div>
</div>
);
}
@@ -1,5 +1,4 @@
import type { ReactNode } from "react";
import { Check, CircleAlert, Eye, EyeOff, X } from "lucide-react";
import { Eye, EyeOff } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Input } from "@/components/ui/input";
@@ -62,58 +61,21 @@ export function channelValuesForSubmit(
return payload;
}
export function channelValidationStatusLabel(
status: string,
t: ReturnType<typeof useTranslation>["t"],
): string {
const labels: Record<string, string> = {
connected: "Connected",
configured: "Not verified",
needs_setup: "Needs setup",
invalid: "Invalid",
unsupported: "Manual setup",
};
return t(`settings.channels.validation.${status}`, {
defaultValue: labels[status] ?? "Checked",
});
}
export function channelValidationStatusClass(status: string): string {
if (status === "connected") {
return "bg-emerald-500/10 text-emerald-700 dark:text-emerald-200";
}
if (status === "configured") {
return "bg-blue-500/10 text-blue-700 dark:text-blue-200";
}
if (status === "invalid") {
return "bg-destructive/10 text-destructive";
}
return "bg-muted text-muted-foreground";
}
export function channelValidationStatusIcon(status: string): ReactNode {
if (status === "connected") {
return <Check className="h-3.5 w-3.5" aria-hidden />;
}
if (status === "invalid") {
return <X className="h-3.5 w-3.5" aria-hidden />;
}
return <CircleAlert className="h-3.5 w-3.5" aria-hidden />;
}
export function channelValidationCheckIcon(status: string): ReactNode {
if (status === "pass") return <Check className="h-3.5 w-3.5" aria-hidden />;
if (status === "fail") return <X className="h-3.5 w-3.5" aria-hidden />;
if (status === "warn") return <CircleAlert className="h-3.5 w-3.5" aria-hidden />;
return <CircleAlert className="h-3.5 w-3.5" aria-hidden />;
}
export function channelValidationCheckIconClass(status: string): string {
if (status === "pass") return "text-emerald-600";
if (status === "fail") return "text-destructive";
if (status === "warn") return "text-amber-600";
return "text-muted-foreground";
}
export type CredentialFormProps = {
fields: ChannelConfigField[];
values: Record<string, string>;
configuredFields?: Set<string>;
visibleSecrets: Record<string, boolean>;
onChange: (key: string, value: string) => void;
onFieldBlur?: (key: string) => void;
onToggleSecret: (key: string) => void;
errors?: Record<string, string>;
clearedSecrets?: Set<string>;
onClearSecret?: (key: string, clear: boolean) => void;
compact?: boolean;
showSecretActions?: boolean;
disabled?: boolean;
};
export function CredentialForm({
fields,
@@ -129,21 +91,7 @@ export function CredentialForm({
compact = false,
showSecretActions = false,
disabled = false,
}: {
fields: ChannelConfigField[];
values: Record<string, string>;
configuredFields?: Set<string>;
visibleSecrets: Record<string, boolean>;
onChange: (key: string, value: string) => void;
onFieldBlur?: (key: string) => void;
onToggleSecret: (key: string) => void;
errors?: Record<string, string>;
clearedSecrets?: Set<string>;
onClearSecret?: (key: string, clear: boolean) => void;
compact?: boolean;
showSecretActions?: boolean;
disabled?: boolean;
}) {
}: CredentialFormProps) {
const { t } = useTranslation();
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
return (
@@ -6,9 +6,10 @@ import { Input } from "@/components/ui/input";
import { SegmentedControl } from "@/components/ui/segmented-control";
import { SETTINGS_SEARCH_INPUT_CLASS } from "@/components/settings/shared/SettingsControls";
import type { ChannelFeatureAction } from "@/channel-plugins/types";
import { ChannelCatalogRow } from "@/components/settings/channels/ChannelCatalogRow";
import { localizedChannelDisplayName } from "@/components/settings/channels/ChannelIdentity";
import { ChannelHelpMenu } from "@/components/settings/channels/ChannelHelpMenu";
import { ChannelCatalogRow, ChannelSetupPanel } from "@/components/settings/channels/ChannelSetupPanel";
import { ChannelSetupPanel } from "@/components/settings/channels/ChannelSetupPanel";
import { DismissibleStatusMessage, RestartRequiredNotice, SettingsGroup } from "@/components/settings/shared/SettingsControls";
import type { NanobotFeaturesPayload } from "@/lib/types";
import { Dialog, DialogClose, DialogContent, DialogTitle } from "@/components/ui/dialog";