feat(webui): improve setup flows across chat channels (NAN-112) (#5356)

* feat(webui): improve channel setup flows

* fix(webui): refine channel setup interactions (NAN-112)

* fix(webui): keep email setup sections channel-owned

* fix(webui): remove concrete channel details from shared components

* refactor(webui): remove unused channel setup resources

* fix(webui): finish channel-owned setup boundaries

* fix(webui): update channel switches optimistically

* test(channels): remove obsolete absence assertions

* fix(webui): flatten channel instance settings disclosure

* fix(webui): complete channel setup and connection flows

* fix(whatsapp): wait for session database release

* fix(webui): preserve scrolling channel controls

* fix(webui): stage channel connection checks

* fix(channels): align verification actions

* fix(email): expose connection checks

* fix(webui): align channel field actions

* fix(email): verify account credentials

* fix(wecom): bypass system proxy for websocket

* fix(channels): stabilize async connection cleanup

* fix(webui): autosave channel credentials

* fix(email): make provider presets non-destructive

* test(weixin): isolate persisted QR credentials
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-11 15:22:14 +08:00
1 parent 3cc3012b3a
commit e8a29a0087
291 files changed
+12194 -3979

No files matched your search

@@ -0,0 +1,48 @@
import { CircleHelp, ExternalLink } from "lucide-react";
import { useTranslation } from "react-i18next";
import { channelSetup } from "@/components/settings/channels/ChannelIdentity";
import { docsUrlWithBase } from "@/components/settings/channels/catalog";
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { Tooltip, TooltipProvider, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
import type { NanobotFeatureInfo } from "@/lib/types";
export function ChannelHelpMenu({ feature, chatAppsDocsUrl }: {
feature: NanobotFeatureInfo;
chatAppsDocsUrl?: string;
}) {
const { t, i18n } = useTranslation();
const setup = channelSetup(feature, i18n.resolvedLanguage ?? i18n.language);
const links = [
{ url: setup.officialUrl, label: setup.officialLabel },
{ url: docsUrlWithBase(setup.docsUrl, chatAppsDocsUrl), label: setup.docsLabel },
].filter((link) => link.url);
if (!links.length) return null;
const label = t("settings.channels.help", { defaultValue: "Help" });
return (
<TooltipProvider>
<DropdownMenu>
<Tooltip>
<TooltipTrigger asChild>
<DropdownMenuTrigger asChild>
<button type="button" aria-label={label}
className="grid h-8 w-8 place-items-center rounded-full text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring">
<CircleHelp className="h-4 w-4" aria-hidden />
</button>
</DropdownMenuTrigger>
</TooltipTrigger>
<TooltipContent>{label}</TooltipContent>
</Tooltip>
<DropdownMenuContent align="end">
{links.map((link) => (
<DropdownMenuItem key={link.url} asChild>
<a href={link.url} target="_blank" rel="noreferrer">
{link.label ?? label}
<ExternalLink className="ml-2 h-3.5 w-3.5 text-muted-foreground" aria-hidden />
</a>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
</TooltipProvider>
);
}
@@ -1,5 +1,5 @@
import { useMemo, type ReactNode } from "react";
import type { useTranslation } from "react-i18next";
import { useTranslation } from "react-i18next";
import {
channelFieldMessageKey,
@@ -12,14 +12,17 @@ import {
} from "@/channel-plugins/registry";
import type {
ChannelConfigField,
ChannelFieldPresentation,
ChannelSetupPresentation,
} from "@/components/settings/channels/catalog";
import { channelValidationMessage } from "@/components/settings/channels/validationMessages";
import { useLogoFallback } from "@/hooks/useLogoFallback";
import { normalizeLocale } from "@/i18n/config";
import { logoFallbackUrls } from "@/lib/provider-brand";
import type { ChannelRuntimeStatus, NanobotFeatureInfo } from "@/lib/types";
export type ChannelFilter = "all" | "on" | "off";
export const CHANNEL_SETUP_PANEL_CLASS_NAME =
"min-h-full rounded-panel bg-settings-surface p-6";
export function channelSetup(
feature: NanobotFeatureInfo,
@@ -35,25 +38,23 @@ export function channelSetup(
key,
label: copy?.label ?? fieldLabel(key.split(".").at(-1) ?? key),
placeholder: copy?.placeholder,
help: copy?.help,
};
};
const localizePresentedField = (
field: ChannelFieldPresentation,
): ChannelConfigField => ({
...localizeField(field.key),
section: field.section,
});
const presentation: ChannelSetupPresentation = {
...definition,
primaryActionLabel: setupMessages?.primaryAction,
docsLabel: setupMessages?.docsLabel,
officialLabel: setupMessages?.officialLabel,
summary:
setupMessages?.summary
?? "Enable turns on this channel in nanobot, but this integration still needs platform-specific setup before it can receive messages.",
tryIt: setupMessages?.tryIt,
steps: setupMessages?.steps ?? [
`Open ~/.nanobot/config.json and find channels.${feature.name}.`,
"Add the credentials required by that platform, using the channel documentation as the source of truth.",
"Restart nanobot, then send a small test message from that platform.",
],
fields: definition?.fields?.map((field) => localizeField(field.key)),
manualFields: definition?.manualFields?.map((field) => localizeField(field.key)),
presetLabel: setupMessages?.presetLabel,
sectionLabels: setupMessages?.sections,
fields: definition?.fields?.map(localizePresentedField),
manualFields: definition?.manualFields?.map(localizePresentedField),
actions: definition?.actions?.map((action) => ({
...action,
label: setupMessages?.actions?.[action.id] ?? fieldLabel(action.id),
@@ -83,9 +84,11 @@ export function channelSetup(
...copy,
key: field.key,
label: copy.label,
section: copy.section ?? (field.required ? "credentials" : "advanced"),
secret: field.kind === "secret",
optional: !field.required,
inputType: field.kind === "int" ? "number" : undefined,
kind: field.kind,
inputType: channelFieldInputType(field.field, field.kind),
defaultValue: field.default_value,
options:
field.kind === "enum" || field.kind === "bool"
@@ -106,11 +109,24 @@ export function channelSetup(
officialLabel:
presentation.officialLabel
?? (contract.official_url ? "Open official setup" : undefined),
requirements: contract.requirements,
fields: fields.length ? fields : undefined,
manualFields: manual.length ? manual : undefined,
};
}
function channelFieldInputType(
field: string,
kind: string,
): ChannelConfigField["inputType"] {
if (kind === "int" || kind === "float") return "number";
const normalized = field.toLowerCase();
if (normalized.includes("url")) return "url";
if (normalized.includes("email") || normalized.includes("address")) return "email";
if (normalized.includes("phone")) return "tel";
return undefined;
}
function fieldLabel(value: string): string {
const spaced = value
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
@@ -126,21 +142,14 @@ export function ChannelLogo({
feature: NanobotFeatureInfo;
showBrandLogos: boolean;
}) {
const presentation = channelUiPresentation(feature.name, feature.webui);
const presentation = channelUiPresentation(feature.name, feature.webui)
?? channelUiPresentation(feature.name);
const initials = presentation?.initials ?? feature.display_name.slice(0, 2).toUpperCase();
const color = presentation?.color ?? "#6B7280";
const Icon = presentation?.icon;
const logoUrls = useMemo(() => logoFallbackUrls(presentation?.logoUrl), [presentation?.logoUrl]);
const { logoUrl, onLogoError, onLogoLoad } = useLogoFallback(logoUrls);
if (feature.name === "websocket") {
return (
<span className="grid h-10 w-10 shrink-0 place-items-center rounded-control bg-background">
<img src="/brand/nanobot_mark.svg" alt="" className="h-6 w-6 object-contain" draggable={false} />
</span>
);
}
if (showBrandLogos && logoUrl) {
return (
<span
@@ -194,24 +203,6 @@ export function localizedChannelDisplayName(
return channelTranslator(t, channelUiOwner(feature.name))("displayName", fallback);
}
export function channelDescription(feature: NanobotFeatureInfo, t: ReturnType<typeof useTranslation>["t"]): string {
const fallback =
`Use nanobot from ${channelDisplayName(feature)}.`;
return channelTranslator(t, channelUiOwner(feature.name))("description", fallback);
}
export function channelRequirements(feature: NanobotFeatureInfo, t: ReturnType<typeof useTranslation>["t"]): string {
const fallback =
"Channel credentials and gateway settings";
return channelTranslator(t, channelUiOwner(feature.name))("requirements", fallback);
}
export function channelMatchesFilter(feature: NanobotFeatureInfo, filter: ChannelFilter): boolean {
if (filter === "on") return channelIsRunning(feature);
if (filter === "off") return !channelIsRunning(feature);
return true;
}
export function channelIsRunning(feature: NanobotFeatureInfo): boolean {
return feature.runtime_status === "running";
}
@@ -232,27 +223,11 @@ export function channelStatusLabel(
}
if (channelIsRunning(feature)) return tx("settings.values.on", "On");
if (feature.enabled) return tx("settings.channels.runtimeStopped", "Not running");
if (feature.configured === false) return tx("settings.channels.needsConfig", "Needs setup");
if (feature.configured === true) return tx("settings.nanobotFeatures.ready", "Ready");
return tx("settings.values.off", "Off");
}
export function channelSearchText(
feature: NanobotFeatureInfo,
t?: ReturnType<typeof useTranslation>["t"],
): string {
return [
t ? localizedChannelDisplayName(feature, t) : undefined,
channelDisplayName(feature),
feature.display_name,
feature.name,
feature.status,
t ? channelDescription(feature, t) : undefined,
t ? channelRequirements(feature, t) : undefined,
]
.join(" ")
.toLowerCase();
}
export function ChannelStatusBadge({
children,
status,
@@ -281,10 +256,11 @@ export function ChannelRuntimeError({
message?: string;
className?: string;
}) {
const { t } = useTranslation();
if (!message) return null;
return (
<div className={`${className} rounded-control border border-destructive/20 bg-destructive/5 px-3 py-2 text-[12px] leading-5 text-destructive`}>
{message}
{channelValidationMessage(message, t)}
</div>
);
}
@@ -13,17 +13,12 @@ import {
defaultChannelFieldValues,
} from "@/components/settings/channels/CredentialForm";
import {
CHANNEL_SETUP_PANEL_CLASS_NAME,
ChannelLogo,
ChannelRuntimeError,
ChannelStatusBadge,
channelSetup,
channelStatusLabel,
localizedChannelDisplayName,
} from "@/components/settings/channels/ChannelIdentity";
import {
ChannelGuideLink,
ChannelSetupSteps,
} from "@/components/settings/channels/ChannelSetupParts";
import { Button } from "@/components/ui/button";
import { useLogoFallback } from "@/hooks/useLogoFallback";
import {
@@ -41,7 +36,6 @@ import { cn } from "@/lib/utils";
import { useClient } from "@/providers/ClientProvider";
export type ChannelInstancesPanelCustomization = {
countLabel?: (runningCount: number) => string;
toggleAriaLabel?: (instance: NanobotChannelInstanceInfo) => string;
configuredLabel?: string;
needsSetupLabel?: string;
@@ -53,14 +47,12 @@ export type ChannelInstancesPanelCustomization = {
export function ChannelInstancesPanel({
feature,
showBrandLogos,
chatAppsDocsUrl,
instances: providedInstances,
onFeaturesUpdate,
customization = {},
}: {
feature: NanobotFeatureInfo;
showBrandLogos: boolean;
chatAppsDocsUrl?: string;
instances?: NanobotChannelInstanceInfo[];
onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void;
customization?: ChannelInstancesPanelCustomization;
@@ -70,8 +62,9 @@ export function ChannelInstancesPanel({
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
const displayName = localizedChannelDisplayName(feature, t);
const instances = providedInstances ?? feature.instances ?? [];
const [selectedId, setSelectedId] = useState<string | null>(null);
const [busyInstanceId, setBusyInstanceId] = useState<string | null>(null);
const [editor, setEditor] = useState<{ id: string; expanded: boolean } | null>(null);
const selectedId = editor?.id;
const [pendingToggle, setPendingToggle] = useState<{ id: string; checked: boolean } | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const selected = selectedId ? instances.find((instance) => instance.id === selectedId) : undefined;
const setup = useMemo(
@@ -87,9 +80,9 @@ export function ChannelInstancesPanel({
);
const [visibleSecrets, setVisibleSecrets] = useState<Record<string, boolean>>({});
const [savingFields, setSavingFields] = useState(false);
const configuredCount = instances.filter((instance) => instance.configured).length;
const runningCount = instances.filter((instance) => instance.runtime_status === "running").length;
const selectedValuesKey = JSON.stringify(selected?.config_values ?? {});
const selectedValuesKey = JSON.stringify(
defaultChannelFieldValues(instanceFields, selected?.config_values),
);
const selectedConfiguredFields = useMemo(
() => new Set(selected?.configured_fields ?? []),
[selected?.configured_fields],
@@ -97,17 +90,18 @@ export function ChannelInstancesPanel({
useEffect(() => {
if (selectedId && !instances.some((instance) => instance.id === selectedId)) {
setSelectedId(null);
setEditor(null);
}
}, [instances, selectedId]);
useEffect(() => {
setFieldValues(defaultChannelFieldValues(instanceFields, selected?.config_values));
setVisibleSecrets({});
}, [instanceFields, selected?.id, selectedValuesKey]);
}, [selected?.id, selectedValuesKey]);
const toggleInstance = async (instance: NanobotChannelInstanceInfo, checked: boolean) => {
setBusyInstanceId(instance.id);
if (pendingToggle || savingFields) return;
setPendingToggle({ id: instance.id, checked });
setNotice(null);
try {
const payload = checked
@@ -117,12 +111,12 @@ export function ChannelInstancesPanel({
} catch (err) {
setNotice((err as Error).message);
} finally {
setBusyInstanceId(null);
setPendingToggle(null);
}
};
const saveSelectedInstanceSettings = async () => {
if (!selected) return;
if (!selected || pendingToggle || savingFields) return;
setSavingFields(true);
setNotice(null);
try {
@@ -144,35 +138,24 @@ export function ChannelInstancesPanel({
};
return (
<aside className="min-h-full rounded-panel bg-settings-surface p-5">
<div className="flex items-start justify-between gap-3">
<div className="flex min-w-0 items-start gap-3">
<ChannelLogo feature={feature} showBrandLogos={showBrandLogos} />
<div className="min-w-0 flex-1">
<h3 className="truncate text-[18px] font-semibold leading-6 text-foreground">
{displayName}
</h3>
<p className="mt-1 text-[13px] leading-5 text-muted-foreground">
{customization.countLabel?.(runningCount)
?? t("settings.channels.configuredInstances", {
count: configuredCount,
defaultValue: `${configuredCount} instances configured`,
})}
</p>
</div>
</div>
<div className="flex shrink-0 items-center gap-2">
<ChannelStatusBadge status={feature.runtime_status}>
{channelStatusLabel(feature, tx)}
</ChannelStatusBadge>
</div>
<aside className={CHANNEL_SETUP_PANEL_CLASS_NAME}>
<div className="pe-20">
<ChannelLogo feature={feature} showBrandLogos={showBrandLogos} />
<h3 className="sr-only">{displayName}</h3>
</div>
<ChannelRuntimeError message={feature.runtime_error} />
<div className="mt-5 space-y-3">
{instances.map((instance) => {
const expanded = selected?.id === instance.id;
const expanded = selected?.id === instance.id && editor?.expanded === true;
const toggling = pendingToggle?.id === instance.id;
const checked = toggling ? pendingToggle.checked : instanceToggleChecked(instance);
const instanceSummary = customization.renderInstanceSummary
? customization.renderInstanceSummary(instance)
: instance.id;
const instanceAction = customization.renderInstanceAction?.(instance);
const hasInstanceOverview = Boolean(instanceSummary || instanceAction);
return (
<article
key={instance.id}
@@ -180,18 +163,11 @@ export function ChannelInstancesPanel({
"overflow-hidden rounded-floating transition-colors",
expanded
? "bg-background"
: "bg-background/70 settings-hover",
: "bg-background/70",
)}
>
<div className="flex items-center gap-3 px-3 py-3">
<button
type="button"
className="flex min-w-0 flex-1 items-center gap-3 text-left"
onClick={() =>
setSelectedId((current) => (current === instance.id ? null : instance.id))
}
aria-expanded={expanded}
>
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 px-3 py-3">
<div className="flex min-w-0 flex-[1_1_12rem] items-center gap-3">
<ChannelInstanceAvatar
feature={feature}
instance={instance}
@@ -200,22 +176,43 @@ export function ChannelInstancesPanel({
<span className="min-w-0 flex-1 truncate text-[13px] font-semibold text-foreground">
{channelInstanceDisplayName(instance)}
</span>
<ChevronDown
className={cn(
"h-4 w-4 shrink-0 text-muted-foreground transition-transform",
expanded && "rotate-180",
)}
aria-hidden
<ChannelInstanceStatusBadge
instance={instance}
configuredLabel={customization.configuredLabel}
needsSetupLabel={customization.needsSetupLabel}
/>
</button>
<div className="flex shrink-0 items-center gap-2">
{busyInstanceId === instance.id ? (
</div>
<div className="ms-auto flex shrink-0 items-center gap-3">
{instanceFields.length ? (
<button
type="button"
className="inline-flex min-h-8 items-center gap-1.5 rounded px-1 text-[12px] text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-offset-2"
onClick={() =>
setEditor((current) => ({
id: instance.id,
expanded: current?.id !== instance.id || !current.expanded,
}))
}
aria-expanded={expanded}
>
{tx("settings.channels.advanced", "Advanced")}
<ChevronDown
className={cn(
"h-3.5 w-3.5 transition-transform motion-reduce:transition-none",
expanded && "rotate-180",
)}
aria-hidden
/>
</button>
) : null}
{toggling ? (
<Loader2 className="h-3.5 w-3.5 animate-spin text-muted-foreground" aria-hidden />
) : null}
<ToggleButton
checked={instanceToggleChecked(instance)}
checked={checked}
disabled={
busyInstanceId === instance.id
Boolean(pendingToggle)
|| savingFields
|| !instance.configured
}
ariaLabel={customization.toggleAriaLabel?.(instance)
@@ -223,51 +220,28 @@ export function ChannelInstancesPanel({
name: channelInstanceDisplayName(instance),
defaultValue: "{{name}} instance",
})}
label={instanceToggleChecked(instance) ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}
label={checked ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}
onChange={(checked) => void toggleInstance(instance, checked)}
/>
</div>
</div>
{expanded ? (
<div className="space-y-5 px-4 pb-4">
<section className="pt-4">
<div className="mb-3 flex items-start justify-between gap-3">
{hasInstanceOverview || (expanded && instanceFields.length > 0) ? (
<div className="space-y-3 px-4 pb-4 pt-1">
{hasInstanceOverview ? <section className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
{instanceSummary ? (
<p className="min-w-0 flex-1 truncate font-mono text-[11.5px] leading-6 text-muted-foreground">
{customization.renderInstanceSummary?.(instance) ?? instance.id}
{instanceSummary}
</p>
<ChannelInstanceStatusBadge
instance={instance}
configuredLabel={customization.configuredLabel}
needsSetupLabel={customization.needsSetupLabel}
/>
</div>
{customization.renderInstanceAction?.(instance)}
</section>
<ChannelSetupSteps
steps={setup.steps}
action={
<ChannelGuideLink
feature={feature}
setup={setup}
chatAppsDocsUrl={chatAppsDocsUrl}
compact
/>
}
/>
{instanceFields.length ? (
<details className="group text-[12px] leading-5 text-muted-foreground">
<summary className="cursor-pointer list-none text-[12px] font-semibold text-foreground">
<span className="inline-flex items-center gap-1.5">
{tx("settings.channels.advanced", "Advanced")}
<ChevronDown
className="h-3.5 w-3.5 transition-transform group-open:rotate-180"
aria-hidden
/>
</span>
</summary>
) : <span className="flex-1" />}
{instanceAction}
</section> : null}
{expanded && instanceFields.length > 0 ? (
<div className={cn(
"text-[12px] leading-5 text-muted-foreground",
hasInstanceOverview && "border-t border-border/50 pt-3",
)}>
<form
className="mt-3"
onSubmit={(event) => {
event.preventDefault();
void saveSelectedInstanceSettings();
@@ -292,7 +266,7 @@ export function ChannelInstancesPanel({
size="sm"
variant="secondary"
className="h-8 rounded-full bg-muted/70 px-3 text-[12px] font-semibold settings-hover"
disabled={savingFields}
disabled={savingFields || Boolean(pendingToggle)}
>
{savingFields ? (
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />
@@ -301,7 +275,7 @@ export function ChannelInstancesPanel({
</Button>
</div>
</form>
</details>
</div>
) : null}
</div>
) : null}
@@ -1,6 +1,7 @@
import { channelValidationMessage } from "./validationMessages";
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
import QRCode from "qrcode";
import { Check, Loader2, Network, RotateCcw } from "lucide-react";
import { Check, Loader2, RotateCcw } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
@@ -28,13 +29,6 @@ export type ChannelQrConnectLabels = {
connect: string;
};
export type ChannelConnectStartOptions = {
domain?: string;
instanceId?: string;
mode?: "replace" | "create";
force?: boolean;
};
export type ChannelQrConnectPendingContext = {
connect: ChannelConnectPayload;
busy: boolean;
@@ -45,10 +39,12 @@ export type ChannelQrConnectPendingContext = {
export function ChannelQrConnectFlow({
channelName,
startOptions = {},
startParams = {},
idleLabel,
connectRequestId,
forceOnRepeat = false,
autoStart = false,
minimalPending = false,
labels,
onFeaturesUpdate,
pausePolling,
@@ -58,10 +54,12 @@ export function ChannelQrConnectFlow({
}: {
token: string;
channelName: string;
startOptions?: ChannelConnectStartOptions;
startParams?: Readonly<Record<string, string | boolean>>;
idleLabel?: string;
connectRequestId?: number;
forceOnRepeat?: boolean;
autoStart?: boolean;
minimalPending?: boolean;
labels: ChannelQrConnectLabels;
onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void;
pausePolling?: (payload: ChannelConnectPayload) => boolean;
@@ -77,19 +75,16 @@ export function ChannelQrConnectFlow({
const [qrDataUrl, setQrDataUrl] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [handledRequestId, setHandledRequestId] = useState(0);
const handledRequestId = useRef(0);
const autoStarted = useRef(false);
const pollInFlight = useRef(false);
const startDomain = startOptions.domain;
const startInstanceId = startOptions.instanceId;
const startMode = startOptions.mode;
const startForce = startOptions.force;
const pending = connect?.status === "pending";
const succeeded = connect?.status === "succeeded";
const canStart = !pending && !busy;
const pollingPaused = Boolean(connect && pausePolling?.(connect));
const displayMessage = connect
? resolveMessage?.(connect) ?? connect.message
? resolveMessage?.(connect) ?? (connect.message ? channelValidationMessage(connect.message, t) : undefined)
: undefined;
useEffect(() => {
@@ -176,10 +171,8 @@ export function ChannelQrConnectFlow({
setError(null);
try {
const payload = await startChannelConnect(client, channelName, {
domain: startDomain,
instanceId: startInstanceId,
mode: startMode,
force: force || startForce,
...startParams,
...(force ? { force: true } : {}),
});
setConnect(payload);
} catch (err) {
@@ -187,13 +180,15 @@ export function ChannelQrConnectFlow({
} finally {
setBusy(false);
}
}, [channelName, client, startDomain, startForce, startInstanceId, startMode]);
}, [channelName, client, startParams]);
useEffect(() => {
if (!connectRequestId || connectRequestId === handledRequestId) return;
setHandledRequestId(connectRequestId);
const requested = Boolean(connectRequestId && connectRequestId !== handledRequestId.current);
if (!requested && !(autoStart && !autoStarted.current)) return;
handledRequestId.current = connectRequestId ?? 0;
autoStarted.current = true;
void start();
}, [connectRequestId, handledRequestId, start]);
}, [autoStart, connectRequestId, start]);
const cancel = async () => {
if (!connect?.session_id) {
@@ -250,7 +245,28 @@ export function ChannelQrConnectFlow({
return (
<div className="mt-3 space-y-3">
{pending ? (
{autoStart && busy && !connect ? (
<div role="status" className="grid min-h-[228px] place-items-center">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" aria-hidden />
<span className="sr-only">{labels.connecting}</span>
</div>
) : null}
{pending && minimalPending ? (
<div className="flex min-h-[228px] flex-col items-center justify-center gap-4 py-4">
<div className="grid h-[196px] w-[196px] place-items-center rounded-control bg-background shadow-[inset_0_0_0_1px_oklch(0_0_0/0.1)] dark:shadow-[inset_0_0_0_1px_oklch(1_0_0/0.1)]">
{qrDataUrl ? (
<img
src={qrDataUrl}
alt={labels.qrAlt}
className="h-[184px] w-[184px]"
/>
) : (
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" aria-hidden />
)}
</div>
{renderPending?.({ connect, busy, poll: submitPoll })}
</div>
) : pending ? (
<div className="grid gap-4 rounded-control border border-border/70 p-4 sm:grid-cols-[auto_minmax(0,1fr)]">
<div className="grid h-[196px] w-[196px] place-items-center rounded-control border border-border/60 bg-background">
{qrDataUrl ? (
@@ -268,12 +284,12 @@ export function ChannelQrConnectFlow({
{labels.scanTitle}
</div>
<p className="mt-1 text-[12.5px] leading-5 text-muted-foreground">
{labels.scanDescription}
{qrDataUrl ? labels.scanDescription : null}
</p>
{renderPending?.({ connect, busy, poll: submitPoll }) ?? (
<div className="mt-3 flex items-center gap-2 text-[12px] text-muted-foreground">
<Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
{labels.waiting}
{qrDataUrl ? labels.waiting : labels.connecting}
</div>
)}
<div className="mt-4 flex flex-wrap justify-end gap-2">
@@ -311,7 +327,7 @@ export function ChannelQrConnectFlow({
</div>
) : null}
<div className="flex flex-wrap justify-end gap-2">
{!pending && !(autoStart && busy && !connect) ? <div className="flex flex-wrap justify-end gap-2">
<Button
type="button"
size="sm"
@@ -324,16 +340,14 @@ export function ChannelQrConnectFlow({
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />
) : succeeded ? (
<RotateCcw className="mr-1.5 h-3.5 w-3.5" aria-hidden />
) : (
<Network className="mr-1.5 h-3.5 w-3.5" aria-hidden />
)}
) : null}
{pending
? labels.connecting
: succeeded
? labels.scanAgain
: idleLabel ?? labels.connect}
</Button>
</div>
</div> : null}
</div>
);
}
File diff suppressed because it is too large. Load diff
@@ -1,11 +1,11 @@
import { useMemo, useState, type ReactNode } from "react";
import { channelValidationMessage } from "./validationMessages";
import { useEffect, useMemo, useState } from "react";
import { Clipboard, ExternalLink, Loader2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { channelUiPresentation } from "@/channel-plugins/registry";
import { Button } from "@/components/ui/button";
import {
docsUrlWithBase,
type ChannelProviderPreset,
type ChannelSetupPresentation,
} from "@/components/settings/channels/catalog";
@@ -16,154 +16,13 @@ import {
channelValidationStatusIcon,
channelValidationStatusLabel,
} from "@/components/settings/channels/CredentialForm";
import { useLogoFallback } from "@/hooks/useLogoFallback";
import { copyTextToClipboard } from "@/lib/clipboard";
import { logoFallbackUrls } from "@/lib/provider-brand";
import type {
ChannelValidationPayload,
NanobotFeatureInfo,
} from "@/lib/types";
import { cn } from "@/lib/utils";
export function ChannelGuideLink({
feature,
setup,
chatAppsDocsUrl,
compact = false,
}: {
feature: NanobotFeatureInfo;
setup: ChannelSetupPresentation;
chatAppsDocsUrl?: string;
compact?: boolean;
}) {
const { t } = useTranslation();
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
const presentation = channelUiPresentation(feature.name, feature.webui);
const logoUrls = useMemo(
() => logoFallbackUrls(setup.docsLogoUrl ?? presentation?.logoUrl),
[presentation?.logoUrl, setup.docsLogoUrl],
);
const { logoUrl, onLogoError, onLogoLoad } = useLogoFallback(logoUrls);
const Icon = presentation?.icon;
const initials = presentation?.initials ?? feature.display_name.slice(0, 2).toUpperCase();
const color = presentation?.color ?? "#6B7280";
const docsUrl = docsUrlWithBase(setup.docsUrl, chatAppsDocsUrl);
if (!docsUrl) return null;
return (
<a
href={docsUrl}
target="_blank"
rel="noreferrer"
className={cn(
"inline-flex max-w-full items-center gap-2 bg-background/80 font-semibold text-foreground transition-colors settings-hover",
compact
? "shrink-0 rounded-full py-1 pl-1 pr-2.5 text-[11.5px]"
: "mt-3 rounded-control py-1.5 pl-1.5 pr-3 text-[12px]",
)}
>
<span
className={cn(
"grid shrink-0 place-items-center overflow-hidden bg-muted/70 font-bold",
compact ? "h-5 w-5 rounded-full text-[9px]" : "h-6 w-6 rounded-compact text-[10px]",
)}
style={{ color }}
aria-hidden
>
{logoUrl ? (
<img
src={logoUrl}
alt=""
decoding="async"
loading="lazy"
className={cn("object-contain", compact ? "h-3.5 w-3.5" : "h-4 w-4")}
onLoad={onLogoLoad}
onError={onLogoError}
/>
) : Icon ? (
<Icon className={compact ? "h-3 w-3" : "h-3.5 w-3.5"} strokeWidth={2.25} />
) : (
initials
)}
</span>
<span className="truncate">
{setup.docsLabel ?? tx("settings.channels.officialGuide", "Official guide")}
</span>
<ExternalLink className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />
</a>
);
}
export function ChannelSetupLinks({
feature,
setup,
chatAppsDocsUrl,
}: {
feature: NanobotFeatureInfo;
setup: ChannelSetupPresentation;
chatAppsDocsUrl?: string;
}) {
return (
<div className="mt-3 flex flex-wrap items-center gap-2">
<ChannelOfficialLink feature={feature} setup={setup} />
<ChannelGuideLink feature={feature} setup={setup} chatAppsDocsUrl={chatAppsDocsUrl} compact />
</div>
);
}
function ChannelOfficialLink({
feature,
setup,
}: {
feature: NanobotFeatureInfo;
setup: ChannelSetupPresentation;
}) {
const presentation = channelUiPresentation(feature.name, feature.webui);
const logoUrls = useMemo(
() => logoFallbackUrls(setup.docsLogoUrl ?? presentation?.logoUrl),
[presentation?.logoUrl, setup.docsLogoUrl],
);
const { logoUrl, onLogoError, onLogoLoad } = useLogoFallback(logoUrls);
const Icon = presentation?.icon;
const initials = presentation?.initials ?? feature.display_name.slice(0, 2).toUpperCase();
const color = presentation?.color ?? "#6B7280";
const label = setup.officialLabel;
if (!setup.officialUrl || !label) return null;
return (
<a
href={setup.officialUrl}
target="_blank"
rel="noreferrer"
className="inline-flex max-w-full shrink-0 items-center gap-2 rounded-full bg-background/80 py-1 pl-1 pr-2.5 text-[11.5px] font-semibold text-foreground transition-colors settings-hover"
>
<span
className="grid h-5 w-5 shrink-0 place-items-center overflow-hidden rounded-full bg-muted/70"
style={{ color }}
aria-hidden
>
{logoUrl ? (
<img
src={logoUrl}
alt=""
decoding="async"
loading="lazy"
className="h-3.5 w-3.5 object-contain"
onLoad={onLogoLoad}
onError={onLogoError}
/>
) : Icon ? (
<Icon className="h-3 w-3" strokeWidth={2.25} />
) : (
<span className="text-[8px] font-bold">{initials}</span>
)}
</span>
<span className="truncate">{label}</span>
<ExternalLink className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />
</a>
);
}
export function ChannelSetupActions({
feature,
setup,
@@ -216,48 +75,48 @@ export function ChannelSetupActions({
export function ChannelProviderPresets({
presets,
onApply,
label,
disabled = false,
}: {
presets: ChannelProviderPreset[];
onApply: (preset: ChannelProviderPreset) => void;
label?: string;
disabled?: boolean;
}) {
const { t } = useTranslation();
const [selected, setSelected] = useState("");
if (!presets.length) return null;
return (
<div className="mt-3">
<div className="mb-1 text-[11px] font-medium text-foreground/85">
{t("settings.channels.providerPreset", { defaultValue: "Provider" })}
</div>
<div
role="radiogroup"
aria-label={t("settings.channels.providerPreset", { defaultValue: "Provider" })}
className="grid rounded-control bg-muted p-0.5 text-[12px] font-medium text-muted-foreground"
style={{ gridTemplateColumns: `repeat(${presets.length}, minmax(0, 1fr))` }}
>
<fieldset>
<legend className="mb-1 text-[11px] font-medium text-foreground/85">
{label ?? t("settings.channels.providerPreset", { defaultValue: "Provider" })}
</legend>
<div className="flex flex-wrap gap-2">
{presets.map((preset) => (
<button
<Button
key={preset.id}
type="button"
role="radio"
aria-checked={selected === preset.id}
onClick={() => {
setSelected(preset.id);
onApply(preset);
}}
className={cn(
"min-h-8 rounded-compact px-2 py-1.5 transition-colors hover:text-foreground",
selected === preset.id && "bg-background text-foreground",
)}
size="sm"
variant="outline"
disabled={disabled}
className="h-8 rounded-full px-3 text-[12px] font-medium"
onClick={() => onApply(preset)}
>
{preset.label}
</button>
</Button>
))}
</div>
</div>
</fieldset>
);
}
export function ChannelValidationBadge({
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,
@@ -267,118 +126,108 @@ export function ChannelValidationBadge({
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 label = validating
? t("settings.channels.checking", { defaultValue: "Checking..." })
: channelValidationStatusLabel(status, t);
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 (
<span
className={cn(
"inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[11.5px] font-medium",
channelValidationStatusClass(status),
)}
<div
role="status"
aria-live="polite"
aria-atomic="true"
className="rounded-control border border-border/60 bg-muted/25 px-3 py-3"
>
{validating ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
) : (
channelValidationStatusIcon(status)
)}
{label}
</span>
);
}
export function ChannelValidationDetails({ validation }: { validation: ChannelValidationPayload | null }) {
const message = validation?.message;
if (!validation?.identity?.name && !message) return null;
return (
<div className="mt-2 truncate text-[11.5px] text-muted-foreground">
{validation?.identity?.name
? validation.identity.workspace
? `${validation.identity.name} · ${validation.identity.workspace}`
: validation.identity.name
: message}
</div>
);
}
export function ChannelValidationChecks({ validation }: { validation: ChannelValidationPayload }) {
const { t } = useTranslation();
if (!validation.checks.length) return null;
return (
<div>
<div className="mb-2 text-[12px] font-semibold text-foreground">
{t("settings.channels.connectionChecks")}
</div>
<div className="space-y-2">
{validation.checks.slice(0, 6).map((check) => (
<div key={check.id} className="flex gap-2 text-[12px] leading-5">
<span className={cn("mt-0.5", channelValidationCheckIconClass(check.status))}>
{channelValidationCheckIcon(check.status)}
</span>
<div className="min-w-0 flex-1">
<div className="font-medium text-foreground/85">{check.label}</div>
{check.message ? (
<div className="text-muted-foreground">{check.message}</div>
) : null}
{check.action_url ? (
<a
href={check.action_url}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1 text-foreground underline decoration-border underline-offset-4"
>
{t("settings.channels.open")}
<ExternalLink className="h-3 w-3" aria-hidden />
</a>
) : null}
</div>
<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>
);
}
export function ChannelSetupSteps({
steps,
action,
tryIt,
}: {
steps: string[];
action?: ReactNode;
tryIt?: string;
}) {
const { t } = useTranslation();
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
return (
<div className="text-[12.5px] leading-5 text-muted-foreground">
<div className="mb-2 flex items-center justify-between gap-3">
<div className="text-[12px] font-semibold text-foreground">
{tx("settings.channels.setupSteps", "Next steps")}
</div>
{action}
</div>
<ol className="space-y-1.5">
{steps.map((step, index) => (
<li key={step} className="flex gap-2">
<span className="mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-full bg-muted text-[10px] font-semibold text-muted-foreground">
{index + 1}
</span>
<span>{step}</span>
</li>
))}
</ol>
{tryIt ? (
<div className="mt-3 rounded-control bg-background/75 px-3 py-2 text-[12px] text-muted-foreground">
<span className="font-medium text-foreground">
{tx("settings.channels.tryIt", "Try it")}
</span>
<span className="ml-2">
{tryIt}
</span>
</div>
) : null}
</div>
);
}
@@ -3,6 +3,7 @@ import { Check, CircleAlert, Eye, EyeOff, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import type { ChannelConfigField } from "@/components/settings/channels/catalog";
import { cn } from "@/lib/utils";
@@ -10,6 +11,10 @@ function channelFieldValue(field: ChannelConfigField, values: Record<string, str
return values[field.key] ?? field.defaultValue ?? field.options?.[0]?.value ?? "";
}
export function channelFieldInputId(key: string): string {
return `channel-field-${key.replace(/[^a-zA-Z0-9_-]/g, "-")}`;
}
export function defaultChannelFieldValues(
fields: ChannelConfigField[],
configValues: Record<string, string> | undefined = undefined,
@@ -39,9 +44,14 @@ export function channelValuesForSubmit(
fields: ChannelConfigField[],
values: Record<string, string>,
touchedFields: Set<string>,
): Record<string, string> {
const payload: Record<string, string> = {};
clearedSecrets: Set<string> = new Set(),
): Record<string, string | null> {
const payload: Record<string, string | null> = {};
for (const field of fields) {
if (field.secret && clearedSecrets.has(field.key)) {
payload[field.key] = null;
continue;
}
const touched = touchedFields.has(field.key);
const value = channelFieldValue(field, values);
if (field.secret && !value.trim()) continue;
@@ -58,7 +68,7 @@ export function channelValidationStatusLabel(
): string {
const labels: Record<string, string> = {
connected: "Connected",
configured: "Configured manually",
configured: "Not verified",
needs_setup: "Needs setup",
invalid: "Invalid",
unsupported: "Manual setup",
@@ -82,7 +92,7 @@ export function channelValidationStatusClass(status: string): string {
}
export function channelValidationStatusIcon(status: string): ReactNode {
if (status === "connected" || status === "configured") {
if (status === "connected") {
return <Check className="h-3.5 w-3.5" aria-hidden />;
}
if (status === "invalid") {
@@ -111,34 +121,53 @@ export function CredentialForm({
configuredFields,
visibleSecrets,
onChange,
onFieldBlur,
onToggleSecret,
errors = {},
clearedSecrets = new Set(),
onClearSecret,
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;
}) {
const { t } = useTranslation();
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
return (
<div className={cn(compact ? "space-y-2.5" : "mt-3 space-y-2.5")}>
<div className={cn("grid", compact ? "gap-y-4" : "mt-3 gap-y-2.5")}>
{fields.map((field) => {
const inputId = channelFieldInputId(field.key);
const error = errors[field.key];
const errorId = error ? `${inputId}-error` : undefined;
const describedBy = errorId;
const visible = Boolean(visibleSecrets[field.key]);
const value = values[field.key] ?? "";
const savedSecret = Boolean(field.secret && configuredFields?.has(field.key) && !value.trim());
const clearSecret = clearedSecrets.has(field.key);
const savedSecret = Boolean(
field.secret && configuredFields?.has(field.key) && !value.trim() && !clearSecret,
);
const showSecretToggle = Boolean(field.secret && value.trim());
const inputType = field.secret && !visible ? "password" : field.inputType ?? "text";
const selectedOption = channelFieldValue(field, values);
const header = (
<span className="flex items-center justify-between gap-2 text-[11px] font-medium text-foreground/85">
<span>{field.label}</span>
{savedSecret ? (
<span className="font-normal text-muted-foreground">
{tx("settings.channels.savedSecret", "Saved")}
{clearSecret ? (
<span className="font-normal text-destructive">
{tx("settings.channels.secretWillBeRemoved", "Will be removed")}
</span>
) : field.optional && !compact ? (
<span className="font-normal text-muted-foreground">
@@ -147,48 +176,94 @@ export function CredentialForm({
) : null}
</span>
);
const help = field.help ? (
<span className="mt-1 block text-[11px] leading-4 text-muted-foreground">
{field.help}
const errorMessage = error ? (
<span id={errorId} className="mt-1 block text-[11px] leading-4 text-destructive">
{error}
</span>
) : null;
if (field.options?.length) {
return (
<div key={field.key} className="block">
{header}
<fieldset
key={field.key}
id={`${inputId}-group`}
aria-labelledby={`${inputId}-label`}
aria-invalid={Boolean(error)}
aria-describedby={describedBy}
className="block"
>
<div className="grid grid-cols-[minmax(0,0.8fr)_minmax(0,1.2fr)] items-start gap-x-4">
<span id={`${inputId}-label`} className="flex min-h-12 items-center sm:min-h-10">{header}</span>
<div className="min-w-0">
<span
role="radiogroup"
aria-label={field.label}
className="mt-1 grid rounded-control bg-muted p-0.5 text-[12px] font-medium text-muted-foreground"
className="grid rounded-control bg-muted p-0.5 text-[12px] font-medium text-muted-foreground"
style={{ gridTemplateColumns: `repeat(${field.options.length}, minmax(0, 1fr))` }}
>
{field.options.map((option) => (
<button
key={option.value}
type="button"
role="radio"
aria-checked={selectedOption === option.value}
onClick={() => onChange(field.key, option.value)}
className={cn(
"min-h-8 rounded-compact px-2 py-1.5 transition-colors hover:text-foreground",
selectedOption === option.value
&& "bg-background text-foreground ring-1 ring-inset ring-border/45",
)}
>
{option.label}
</button>
{field.options.map((option, index) => (
<label key={option.value} className="relative block">
<input
id={index === 0 ? inputId : `${inputId}-${index}`}
type="radio"
name={inputId}
value={option.value}
checked={selectedOption === option.value}
disabled={disabled}
aria-invalid={Boolean(error)}
aria-describedby={describedBy}
onChange={() => onChange(field.key, option.value)}
onBlur={() => onFieldBlur?.(field.key)}
className="peer sr-only"
/>
<span className="grid min-h-11 cursor-pointer place-items-center rounded-compact px-2 py-1.5 transition-colors hover:text-foreground peer-checked:bg-background peer-checked:text-foreground peer-checked:ring-1 peer-checked:ring-inset peer-checked:ring-border/45 peer-focus-visible:ring-2 peer-focus-visible:ring-ring sm:min-h-9">
{option.label}
</span>
</label>
))}
</span>
{help}
{errorMessage}
</div>
</div>
</fieldset>
);
}
if (field.kind === "json") {
return (
<div key={field.key} className="grid grid-cols-[minmax(0,0.8fr)_minmax(0,1.2fr)] items-start gap-x-4">
<label htmlFor={inputId} className="flex min-h-10 min-w-0 items-center self-start sm:min-h-9">
{header}
</label>
<div className="min-w-0">
<Textarea
id={inputId}
aria-label={field.label}
aria-invalid={Boolean(error)}
aria-describedby={describedBy}
placeholder={field.placeholder}
value={value}
disabled={disabled}
onChange={(event) => onChange(field.key, event.target.value)}
onBlur={() => onFieldBlur?.(field.key)}
rows={4}
spellCheck={false}
className={cn(
"resize-y border-border/40 bg-background font-mono text-[12px]",
error && "border-destructive focus-visible:ring-destructive/30",
)}
/>
{errorMessage}
</div>
</div>
);
}
return (
<label key={field.key} className="block">
{header}
<span className="relative mt-1 block">
<div key={field.key} className="grid grid-cols-[minmax(0,0.8fr)_minmax(0,1.2fr)] items-start gap-x-4">
<label htmlFor={inputId} className="flex min-h-10 min-w-0 items-center self-start sm:min-h-9">{header}</label>
<div className="min-w-0">
<span className="relative block">
<Input
id={inputId}
aria-label={field.label}
aria-invalid={Boolean(error)}
aria-describedby={describedBy}
type={inputType}
autoComplete={field.secret ? "off" : undefined}
inputMode={field.inputType === "number" ? "numeric" : undefined}
@@ -198,9 +273,12 @@ export function CredentialForm({
: field.placeholder
}
value={values[field.key] ?? ""}
disabled={disabled}
onChange={(event) => onChange(field.key, event.target.value)}
onBlur={() => onFieldBlur?.(field.key)}
className={cn(
"h-9 rounded-full border-border/60 bg-muted/35 text-[13px]",
"h-10 rounded-full border-border/40 bg-background text-base sm:h-9 sm:text-[13px]",
error && "border-destructive focus-visible:ring-destructive/30",
showSecretToggle && "pr-9",
)}
/>
@@ -213,7 +291,8 @@ export function CredentialForm({
: tx("settings.channels.showSecret", "Show secret")
}
onClick={() => onToggleSecret(field.key)}
className="absolute right-2 top-1/2 grid h-6 w-6 -translate-y-1/2 place-items-center rounded-full text-muted-foreground settings-hover hover:text-foreground"
disabled={disabled}
className="absolute right-0 top-1/2 grid h-10 w-10 -translate-y-1/2 place-items-center rounded-full text-muted-foreground hover:bg-background hover:text-foreground sm:right-1 sm:h-8 sm:w-8"
>
{visible ? (
<EyeOff className="h-3.5 w-3.5" aria-hidden />
@@ -223,8 +302,21 @@ export function CredentialForm({
</button>
) : null}
</span>
{help}
</label>
{errorMessage}
{showSecretActions && field.secret && configuredFields?.has(field.key) && !value.trim() && onClearSecret ? (
<button
type="button"
className="mt-1 min-h-8 text-[11px] font-medium text-muted-foreground underline-offset-4 hover:text-foreground hover:underline"
onClick={() => onClearSecret(field.key, !clearSecret)}
disabled={disabled}
>
{clearSecret
? tx("settings.channels.keepSavedSecret", "Keep saved credential")
: tx("settings.channels.removeSavedSecret", "Remove saved credential")}
</button>
) : null}
</div>
</div>
);
})}
</div>
@@ -1,10 +1,10 @@
import type { LucideIcon } from "lucide-react";
import type { ComponentType } from "react";
export type ChannelPresentation = {
displayName: string;
initials: string;
color: string;
icon?: LucideIcon;
icon?: ComponentType<{ className?: string; strokeWidth?: string | number }>;
logoUrl?: string;
setup?: ChannelCatalogSetupPresentation;
};
@@ -15,14 +15,13 @@ export type ChannelSetupPresentation = {
command?: string;
docsUrl?: string;
docsLabel?: string;
docsLogoUrl?: string;
officialUrl?: string;
officialLabel?: string;
summary?: string;
tryIt?: string;
steps: string[];
presetLabel?: string;
sectionLabels?: Record<string, string>;
fields?: ChannelConfigField[];
manualFields?: ChannelConfigField[];
requirements?: ChannelSetupRequirement[];
actions?: ChannelSetupAction[];
presets?: ChannelProviderPreset[];
};
@@ -31,15 +30,28 @@ type ChannelCatalogSetupPresentation = {
mode?: "webui" | "credentials" | "connect";
command?: string;
docsUrl?: string;
docsLogoUrl?: string;
fields?: ChannelFieldPresentation[];
manualFields?: ChannelFieldPresentation[];
actions?: ChannelSetupActionDefinition[];
presets?: ChannelProviderPresetDefinition[];
};
type ChannelFieldPresentation = {
export type ChannelFieldPresentation = {
key: string;
section?: string;
};
export type ChannelFieldSection =
| "account"
| "credentials"
| "connection"
| "access"
| "behavior"
| "security"
| "advanced";
export type ChannelSetupRequirement = {
alternatives: string[][];
};
type ChannelSetupActionDefinition = Omit<ChannelSetupAction, "label">;
@@ -66,8 +78,9 @@ export type ChannelConfigField = {
placeholder?: string;
secret?: boolean;
optional?: boolean;
help?: string;
inputType?: "text" | "number";
inputType?: "text" | "number" | "url" | "email" | "tel";
kind?: "string" | "secret" | "int" | "bool" | "list" | "enum" | string;
section?: string;
defaultValue?: string;
options?: ChannelConfigOption[];
};
@@ -0,0 +1,17 @@
import type { TFunction } from "i18next";
const messages: Record<string, string> = {
"Connection verified.": "connected",
"Configuration is present, but full verification was not possible.": "unverified",
"Required setup is missing.": "missing",
"Configuration was checked and looks invalid.": "invalid",
"This channel is not supported by the WebUI setup checker.": "unsupported",
"Configured.": "present",
"Required.": "required",
"This channel can be checked from saved fields, but not fully verified in-browser.": "manual",
};
export function channelValidationMessage(message: string, t: TFunction): string {
const key = messages[message];
return key ? t(`settings.channels.validationMessages.${key}`, { defaultValue: message }) : message;
}