Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(frontend): web IM channel configuration with test and hot toggle

shadowinlifeb859cbaf467b
diff --git a/frontend/src/components/settings/ChannelConfigPanel.tsx b/frontend/src/components/settings/ChannelConfigPanel.tsx
new file mode 100644
index 000000000..2a90262d9
--- /dev/null
+++ b/frontend/src/components/settings/ChannelConfigPanel.tsx
@@ -0,0 +1,620 @@
+import { useEffect, useId, useMemo, useState, type FormEvent, type KeyboardEvent } from "react";
+import {
+ CheckCircle2,
+ ChevronRight,
+ ExternalLink,
+ KeyRound,
+ Loader2,
+ PlugZap,
+ Save,
+ ShieldAlert,
+ X,
+ XCircle,
+} from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { toast } from "sonner";
+import {
+ ApiError,
+ api,
+ type ChannelConfigEntry,
+ type ChannelFieldHint,
+ type ChannelPutBody,
+ type ChannelTestResult,
+} from "@/lib/api";
+
+const fieldClass =
+ "w-full rounded-md border bg-background px-3 py-2 text-sm outline-none transition focus:border-primary focus:ring-2 focus:ring-primary/20 disabled:cursor-not-allowed disabled:opacity-60";
+const labelClass = "text-sm font-medium";
+const hintClass = "text-xs text-muted-foreground";
+// `errorFromResponse` collapses a structured `detail` object to its string
+// form, so the HTTP status is the reliable signal and probing for a `code` is
+// best-effort only.
+const OPAQUE_DETAIL = "[object Object]";
+
+type FormValue = string | boolean | string[];
+
+interface ApiFailure {
+ status: number | null;
+ code: string | null;
+ message: string;
+}
+
+/** Read a failed request into status/code/message without trusting its shape. */
+function describeApiFailure(error: unknown): ApiFailure {
+ const status = error instanceof ApiError ? error.status : null;
+ const rawMessage = error instanceof Error ? error.message : "";
+ const message = rawMessage === OPAQUE_DETAIL ? "" : rawMessage;
+ let code: string | null = null;
+ if (error && typeof error === "object") {
+ const carrier = error as { code?: unknown; detail?: unknown };
+ if (typeof carrier.code === "string") {
+ code = carrier.code;
+ } else if (carrier.detail && typeof carrier.detail === "object" && "code" in carrier.detail) {
+ const detailCode = (carrier.detail as { code?: unknown }).code;
+ if (typeof detailCode === "string") code = detailCode;
+ }
+ }
+ return { status, code, message };
+}
+
+/** Normalize one stored value into the shape its widget edits. */
+function fieldValue(field: ChannelFieldHint, values: Record<string, unknown>): FormValue {
+ const raw = values[field.key];
+ if (field.type === "bool") return Boolean(raw);
+ if (field.type === "list") return Array.isArray(raw) ? raw.map(String) : [];
+ return raw === null || raw === undefined ? "" : String(raw);
+}
+
+function initialFormValues(entry: ChannelConfigEntry): Record<string, FormValue> {
+ const next: Record<string, FormValue> = {};
+ for (const field of entry.fields) {
+ if (field.secret) continue;
+ next[field.key] = fieldValue(field, entry.values);
+ }
+ return next;
+}
+
+export interface ChannelConfigPanelProps {
+ name: string;
+ entry: ChannelConfigEntry;
+ writable: boolean;
+ configPath?: string;
+ /** Called after a successful PUT so the parent can refresh status + config. */
+ onChanged: () => void | Promise<void>;
+}
+
+/**
+ * Generic channel configuration form driven by the backend's `fields`
+ * metadata: text, password (masked secrets), bool and list (tag) widgets.
+ *
+ * Secrets are accepted but never rendered — a stored secret is only ever
+ * shown as its masked placeholder, and typing replaces it while leaving the
+ * field empty keeps the stored value.
+ */
+export function ChannelConfigPanel({
+ name,
+ entry,
+ writable,
+ configPath,
+ onChanged,
+}: ChannelConfigPanelProps) {
+ const { t } = useTranslation();
+ const idPrefix = useId();
+ const [values, setValues] = useState<Record<string, FormValue>>(() => initialFormValues(entry));
+ const [secretDrafts, setSecretDrafts] = useState<Record<string, string>>({});
+ const [clears, setClears] = useState<Record<string, boolean>>({});
+ const [listDrafts, setListDrafts] = useState<Record<string, string>>({});
+ const [guideOpen, setGuideOpen] = useState(false);
+ const [testing, setTesting] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const [toggling, setToggling] = useState(false);
+ const [testResult, setTestResult] = useState<ChannelTestResult | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [errorDetail, setErrorDetail] = useState<string | null>(null);
+ const [enableAnyway, setEnableAnyway] = useState(false);
+
+ useEffect(() => {
+ // A freshly fetched entry re-seeds non-secret fields (typed secret drafts
+ // survive a refresh until they are saved or cleared).
+ setValues(initialFormValues(entry));
+ setTestResult(null);
+ setError(null);
+ setErrorDetail(null);
+ setEnableAnyway(false);
+ }, [entry]);
+
+ const enabled = Boolean(entry.values.enabled);
+ const busy = saving || toggling || testing;
+ const formDisabled = !writable || saving || testing;
+
+ // Literal i18n calls per known backend help_key (typed i18n rejects
+ // interpolated keys); the raw config key is the fallback label for any
+ // channel metadata this build does not know yet.
+ const fieldText = useMemo<Record<string, { label: string; help: string }>>(
+ () => ({
+ "settings.channels.fields.dingtalk.client_id": { label: t("settings.channels.fields.dingtalk.client_id.label"), help: t("settings.channels.fields.dingtalk.client_id.help") },
+ "settings.channels.fields.dingtalk.client_secret": { label: t("settings.channels.fields.dingtalk.client_secret.label"), help: t("settings.channels.fields.dingtalk.client_secret.help") },
+ "settings.channels.fields.dingtalk.allow_from": { label: t("settings.channels.fields.dingtalk.allow_from.label"), help: t("settings.channels.fields.dingtalk.allow_from.help") },
+ "settings.channels.fields.dingtalk.allow_remote_media_redirects": { label: t("settings.channels.fields.dingtalk.allow_remote_media_redirects.label"), help: t("settings.channels.fields.dingtalk.allow_remote_media_redirects.help") },
+ "settings.channels.fields.dingtalk.remote_media_redirect_allowed_hosts": { label: t("settings.channels.fields.dingtalk.remote_media_redirect_allowed_hosts.label"), help: t("settings.channels.fields.dingtalk.remote_media_redirect_allowed_hosts.help") },
+ "settings.channels.fields.dingtalk.group_user_isolation": { label: t("settings.channels.fields.dingtalk.group_user_isolation.label"), help: t("settings.channels.fields.dingtalk.group_user_isolation.help") },
+ "settings.channels.fields.dingtalk.force_ipv4": { label: t("settings.channels.fields.dingtalk.force_ipv4.label"), help: t("settings.channels.fields.dingtalk.force_ipv4.help") },
+ }),
+ [t],
+ );
+
+ const testCodeText = useMemo<Record<ChannelTestResult["code"], string>>(
+ () => ({
+ ok: t("settings.channels.config.testCodeOk"),
+ invalid_credentials: t("settings.channels.config.testCodeInvalidCredentials"),
+ network: t("settings.channels.config.testCodeNetwork"),
+ unsupported: t("settings.channels.config.testCodeUnsupported"),
+ }),
+ [t],
+ );
+
+ const guide = useMemo(() => {
+ if (name !== "dingtalk") return null;
+ return {
+ title: t("settings.channels.guides.dingtalk.title"),
+ intro: t("settings.channels.guides.dingtalk.intro"),
+ steps: [
+ t("settings.channels.guides.dingtalk.step1"),
+ t("settings.channels.guides.dingtalk.step2"),
+ t("settings.channels.guides.dingtalk.step3"),
+ t("settings.channels.guides.dingtalk.step4"),
+ t("settings.channels.guides.dingtalk.step5"),
+ ],
+ docsUrl: "https://open-dev.dingtalk.com/",
+ docsLabel: t("settings.channels.guides.dingtalk.docsLabel"),
+ };
+ }, [name, t]);
+
+ const setValue = (key: string, value: FormValue) => {
+ setValues((current) => ({ ...current, [key]: value }));
+ };
+
+ const commitListDraft = (key: string) => {
+ const parts = (listDrafts[key] ?? "").split(",").map((part) => part.trim()).filter(Boolean);
+ if (!parts.length) return;
+ setValues((current) => {
+ const existing = Array.isArray(current[key]) ? (current[key] as string[]) : [];
+ const merged = [...existing];
+ for (const part of parts) if (!merged.includes(part)) merged.push(part);
+ return { ...current, [key]: merged };
+ });
+ setListDrafts((current) => ({ ...current, [key]: "" }));
+ };
+
+ const removeListValue = (key: string, value: string) => {
+ setValues((current) => {
+ const existing = Array.isArray(current[key]) ? (current[key] as string[]) : [];
+ return { ...current, [key]: existing.filter((item) => item !== value) };
+ });
+ };
+
+ const onListKeyDown = (event: KeyboardEvent<HTMLInputElement>, key: string) => {
+ if (event.key !== "Enter" && event.key !== ",") return;
+ event.preventDefault();
+ commitListDraft(key);
+ };
+
+ /** Non-secret fields always carry their current value; secret fields only a typed replacement. */
+ const buildPatch = (): Record<string, unknown> => {
+ const patch: Record<string, unknown> = {};
+ for (const field of entry.fields) {
+ if (field.secret) {
+ const draft = (secretDrafts[field.key] ?? "").trim();
+ if (draft) patch[field.key] = draft;
+ continue;
+ }
+ const value = values[field.key];
+ if (field.type === "list") patch[field.key] = Array.isArray(value) ? value : [];
+ else if (field.type === "bool") patch[field.key] = Boolean(value);
+ else patch[field.key] = typeof value === "string" ? value : "";
+ }
+ return patch;
+ };
+
+ const isDirty = useMemo(() => {
+ const secretDraft = entry.fields.some(
+ (field) => field.secret && (secretDrafts[field.key] ?? "").trim() !== "",
+ );
+ const clearPending = entry.fields.some((field) => clears[field.key]);
+ const changed = entry.fields.some((field) => {
+ if (field.secret) return false;
+ const current = values[field.key];
+ const original = fieldValue(field, entry.values);
+ return JSON.stringify(current) !== JSON.stringify(original);
+ });
+ return secretDraft || clearPending || changed;
+ }, [clears, entry, secretDrafts, values]);
+
+ const showError = (message: string, detail?: string | null) => {
+ setError(message);
+ setErrorDetail(detail || null);
+ };
+
+ const submit = async (event: FormEvent) => {
+ event.preventDefault();
+ setSaving(true);
+ setError(null);
+ setErrorDetail(null);
+ setEnableAnyway(false);
+ const body: ChannelPutBody = { config: buildPatch() };
+ for (const field of entry.fields) {
+ if (field.secret && clears[field.key]) body[`clear_${field.key}`] = true;
+ }
+ try {
+ await api.putChannelConfig(name, body);
+ setSecretDrafts({});
+ setClears({});
+ toast.success(t("settings.channels.config.saved"));
+ await onChanged();
+ } catch (saveError) {
+ const failure = describeApiFailure(saveError);
+ const message = failure.code === "config_not_writable" || failure.status === 400
+ ? t("settings.channels.config.notWritable", { path: configPath ?? "" })
+ : t("settings.channels.config.saveFailed", {
+ message: failure.message || t("settings.unknownError"),
+ });
+ showError(message);
+ toast.error(message);
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const runTest = async () => {
+ if (!entry.supports_test) return;
+ setTesting(true);
+ setError(null);
+ setErrorDetail(null);
+ setTestResult(null);
+ try {
+ // Pristine forms exercise the saved config (empty body); a dirty form
+ // tests exactly what is on screen, including a typed-but-unsaved secret.
+ const result = await api.testChannel(
+ name,
+ isDirty ? { config: buildPatch() } : undefined,
+ );
+ setTestResult(result);
+ if (result.ok) toast.success(t("settings.channels.config.testOk"));
+ else toast.error(testCodeText[result.code]);
+ } catch (testError) {
+ const failure = describeApiFailure(testError);
+ showError(t("settings.channels.config.testFailed", {
+ message: failure.message || t("settings.unknownError"),
+ }));
+ } finally {
+ setTesting(false);
+ }
+ };
+
+ const setEnabled = async (next: boolean, options?: { skipVerify?: boolean }) => {
+ setToggling(true);
+ setError(null);
+ setErrorDetail(null);
+ setEnableAnyway(false);
+ try {
+ await api.putChannelConfig(name, {
+ config: { enabled: next },
+ skip_verify: options?.skipVerify,
+ });
+ toast.success(
+ next
+ ? t("settings.channels.config.enabledToast")
+ : t("settings.channels.config.disabledToast"),
+ );
+ await onChanged();
+ } catch (toggleError) {
+ const failure = describeApiFailure(toggleError);
+ if (next && failure.status === 422) {
+ // Credential verification blocked the enable transition; the user can
+ // override with skip_verify after seeing the honest failure.
+ showError(t("settings.channels.config.enableRejected"), failure.message);
+ setEnableAnyway(true);
+ } else if (failure.code === "config_not_writable" || failure.status === 400) {
+ showError(t("settings.channels.config.notWritable", { path: configPath ?? "" }));
+ } else {
+ const message = next
+ ? t("settings.channels.config.enableFailed", {
+ message: failure.message || t("settings.unknownError"),
+ })
+ : t("settings.channels.config.disableFailed", {
+ message: failure.message || t("settings.unknownError"),
+ });
+ showError(message);
+ toast.error(message);
+ }
+ } finally {
+ setToggling(false);
+ }
+ };
+
+ const renderField = (field: ChannelFieldHint) => {
+ const text = fieldText[field.help_key ?? ""] ?? {
+ label: field.key.split("_").join(" "),
+ help: "",
+ };
+ const inputId = `${idPrefix}-${field.key}`;
+ const disabled = formDisabled || Boolean(field.secret && clears[field.key]);
+
+ if (field.type === "bool") {
+ return (
+ <div key={field.key} className="grid gap-2">
+ <label className="flex items-center justify-between gap-3 rounded-md border bg-muted/20 px-3 py-2">
+ <span className={labelClass}>{text.label}</span>
+ <input
+ id={inputId}
+ type="checkbox"
+ checked={Boolean(values[field.key])}
+ onChange={(event) => setValue(field.key, event.target.checked)}
+ className="h-4 w-4 accent-primary"
+ disabled={formDisabled}
+ />
+ </label>
+ {text.help ? <span className={hintClass}>{text.help}</span> : null}
+ </div>
+ );
+ }
+
+ if (field.type === "list") {
+ const items = Array.isArray(values[field.key]) ? (values[field.key] as string[]) : [];
+ return (
+ <div key={field.key} className="grid gap-2">
+ <label className={labelClass} htmlFor={inputId}>{text.label}</label>
+ <div className={`${fieldClass} flex min-h-10 flex-wrap items-center gap-1.5`}>
+ {items.map((item) => (
+ <span
+ key={item}
+ className="inline-flex items-center gap-1 rounded-full bg-muted px-2 py-0.5 text-xs"
+ >
+ {item}
+ <button
+ type="button"
+ onClick={() => removeListValue(field.key, item)}
+ disabled={formDisabled}
+ aria-label={t("settings.channels.config.removeValue", { value: item })}
+ className="rounded-full text-muted-foreground transition hover:text-foreground disabled:opacity-50"
+ >
+ <X className="h-3 w-3" />
+ </button>
+ </span>
+ ))}
+ <input
+ id={inputId}
+ value={listDrafts[field.key] ?? ""}
+ onChange={(event) => setListDrafts((current) => ({ ...current, [field.key]: event.target.value }))}
+ onKeyDown={(event) => onListKeyDown(event, field.key)}
+ onBlur={() => commitListDraft(field.key)}
+ className="min-w-24 flex-1 bg-transparent text-sm outline-none"
+ placeholder={items.length ? "" : t("settings.channels.config.listPlaceholder")}
+ disabled={formDisabled}
+ />
+ </div>
+ {text.help ? <span className={hintClass}>{text.help}</span> : null}
+ </div>
+ );
+ }
+
+ const secret = entry.secrets[field.key];
+ const placeholder = field.secret
+ ? secret?.set
+ ? t("settings.channels.config.keepCurrent", { masked: secret.masked })
+ : t("settings.channels.config.secretNotSet")
+ : "";
+ return (
+ <div key={field.key} className="grid gap-2">
+ <label className={labelClass} htmlFor={inputId}>
+ {text.label}
+ {field.required ? (
+ <span className="ms-1 text-destructive" aria-hidden="true">*</span>
+ ) : null}
+ </label>
+ <div className="relative">
+ {field.secret ? (
+ <KeyRound className="pointer-events-none absolute start-3 top-2.5 h-4 w-4 text-muted-foreground" />
+ ) : null}
+ <input
+ id={inputId}
+ type={field.secret ? "password" : "text"}
+ value={field.secret ? (secretDrafts[field.key] ?? "") : (values[field.key] as string ?? "")}
+ onChange={(event) => {
+ if (field.secret) {
+ setSecretDrafts((current) => ({ ...current, [field.key]: event.target.value }));
+ } else {
+ setValue(field.key, event.target.value);
+ }
+ }}
+ className={`${fieldClass}${field.secret ? " ps-9" : ""}`}
+ placeholder={placeholder}
+ autoComplete={field.secret ? "new-password" : "off"}
+ disabled={disabled}
+ />
+ </div>
+ <div className="flex items-start justify-between gap-3">
+ <span className={hintClass}>
+ {text.help}
+ {field.required ? ` ${t("settings.channels.config.required")}` : ""}
+ </span>
+ {field.secret && secret?.set ? (
+ <label className="flex shrink-0 items-center gap-2 text-xs text-muted-foreground">
+ <input
+ type="checkbox"
+ checked={Boolean(clears[field.key])}
+ onChange={(event) => {
+ const checked = event.target.checked;
+ setClears((current) => ({ ...current, [field.key]: checked }));
+ if (checked) setSecretDrafts((current) => ({ ...current, [field.key]: "" }));
+ }}
+ className="h-3.5 w-3.5 accent-primary"
+ disabled={formDisabled}
+ />
+ {t("settings.channels.config.clearSecret")}
+ </label>
+ ) : null}
+ </div>
+ </div>
+ );
+ };
+
+ return (
+ <div className="grid gap-4">
+ {!writable ? (
+ <div className="rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-sm text-warning-foreground">
+ {t("settings.channels.config.notWritable", { path: configPath ?? "" })}
+ </div>
+ ) : null}
+
+ {!entry.sdk_available ? (
+ <div className="inline-flex w-fit items-center gap-2 rounded-full bg-warning/10 px-2.5 py-1 text-xs text-warning-foreground">
+ <ShieldAlert className="h-3.5 w-3.5" />
+ {entry.install_hint
+ ? t("settings.channels.config.sdkMissing", { hint: entry.install_hint })
+ : t("settings.channels.config.sdkMissingNoHint")}
+ </div>
+ ) : null}
+
+ <div className="flex flex-wrap items-center justify-between gap-3 rounded-md border bg-muted/20 px-3 py-2">
+ <div>
+ <div className={labelClass}>{t("settings.channels.config.enable")}</div>
+ <div className={hintClass}>{t("settings.channels.config.enableHint")}</div>
+ </div>
+ <div className="flex items-center gap-2">
+ <span className={`rounded-full px-2 py-0.5 text-xs ${enabled ? "bg-success/10 text-success" : "bg-muted text-muted-foreground"}`}>
+ {enabled ? t("settings.channels.enabled") : t("settings.channels.disabled")}
+ </span>
+ {toggling ? <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" /> : null}
+ <input
+ type="checkbox"
+ checked={enabled}
+ onChange={(event) => void setEnabled(event.target.checked)}
+ className="h-4 w-4 accent-primary"
+ aria-label={t("settings.channels.config.enable")}
+ disabled={!writable || toggling}
+ />
+ </div>
+ </div>
+
+ {enableAnyway ? (
+ <div className="flex flex-wrap items-center gap-3 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive">
+ <span className="min-w-0 flex-1">{error}</span>
+ <button
+ type="button"
+ onClick={() => void setEnabled(true, { skipVerify: true })}
+ disabled={toggling}
+ className="inline-flex shrink-0 items-center gap-2 rounded-md border border-destructive/40 px-3 py-1.5 text-sm transition hover:bg-destructive/10 disabled:cursor-not-allowed disabled:opacity-60"
+ >
+ {t("settings.channels.config.enableAnyway")}
+ </button>
+ {errorDetail ? (
+ <span className="w-full text-xs">
+ {t("settings.channels.config.enableRejectedDetail", { detail: errorDetail })}
+ </span>
+ ) : null}
+ <span className="w-full text-xs">{t("settings.channels.config.enableAnywayHint")}</span>
+ </div>
+ ) : error ? (
+ <div className="rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive">
+ <div>{error}</div>
+ {errorDetail ? (
+ <div className="mt-1 text-xs">
+ {t("settings.channels.config.enableRejectedDetail", { detail: errorDetail })}
+ </div>
+ ) : null}
+ </div>
+ ) : null}
+
+ <form onSubmit={submit} className="grid gap-4">
+ {entry.fields.length ? (
+ entry.fields.map(renderField)
+ ) : (
+ <p className="text-sm text-muted-foreground">
+ {t("settings.channels.config.noFields")}
+ </p>
+ )}
+
+ <div className="flex flex-wrap items-center gap-3">
+ <button
+ type="button"
+ onClick={() => void runTest()}
+ disabled={!entry.supports_test || busy}
+ className="inline-flex items-center justify-center gap-2 rounded-md border px-4 py-2 text-sm text-muted-foreground transition hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-60"
+ >
+ {testing ? <Loader2 className="h-4 w-4 animate-spin" /> : <PlugZap className="h-4 w-4" />}
+ {testing ? t("settings.channels.config.testing") : t("settings.channels.config.test")}
+ </button>
+ <button
+ type="submit"
+ disabled={formDisabled}
+ className="inline-flex items-center justify-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-70"
+ >
+ {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
+ {saving ? t("settings.saving") : t("settings.channels.config.save")}
+ </button>
+ <span className={hintClass}>{t("settings.channels.config.hotApply")}</span>
+ </div>
+ </form>
+
+ {testResult ? (
+ <div
+ role="status"
+ className={`rounded-md border px-3 py-2 text-sm ${
+ testResult.ok
+ ? "border-success/30 bg-success/5 text-success"
+ : "border-warning/40 bg-warning/10 text-warning-foreground"
+ }`}
+ >
+ <div className="flex items-center gap-2">
+ {testResult.ok
+ ? <CheckCircle2 className="h-4 w-4 shrink-0" />
+ : <XCircle className="h-4 w-4 shrink-0" />}
+ <span className="font-medium">{testCodeText[testResult.code]}</span>
+ </div>
+ {testResult.detail ? (
+ <div className="mt-1 text-xs">{testResult.detail}</div>
+ ) : null}
+ <div className="mt-1 text-xs">
+ {testResult.tested_saved_config
+ ? t("settings.channels.config.testedSavedConfig")
+ : t("settings.channels.config.testedDraftConfig")}
+ </div>
+ </div>
+ ) : null}
+
+ {guide ? (
+ <div className="rounded-md border">
+ <button
+ type="button"
+ onClick={() => setGuideOpen((current) => !current)}
+ aria-expanded={guideOpen}
+ className="flex w-full items-center gap-2 px-3 py-2 text-sm font-medium"
+ >
+ <ChevronRight
+ className={`h-4 w-4 text-muted-foreground transition-transform ${guideOpen ? "rotate-90" : ""}`}
+ />
+ {guide.title}
+ </button>
+ {guideOpen ? (
+ <div className="border-t px-3 py-3">
+ <p className={hintClass}>{guide.intro}</p>
+ <ol className="mt-2 grid list-decimal gap-1.5 ps-5 text-sm">
+ {guide.steps.map((step) => <li key={step}>{step}</li>)}
+ </ol>
+ <a
+ href={guide.docsUrl}
+ target="_blank"
+ rel="noreferrer"
+ className="mt-3 inline-flex items-center gap-1.5 text-xs text-primary transition hover:underline"
+ >
+ <ExternalLink className="h-3.5 w-3.5" />
+ {guide.docsLabel}
+ </a>
+ </div>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ );
+}
\ No newline at end of file
diff --git a/frontend/src/components/settings/ChannelSettings.tsx b/frontend/src/components/settings/ChannelSettings.tsx
new file mode 100644
index 000000000..c31d07bb3
--- /dev/null
+++ b/frontend/src/components/settings/ChannelSettings.tsx
@@ -0,0 +1,315 @@
+import { Fragment, useCallback, useEffect, useMemo, useState } from "react";
+import {
+ ChevronRight,
+ Loader2,
+ MessageSquareMore,
+ Play,
+ RefreshCw,
+ Square,
+} from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { toast } from "sonner";
+import { ChannelConfigPanel } from "@/components/settings/ChannelConfigPanel";
+import {
+ api,
+ type ChannelsConfigResponse,
+ type ChannelRuntimeStatus,
+} from "@/lib/api";
+
+/**
+ * IM channel card: runtime status table with Start/Stop/Refresh, and one
+ * expandable configuration panel per channel (credentials, connection test,
+ * non-destructive enable toggle) backed by GET /channels/config.
+ */
+export function ChannelSettings() {
+ const { t } = useTranslation();
+ const [channelStatus, setChannelStatus] = useState<ChannelRuntimeStatus | null>(null);
+ const [channelsConfig, setChannelsConfig] = useState<ChannelsConfigResponse | null>(null);
+ const [configFailed, setConfigFailed] = useState(false);
+ const [expanded, setExpanded] = useState<Record<string, boolean>>({});
+ const [loading, setLoading] = useState(true);
+ const [channelRefreshing, setChannelRefreshing] = useState(false);
+ const [channelAction, setChannelAction] = useState<"start" | "stop" | null>(null);
+
+ useEffect(() => {
+ let alive = true;
+
+ Promise.allSettled([api.getChannelStatus(), api.getChannelsConfig()])
+ .then(([statusResult, configResult]) => {
+ if (!alive) return;
+ if (statusResult.status === "fulfilled") {
+ setChannelStatus(statusResult.value);
+ } else {
+ const message = statusResult.reason instanceof Error
+ ? statusResult.reason.message
+ : t("settings.unknownError", { defaultValue: "Unknown error" });
+ toast.error(`${t("settings.channels.refreshFailed")}: ${message}`);
+ setChannelStatus(null);
+ }
+ if (configResult.status === "fulfilled") {
+ setChannelsConfig(configResult.value);
+ setConfigFailed(false);
+ } else {
+ setChannelsConfig(null);
+ setConfigFailed(true);
+ }
+ })
+ .finally(() => {
+ if (alive) setLoading(false);
+ });
+
+ return () => {
+ alive = false;
+ };
+ }, [t]);
+
+ const reloadConfig = useCallback(async () => {
+ try {
+ setChannelsConfig(await api.getChannelsConfig());
+ setConfigFailed(false);
+ } catch {
+ setChannelsConfig(null);
+ setConfigFailed(true);
+ }
+ }, []);
+
+ /** Re-read runtime status + config after a panel save/toggle (hot-applied). */
+ const refreshAfterChange = useCallback(async () => {
+ const [statusResult, configResult] = await Promise.allSettled([
+ api.getChannelStatus(),
+ api.getChannelsConfig(),
+ ]);
+ if (statusResult.status === "fulfilled") setChannelStatus(statusResult.value);
+ if (configResult.status === "fulfilled") {
+ setChannelsConfig(configResult.value);
+ setConfigFailed(false);
+ } else {
+ setConfigFailed(true);
+ }
+ }, []);
+
+ const refreshChannelStatus = async () => {
+ setChannelRefreshing(true);
+ try {
+ const [statusResult] = await Promise.allSettled([
+ api.getChannelStatus(),
+ reloadConfig(),
+ ]);
+ if (statusResult.status === "fulfilled") {
+ setChannelStatus(statusResult.value);
+ } else {
+ throw statusResult.reason;
+ }
+ } catch (error) {
+ toast.error(`${t("settings.channels.refreshFailed")}: ${error instanceof Error ? error.message : t("settings.unknownError", { defaultValue: "Unknown error" })}`);
+ } finally {
+ setChannelRefreshing(false);
+ }
+ };
+
+ const setChannelsRunning = async (action: "start" | "stop") => {
+ setChannelAction(action);
+ try {
+ const updated = action === "start" ? await api.startChannels() : await api.stopChannels();
+ setChannelStatus(updated);
+ toast.success(action === "start" ? t("settings.channels.started") : t("settings.channels.stoppedToast"));
+ } catch (error) {
+ toast.error(`${action === "start" ? t("settings.channels.startFailed") : t("settings.channels.stopFailed")}: ${error instanceof Error ? error.message : t("settings.unknownError", { defaultValue: "Unknown error" })}`);
+ } finally {
+ setChannelAction(null);
+ }
+ };
+
+ const rows = useMemo(() => {
+ const statusChannels = channelStatus?.channels ?? {};
+ const configChannels = channelsConfig?.channels ?? {};
+ const names = Array.from(new Set([
+ ...Object.keys(statusChannels),
+ ...Object.keys(configChannels),
+ ])).sort((a, b) => a.localeCompare(b));
+ return names.map((name) => ({
+ name,
+ status: statusChannels[name],
+ entry: configChannels[name],
+ }));
+ }, [channelStatus, channelsConfig]);
+
+ const statusChannels = Object.values(channelStatus?.channels ?? {});
+ const channelEnabledCount = statusChannels.filter((item) => item.enabled).length;
+ const channelLoadedCount = statusChannels.filter((item) => item.loaded).length;
+ const channelUnavailableCount = statusChannels.filter((item) => item.available === false).length;
+ const channelBusy = channelRefreshing || channelAction !== null;
+ const writable = channelsConfig?.writable ?? false;
+
+ const toggleExpanded = (name: string) => {
+ setExpanded((current) => ({ ...current, [name]: !current[name] }));
+ };
+
+ return (
+ <section className="rounded-lg border bg-card p-5 shadow-sm">
+ <div className="mb-5 flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
+ <div className="space-y-1">
+ <div className="flex items-center gap-2">
+ <MessageSquareMore className="h-4 w-4 text-primary" />
+ <h2 className="text-base font-semibold">{t("settings.channels.title")}</h2>
+ {channelsConfig && !channelsConfig.writable ? (
+ <span className="rounded-full bg-warning/10 px-2 py-0.5 text-xs text-warning-foreground">
+ {t("settings.channels.config.notWritableChip")}
+ </span>
+ ) : null}
+ {configFailed ? (
+ <span className="rounded-full bg-warning/10 px-2 py-0.5 text-xs text-warning-foreground">
+ {t("settings.channels.config.loadFailed")}
+ </span>
+ ) : null}
+ </div>
+ <p className="max-w-3xl text-sm text-muted-foreground">{t("settings.channels.description")}</p>
+ </div>
+ <div className="flex flex-wrap gap-2">
+ <button
+ type="button"
+ onClick={() => void refreshChannelStatus()}
+ disabled={channelBusy}
+ className="inline-flex items-center justify-center gap-2 rounded-md border px-3 py-2 text-sm text-muted-foreground transition hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-60"
+ >
+ {channelRefreshing ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
+ {t("settings.channels.refresh")}
+ </button>
+ <button
+ type="button"
+ onClick={() => void setChannelsRunning("start")}
+ disabled={channelBusy || !channelStatus}
+ className="inline-flex items-center justify-center gap-2 rounded-md bg-primary px-3 py-2 text-sm font-medium text-primary-foreground transition hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-60"
+ >
+ {channelAction === "start" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}
+ {t("settings.channels.start")}
+ </button>
+ <button
+ type="button"
+ onClick={() => void setChannelsRunning("stop")}
+ disabled={channelBusy || !channelStatus}
+ className="inline-flex items-center justify-center gap-2 rounded-md border px-3 py-2 text-sm text-muted-foreground transition hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-60"
+ >
+ {channelAction === "stop" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Square className="h-4 w-4" />}
+ {t("settings.channels.stop")}
+ </button>
+ </div>
+ </div>
+
+ {loading ? (
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ {t("settings.loading")}
+ </div>
+ ) : channelStatus ? (
+ <>
+ <div className="mb-4 grid gap-3 md:grid-cols-4">
+ <div className="rounded-md border bg-muted/20 px-3 py-2">
+ <div className="text-xs text-muted-foreground">{t("settings.channels.runtime")}</div>
+ <div className="text-sm font-medium">{channelStatus.running ? t("settings.channels.running") : t("settings.channels.stopped")}</div>
+ </div>
+ <div className="rounded-md border bg-muted/20 px-3 py-2">
+ <div className="text-xs text-muted-foreground">{t("settings.channels.enabled")}</div>
+ <div className="text-sm font-medium">{channelEnabledCount}</div>
+ </div>
+ <div className="rounded-md border bg-muted/20 px-3 py-2">
+ <div className="text-xs text-muted-foreground">{t("settings.channels.loaded")}</div>
+ <div className="text-sm font-medium">{channelLoadedCount}</div>
+ </div>
+ <div className="rounded-md border bg-muted/20 px-3 py-2">
+ <div className="text-xs text-muted-foreground">{t("settings.channels.unavailable")}</div>
+ <div className="text-sm font-medium">{channelUnavailableCount}</div>
+ </div>
+ </div>
+
+ <div className="overflow-hidden rounded-md border">
+ <table className="w-full text-sm">
+ <thead className="bg-muted/40 text-xs text-muted-foreground">
+ <tr>
+ <th className="px-3 py-2 text-start font-medium">{t("settings.channels.channel")}</th>
+ <th className="px-3 py-2 text-start font-medium">{t("settings.channels.state")}</th>
+ <th className="px-3 py-2 text-start font-medium">{t("settings.channels.recovery")}</th>
+ </tr>
+ </thead>
+ <tbody>
+ {rows.map(({ name, status: item, entry }) => {
+ const displayName = item?.display_name || entry?.display_name || name;
+ const isExpanded = Boolean(expanded[name]);
+ const enabled = item?.enabled ?? Boolean(entry?.values.enabled);
+ const loaded = item?.loaded ?? entry?.loaded ?? false;
+ const running = item?.running ?? false;
+ const recovery =
+ item?.install_hint || item?.error
+ || entry?.install_hint || entry?.error
+ || t("settings.channels.noRecovery");
+ return (
+ <Fragment key={name}>
+ <tr className="border-t">
+ <td className="px-3 py-2 align-top">
+ <button
+ type="button"
+ onClick={() => toggleExpanded(name)}
+ aria-expanded={isExpanded}
+ aria-label={t("settings.channels.config.toggleConfig", { name: displayName })}
+ className="flex items-start gap-2 text-start"
+ >
+ <ChevronRight
+ className={`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground transition-transform ${isExpanded ? "rotate-90" : ""}`}
+ />
+ <span>
+ <span className="block font-medium">{displayName}</span>
+ <span className="block text-xs text-muted-foreground">{name}</span>
+ </span>
+ </button>
+ </td>
+ <td className="px-3 py-2 align-top">
+ <div className="flex flex-wrap gap-1.5">
+ <span className={`rounded-full px-2 py-0.5 text-xs ${enabled ? "bg-primary/10 text-primary" : "bg-muted text-muted-foreground"}`}>
+ {enabled ? t("settings.channels.enabled") : t("settings.channels.disabled")}
+ </span>
+ <span className={`rounded-full px-2 py-0.5 text-xs ${loaded ? "bg-success/10 text-success" : "bg-muted text-muted-foreground"}`}>
+ {loaded ? t("settings.channels.loaded") : t("settings.channels.notLoaded")}
+ </span>
+ <span className={`rounded-full px-2 py-0.5 text-xs ${running ? "bg-success/10 text-success" : "bg-muted text-muted-foreground"}`}>
+ {running ? t("settings.channels.running") : t("settings.channels.stopped")}
+ </span>
+ </div>
+ </td>
+ <td className="max-w-md px-3 py-2 align-top text-xs text-muted-foreground">
+ {recovery}
+ </td>
+ </tr>
+ {isExpanded ? (
+ <tr className="border-t bg-muted/10">
+ <td colSpan={3} className="px-3 py-4">
+ {entry ? (
+ <ChannelConfigPanel
+ name={name}
+ entry={entry}
+ writable={writable}
+ configPath={channelsConfig?.config_path}
+ onChanged={refreshAfterChange}
+ />
+ ) : (
+ <p className="text-sm text-muted-foreground">
+ {t("settings.channels.config.loadFailed")}
+ </p>
+ )}
+ </td>
+ </tr>
+ ) : null}
+ </Fragment>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+ </>
+ ) : (
+ <div className="rounded-md border bg-muted/20 px-4 py-6 text-center text-sm text-muted-foreground">
+ {t("settings.channels.refreshFailed")}
+ </div>
+ )}
+ </section>
+ );
+}
\ No newline at end of file
diff --git a/frontend/src/components/settings/__tests__/ChannelSettings.test.tsx b/frontend/src/components/settings/__tests__/ChannelSettings.test.tsx
new file mode 100644
index 000000000..a87fd888b
--- /dev/null
+++ b/frontend/src/components/settings/__tests__/ChannelSettings.test.tsx
@@ -0,0 +1,336 @@
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import i18n from "@/i18n";
+import { ApiError } from "@/lib/api";
+import { ChannelSettings } from "@/components/settings/ChannelSettings";
+import { toast } from "sonner";
+
+const apiMock = vi.hoisted(() => ({
+ getChannelStatus: vi.fn(),
+ getChannelsConfig: vi.fn(),
+ startChannels: vi.fn(),
+ stopChannels: vi.fn(),
+ putChannelConfig: vi.fn(),
+ testChannel: vi.fn(),
+}));
+
+vi.mock("@/lib/api", async () => {
+ const actual = await vi.importActual<typeof import("@/lib/api")>("@/lib/api");
+ return {
+ ...actual,
+ api: apiMock,
+ };
+});
+
+vi.mock("sonner", () => ({
+ toast: {
+ success: vi.fn(),
+ info: vi.fn(),
+ error: vi.fn(),
+ },
+}));
+
+function channelStatus(overrides = {}) {
+ return {
+ running: false,
+ inbound_queue: 0,
+ outbound_queue: 0,
+ session_count: 0,
+ channels: {
+ dingtalk: {
+ name: "dingtalk",
+ display_name: "DingTalk",
+ configured: true,
+ enabled: false,
+ available: true,
+ loaded: true,
+ running: false,
+ error: "",
+ install_hint: "",
+ },
+ },
+ ...overrides,
+ };
+}
+
+function dingtalkEntry(overrides: Record<string, unknown> = {}) {
+ return {
+ display_name: "DingTalk",
+ available: true,
+ loaded: true,
+ install_hint: "",
+ error: "",
+ supports_test: true,
+ sdk_available: true,
+ fields: [
+ { key: "client_id", type: "text", secret: false, required: true, help_key: "settings.channels.fields.dingtalk.client_id" },
+ { key: "client_secret", type: "password", secret: true, required: true, help_key: "settings.channels.fields.dingtalk.client_secret" },
+ { key: "allow_from", type: "list", secret: false, required: false, help_key: "settings.channels.fields.dingtalk.allow_from" },
+ { key: "group_user_isolation", type: "bool", secret: false, required: false, help_key: "settings.channels.fields.dingtalk.group_user_isolation" },
+ ],
+ values: {
+ enabled: false,
+ client_id: "ding_appkey",
+ allow_from: ["user-1"],
+ group_user_isolation: false,
+ },
+ secrets: { client_secret: { set: true, masked: "****abcd" } },
+ ...overrides,
+ };
+}
+
+function channelsConfig(overrides: Record<string, unknown> = {}) {
+ return {
+ config_path: "/home/user/.vibe-trading/agent.json",
+ writable: true,
+ runtime_running: false,
+ channels: { dingtalk: dingtalkEntry() },
+ ...overrides,
+ };
+}
+
+/** Render the card with the DingTalk config panel expanded. */
+async function renderExpanded() {
+ render(<ChannelSettings />);
+ await screen.findByText("IM Channels");
+ fireEvent.click(await screen.findByRole("button", { name: "Configure DingTalk" }));
+ expect(await screen.findByDisplayValue("ding_appkey")).toBeInTheDocument();
+}
+
+describe("ChannelSettings config panel", () => {
+ beforeEach(async () => {
+ await i18n.changeLanguage("en");
+ window.localStorage.clear();
+ apiMock.getChannelStatus.mockReset();
+ apiMock.getChannelsConfig.mockReset();
+ apiMock.putChannelConfig.mockReset();
+ apiMock.testChannel.mockReset();
+ vi.mocked(toast.success).mockClear();
+ vi.mocked(toast.error).mockClear();
+ apiMock.getChannelStatus.mockResolvedValue(channelStatus());
+ apiMock.getChannelsConfig.mockResolvedValue(channelsConfig());
+ apiMock.putChannelConfig.mockResolvedValue({
+ channel: dingtalkEntry({ values: { enabled: true, client_id: "ding_appkey" } }),
+ applied: "hot_swapped",
+ });
+ apiMock.testChannel.mockResolvedValue({
+ ok: true,
+ code: "ok",
+ sdk_available: true,
+ tested_saved_config: false,
+ });
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ it("renders the status row and reveals a generic form from the field metadata", async () => {
+ await renderExpanded();
+
+ expect(screen.getByText("DingTalk")).toBeInTheDocument();
+ expect(screen.getByText("Client ID (AppKey)")).toBeInTheDocument();
+ expect(screen.getByText("Client Secret (AppSecret)")).toBeInTheDocument();
+ expect(screen.getByText("Allowed senders")).toBeInTheDocument();
+ expect(screen.getByText("Per-user group sessions")).toBeInTheDocument();
+ // List values render as removable chips.
+ expect(screen.getByText("user-1")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Remove user-1" })).toBeInTheDocument();
+ // Hot-apply copy sits next to Save.
+ expect(screen.getByText("Saving applies immediately — no restart needed.")).toBeInTheDocument();
+ });
+
+ it("shows only the masked secret placeholder and never renders a secret value", async () => {
+ // A contract-violating response that smuggles the raw secret into `values`
+ // still must not reach the DOM: rendering is driven by `fields`, not by
+ // whatever keys `values` happens to carry.
+ apiMock.getChannelsConfig.mockResolvedValue(channelsConfig({
+ channels: {
+ dingtalk: dingtalkEntry({
+ values: {
+ enabled: false,
+ client_id: "ding_appkey",
+ allow_from: [],
+ group_user_isolation: false,
+ client_secret: "leaked-secret-value",
+ },
+ }),
+ },
+ }));
+ await renderExpanded();
+
+ const secretInput = screen.getByPlaceholderText("Keep current (****abcd)");
+ expect(secretInput).toHaveAttribute("type", "password");
+ expect(secretInput).toHaveValue("");
+ expect(document.body.textContent).not.toContain("leaked-secret-value");
+ expect(document.body.textContent).not.toContain("****abcd9");
+ });
+
+ it("tests the saved configuration with an empty body when the form is pristine", async () => {
+ apiMock.testChannel.mockResolvedValue({
+ ok: true,
+ code: "ok",
+ sdk_available: true,
+ tested_saved_config: true,
+ });
+ await renderExpanded();
+
+ fireEvent.click(screen.getByRole("button", { name: "Test connection" }));
+
+ await waitFor(() => expect(apiMock.testChannel).toHaveBeenCalledTimes(1));
+ expect(apiMock.testChannel).toHaveBeenCalledWith("dingtalk", undefined);
+ expect(await screen.findByText("Tested the saved configuration.")).toBeInTheDocument();
+ });
+
+ it("tests unsaved credentials straight from the form", async () => {
+ await renderExpanded();
+
+ fireEvent.change(screen.getByPlaceholderText("Keep current (****abcd)"), {
+ target: { value: "typed-secret" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Test connection" }));
+
+ await waitFor(() => expect(apiMock.testChannel).toHaveBeenCalledTimes(1));
+ const [name, body] = apiMock.testChannel.mock.calls[0] as [string, { config?: Record<string, unknown> }];
+ expect(name).toBe("dingtalk");
+ expect(body.config).toMatchObject({ client_secret: "typed-secret", client_id: "ding_appkey" });
+ // The typed secret must only travel in the request, never be echoed.
+ expect(document.body.textContent).not.toContain("typed-secret");
+ expect(await screen.findByText("Tested the values currently in the form (not saved yet).")).toBeInTheDocument();
+ });
+
+ it("enables the channel with a PUT and refreshes status + config", async () => {
+ await renderExpanded();
+ expect(apiMock.getChannelsConfig).toHaveBeenCalledTimes(1);
+
+ fireEvent.click(screen.getByRole("checkbox", { name: "Enable channel" }));
+
+ await waitFor(() => expect(apiMock.putChannelConfig).toHaveBeenCalledTimes(1));
+ expect(apiMock.putChannelConfig).toHaveBeenCalledWith("dingtalk", {
+ config: { enabled: true },
+ skip_verify: undefined,
+ });
+ await waitFor(() => expect(apiMock.getChannelsConfig).toHaveBeenCalledTimes(2));
+ expect(apiMock.getChannelStatus).toHaveBeenCalledTimes(2);
+ expect(toast.success).toHaveBeenCalledWith("Channel enabled");
+ });
+
+ it("offers Enable anyway when the enable transition is rejected with 422", async () => {
+ apiMock.putChannelConfig.mockRejectedValueOnce(new ApiError("invalid_credentials", 422));
+ await renderExpanded();
+
+ fireEvent.click(screen.getByRole("checkbox", { name: "Enable channel" }));
+
+ const anyway = await screen.findByRole("button", { name: "Enable anyway" });
+ expect(screen.getByText(
+ "The provider rejected these credentials, so the channel was not enabled.",
+ )).toBeInTheDocument();
+ expect(screen.getByText("Provider response: invalid_credentials")).toBeInTheDocument();
+
+ fireEvent.click(anyway);
+
+ await waitFor(() => expect(apiMock.putChannelConfig).toHaveBeenCalledTimes(2));
+ expect(apiMock.putChannelConfig).toHaveBeenLastCalledWith("dingtalk", {
+ config: { enabled: true },
+ skip_verify: true,
+ });
+ });
+
+ it("adds list values on Enter and removes them again", async () => {
+ apiMock.getChannelsConfig.mockResolvedValue(channelsConfig({
+ channels: {
+ dingtalk: dingtalkEntry({
+ values: { enabled: false, client_id: "ding_appkey", allow_from: [], group_user_isolation: false },
+ }),
+ },
+ }));
+ await renderExpanded();
+
+ const listInput = screen.getByPlaceholderText("Type a value and press Enter");
+ fireEvent.change(listInput, { target: { value: "user-2" } });
+ fireEvent.keyDown(listInput, { key: "Enter" });
+
+ expect(screen.getByText("user-2")).toBeInTheDocument();
+ expect(listInput).toHaveValue("");
+
+ fireEvent.click(screen.getByRole("button", { name: "Remove user-2" }));
+ expect(screen.queryByText("user-2")).not.toBeInTheDocument();
+ });
+
+ it("saves typed values and clears a stored secret with clear_<field>", async () => {
+ await renderExpanded();
+
+ fireEvent.change(screen.getByPlaceholderText("Keep current (****abcd)"), {
+ target: { value: "new-secret" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Save configuration" }));
+
+ await waitFor(() => expect(apiMock.putChannelConfig).toHaveBeenCalledTimes(1));
+ expect(apiMock.putChannelConfig).toHaveBeenLastCalledWith("dingtalk", {
+ config: {
+ client_id: "ding_appkey",
+ client_secret: "new-secret",
+ allow_from: ["user-1"],
+ group_user_isolation: false,
+ },
+ });
+ expect(toast.success).toHaveBeenCalledWith("Channel configuration saved");
+
+ // Clearing the stored secret sends the clear flag and no secret value.
+ fireEvent.click(screen.getByRole("checkbox", { name: "Clear" }));
+ fireEvent.click(screen.getByRole("button", { name: "Save configuration" }));
+
+ await waitFor(() => expect(apiMock.putChannelConfig).toHaveBeenCalledTimes(2));
+ const [, secondBody] = apiMock.putChannelConfig.mock.calls[1] as [string, Record<string, unknown>];
+ expect(secondBody.clear_client_secret).toBe(true);
+ expect((secondBody.config as Record<string, unknown>).client_secret).toBeUndefined();
+ });
+
+ it("disables every control and explains a non-writable YAML config", async () => {
+ apiMock.getChannelsConfig.mockResolvedValue(channelsConfig({ writable: false }));
+ await renderExpanded();
+
+ expect(screen.getByText(/stored in a YAML file/)).toBeInTheDocument();
+ expect(screen.getByDisplayValue("ding_appkey")).toBeDisabled();
+ expect(screen.getByPlaceholderText("Keep current (****abcd)")).toBeDisabled();
+ expect(screen.getByRole("checkbox", { name: "Enable channel" })).toBeDisabled();
+ expect(screen.getByRole("button", { name: "Save configuration" })).toBeDisabled();
+ });
+
+ it("surfaces the install hint when the runtime SDK is missing", async () => {
+ apiMock.getChannelsConfig.mockResolvedValue(channelsConfig({
+ channels: {
+ dingtalk: dingtalkEntry({
+ sdk_available: false,
+ install_hint: "pip install 'vibe-trading-ai[dingtalk]'",
+ }),
+ },
+ }));
+ await renderExpanded();
+
+ // The same hint also renders in the status row's recovery column.
+ expect(screen.getAllByText(/pip install 'vibe-trading-ai\[dingtalk\]'/).length).toBeGreaterThan(0);
+ });
+
+ it("toggles the DingTalk setup guide with its steps and external link", async () => {
+ await renderExpanded();
+
+ expect(screen.queryByText(/Create an app in the DingTalk developer console/)).not.toBeInTheDocument();
+
+ const guideToggle = screen.getByRole("button", { name: "DingTalk setup guide" });
+ expect(guideToggle).toHaveAttribute("aria-expanded", "false");
+ fireEvent.click(guideToggle);
+
+ expect(guideToggle).toHaveAttribute("aria-expanded", "true");
+ expect(screen.getByText(/Create an app in the DingTalk developer console/)).toBeInTheDocument();
+ expect(screen.getByText(/enable Stream Mode/)).toBeInTheDocument();
+ expect(screen.getByText(/Copy the app's AppKey into Client ID/)).toBeInTheDocument();
+ expect(screen.getByText(/Publish the app/)).toBeInTheDocument();
+ expect(screen.getByText(/then enable the channel/)).toBeInTheDocument();
+ expect(screen.getByRole("link", { name: "Open the DingTalk developer console" }))
+ .toHaveAttribute("href", "https://open-dev.dingtalk.com/");
+
+ fireEvent.click(guideToggle);
+ expect(guideToggle).toHaveAttribute("aria-expanded", "false");
+ expect(screen.queryByText(/Create an app in the DingTalk developer console/)).not.toBeInTheDocument();
+ });
+});
\ No newline at end of file
diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.json
index 5b9dce532..ae5a2b91c 100644
--- a/frontend/src/i18n/locales/ar.json
+++ b/frontend/src/i18n/locales/ar.json
@@ -416,7 +416,90 @@
"stoppedToast": "تم إيقاف قنوات IM",
"refreshFailed": "فشل تحديث قنوات IM",
"startFailed": "فشل بدء قنوات IM",
- "stopFailed": "فشل إيقاف قنوات IM"
+ "stopFailed": "فشل إيقاف قنوات IM",
+ "config": {
+ "toggleConfig": "تهيئة {{name}}",
+ "keepCurrent": "الإبقاء على القيمة الحالية ({{masked}})",
+ "secretNotSet": "غير مُعيّن",
+ "clearSecret": "مسح",
+ "required": "مطلوب",
+ "listPlaceholder": "اكتب قيمة واضغط Enter للإضافة",
+ "removeValue": "إزالة {{value}}",
+ "save": "حفظ الإعدادات",
+ "hotApply": "يُطبَّق الحفظ فورًا — دون حاجة إلى إعادة التشغيل.",
+ "saved": "تم حفظ إعدادات القناة",
+ "saveFailed": "تعذّر حفظ إعدادات القناة: {{message}}",
+ "test": "اختبار الاتصال",
+ "testing": "جارٍ الاختبار…",
+ "testOk": "تم التحقق من الاتصال",
+ "testFailed": "فشل اختبار الاتصال: {{message}}",
+ "testCodeOk": "قبل المزوّد بيانات الاعتماد هذه.",
+ "testCodeInvalidCredentials": "رفض المزوّد بيانات الاعتماد هذه.",
+ "testCodeNetwork": "تعذّر الوصول إلى المزوّد.",
+ "testCodeUnsupported": "هذه القناة لا تدعم اختبار الاتصال.",
+ "testedSavedConfig": "تم اختبار الإعدادات المحفوظة.",
+ "testedDraftConfig": "تم اختبار القيم الموجودة في النموذج (غير المحفوظة بعد).",
+ "enable": "تفعيل القناة",
+ "enableHint": "تعطيلها يحتفظ ببيانات الاعتماد المحفوظة — يمكنك إعادة التفعيل في أي وقت.",
+ "enabledToast": "تم تفعيل القناة",
+ "disabledToast": "تم تعطيل القناة",
+ "enableFailed": "تعذّر تفعيل القناة: {{message}}",
+ "disableFailed": "تعذّر تعطيل القناة: {{message}}",
+ "enableRejected": "رفض المزوّد بيانات الاعتماد هذه، لذا لم يتم تفعيل القناة.",
+ "enableRejectedDetail": "استجابة المزوّد: {{detail}}",
+ "enableAnyway": "التفعيل على أي حال",
+ "enableAnywayHint": "التفعيل على أي حال يتخطى التحقق من بيانات الاعتماد — قد لا تتمكن القناة من الاتصال.",
+ "notWritable": "إعدادات القناة محفوظة في ملف YAML ‏({{path}})، ولا يمكن تعديلها من واجهة الويب. حرّر الملف مباشرةً لتغيير بيانات الاعتماد.",
+ "notWritableChip": "للقراءة فقط (YAML)",
+ "sdkMissing": "حزمة التشغيل SDK غير مثبّتة — {{hint}}",
+ "sdkMissingNoHint": "حزمة التشغيل SDK غير مثبّتة؛ يمكن تهيئة القناة لكنها قد لا تبدأ.",
+ "noFields": "لا توجد حقول قابلة للتهيئة في هذه القناة.",
+ "loadFailed": "تعذّر تحميل إعدادات القناة."
+ },
+ "fields": {
+ "dingtalk": {
+ "client_id": {
+ "label": "Client ID (AppKey)",
+ "help": "مفتاح AppKey الخاص بالتطبيق من صفحة بيانات الاعتماد في وحدة تحكم مطوّري DingTalk."
+ },
+ "client_secret": {
+ "label": "Client Secret (AppSecret)",
+ "help": "سرّ التطبيق AppSecret. يُحفظ على الخادم ولا يُعاد إرساله إلى المتصفح."
+ },
+ "allow_from": {
+ "label": "المرسلون المسموحون",
+ "help": "قائمة اختيارية بمعرّفات مرسلي DingTalk المسموح لهم بالتفاعل مع الوكيل (\"*\" تسمح للجميع). المرسلون غير المقترنين يتلقون رمز اقتران في رسالة خاصة."
+ },
+ "allow_remote_media_redirects": {
+ "label": "السماح بإعادة توجيه الوسائط",
+ "help": "اتّباع إعادة توجيه المزوّد عند تنزيل وسائط الرسائل. معطّل افتراضيًا."
+ },
+ "remote_media_redirect_allowed_hosts": {
+ "label": "المضيفون المسموح بإعادة التوجيه إليهم",
+ "help": "المضيفون المسموح بها عند تفعيل إعادة توجيه الوسائط. القائمة الفارغة تحجب كل إعادة توجيه بين المضيفين."
+ },
+ "group_user_isolation": {
+ "label": "جلسة منفصلة لكل مستخدم في المجموعة",
+ "help": "منح كل عضو في محادثة المجموعة جلسة وكيل خاصة به بدلًا من جلسة مشتركة."
+ },
+ "force_ipv4": {
+ "label": "فرض IPv4",
+ "help": "يربط استدعاءات واجهة DingTalk بعنوان IPv4. مفيد عندما تحتوي قائمة عناوين IP المسموحة على عنوان IPv4 ثابت بينما تتغير بادئة IPv6 باستمرار."
+ }
+ }
+ },
+ "guides": {
+ "dingtalk": {
+ "title": "دليل إعداد DingTalk",
+ "intro": "تستخدم روبوتات DingTalk وضع Stream، لذا لا حاجة إلى عنوان URL عام للاستدعاء.",
+ "step1": "أنشئ تطبيقًا في وحدة تحكم مطوّري DingTalk ‏(open-dev.dingtalk.com).",
+ "step2": "أضف قدرة الروبوت إلى التطبيق وفعّل وضع Stream له.",
+ "step3": "انسخ AppKey الخاص بالتطبيق إلى Client ID وAppSecret إلى Client Secret.",
+ "step4": "انشر التطبيق ليتيح استخدامه داخل مؤسستك.",
+ "step5": "عد إلى هنا، وانقر على «اختبار الاتصال»، ثم فعّل القناة.",
+ "docsLabel": "فتح وحدة تحكم مطوّري DingTalk"
+ }
+ }
},
"generation": "إعدادات التوليد",
"dataSourceSettings": "إعدادات مصادر البيانات",
diff --git a/frontend/src/i18n/locales/de.json b/frontend/src/i18n/locales/de.json
index ba52492df..070660972 100644
--- a/frontend/src/i18n/locales/de.json
+++ b/frontend/src/i18n/locales/de.json
@@ -421,7 +421,90 @@
"stoppedToast": "IM-Kanäle gestoppt",
"refreshFailed": "IM-Kanäle konnten nicht aktualisiert werden",
"startFailed": "IM-Kanäle konnten nicht gestartet werden",
- "stopFailed": "IM-Kanäle konnten nicht gestoppt werden"
+ "stopFailed": "IM-Kanäle konnten nicht gestoppt werden",
+ "config": {
+ "toggleConfig": "{{name}} konfigurieren",
+ "keepCurrent": "Aktuellen Wert behalten ({{masked}})",
+ "secretNotSet": "Nicht gesetzt",
+ "clearSecret": "Löschen",
+ "required": "Erforderlich",
+ "listPlaceholder": "Wert eingeben und mit Enter hinzufügen",
+ "removeValue": "{{value}} entfernen",
+ "save": "Konfiguration speichern",
+ "hotApply": "Speichern wirkt sofort – kein Neustart nötig.",
+ "saved": "Kanal-Konfiguration gespeichert",
+ "saveFailed": "Kanal-Konfiguration konnte nicht gespeichert werden: {{message}}",
+ "test": "Verbindung testen",
+ "testing": "Wird getestet…",
+ "testOk": "Verbindung bestätigt",
+ "testFailed": "Verbindungstest fehlgeschlagen: {{message}}",
+ "testCodeOk": "Der Anbieter hat diese Zugangsdaten akzeptiert.",
+ "testCodeInvalidCredentials": "Der Anbieter hat diese Zugangsdaten abgelehnt.",
+ "testCodeNetwork": "Der Anbieter war nicht erreichbar.",
+ "testCodeUnsupported": "Dieser Kanal unterstützt keine Verbindungstests.",
+ "testedSavedConfig": "Getestet wurde die gespeicherte Konfiguration.",
+ "testedDraftConfig": "Getestet wurden die aktuellen Formularwerte (noch nicht gespeichert).",
+ "enable": "Kanal aktivieren",
+ "enableHint": "Deaktivieren behält die gespeicherten Zugangsdaten – jederzeit wieder aktivierbar.",
+ "enabledToast": "Kanal aktiviert",
+ "disabledToast": "Kanal deaktiviert",
+ "enableFailed": "Kanal konnte nicht aktiviert werden: {{message}}",
+ "disableFailed": "Kanal konnte nicht deaktiviert werden: {{message}}",
+ "enableRejected": "Der Anbieter hat diese Zugangsdaten abgelehnt, daher wurde der Kanal nicht aktiviert.",
+ "enableRejectedDetail": "Antwort des Anbieters: {{detail}}",
+ "enableAnyway": "Trotzdem aktivieren",
+ "enableAnywayHint": "Trotzdem aktivieren überspringt die Prüfung der Zugangsdaten – der Kanal kann möglicherweise keine Verbindung herstellen.",
+ "notWritable": "Die Kanal-Konfiguration liegt in einer YAML-Datei ({{path}}), die die Web-Oberfläche nicht bearbeiten kann. Bearbeite die Datei direkt, um Zugangsdaten zu ändern.",
+ "notWritableChip": "Nur lesbar (YAML)",
+ "sdkMissing": "Laufzeit-SDK nicht installiert – {{hint}}",
+ "sdkMissingNoHint": "Laufzeit-SDK nicht installiert; der Kanal lässt sich konfigurieren, startet aber möglicherweise nicht.",
+ "noFields": "Dieser Kanal hat keine konfigurierbaren Felder.",
+ "loadFailed": "Kanal-Konfiguration konnte nicht geladen werden."
+ },
+ "fields": {
+ "dingtalk": {
+ "client_id": {
+ "label": "Client ID (AppKey)",
+ "help": "Der AppKey der App von der Seite „Zugangsdaten“ der DingTalk-Entwicklerkonsole."
+ },
+ "client_secret": {
+ "label": "Client Secret (AppSecret)",
+ "help": "Das AppSecret der App. Wird serverseitig gespeichert und nie an den Browser zurückgegeben."
+ },
+ "allow_from": {
+ "label": "Erlaubte Absender",
+ "help": "Optionale Positivliste von DingTalk-Absender-IDs, die mit dem Agenten sprechen dürfen („*“ erlaubt alle). Nicht gekoppelte Absender erhalten einen Kopplungscode per Direktnachricht."
+ },
+ "allow_remote_media_redirects": {
+ "label": "Medien-Weiterleitungen erlauben",
+ "help": "Beim Herunterladen von Nachrichtenmedien den Weiterleitungen des Anbieters folgen. Standardmäßig aus."
+ },
+ "remote_media_redirect_allowed_hosts": {
+ "label": "Erlaubte Redirect-Hosts",
+ "help": "Hosts, die bei aktivierten Medien-Weiterleitungen erlaubt sind. Eine leere Liste blockiert alle hostübergreifenden Weiterleitungen."
+ },
+ "group_user_isolation": {
+ "label": "Sitzungen pro Gruppenmitglied",
+ "help": "Jedem Gruppenmitglied eine eigene Agent-Sitzung geben statt einer gemeinsamen."
+ },
+ "force_ipv4": {
+ "label": "IPv4 erzwingen",
+ "help": "Bindet DingTalk-API-Aufrufe an IPv4. Nützlich, wenn die Ausgangs-IP-Whitelist eine stabile IPv4-Adresse enthält, sich das IPv6-Präfix aber ständig ändert."
+ }
+ }
+ },
+ "guides": {
+ "dingtalk": {
+ "title": "DingTalk-Einrichtungsanleitung",
+ "intro": "DingTalk-Bots nutzen den Stream-Modus, daher ist keine öffentliche Callback-URL nötig.",
+ "step1": "Erstelle eine App in der DingTalk-Entwicklerkonsole (open-dev.dingtalk.com).",
+ "step2": "Füge der App die Bot-Funktion hinzu und aktiviere den Stream-Modus.",
+ "step3": "Kopiere den AppKey der App in Client ID und das AppSecret in Client Secret.",
+ "step4": "Veröffentliche die App, damit sie in deiner Organisation verfügbar ist.",
+ "step5": "Kehre hierher zurück, klicke auf „Verbindung testen“ und aktiviere den Kanal.",
+ "docsLabel": "DingTalk-Entwicklerkonsole öffnen"
+ }
+ }
},
"generation": "Generierung",
"dataSourceSettings": "Datenquellen-Einstellungen",
diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json
index 0d66694e1..c73264f49 100644
--- a/frontend/src/i18n/locales/en.json
+++ b/frontend/src/i18n/locales/en.json
@@ -421,7 +421,90 @@
"stoppedToast": "IM channels stopped",
"refreshFailed": "Failed to refresh IM channels",
"startFailed": "Failed to start IM channels",
- "stopFailed": "Failed to stop IM channels"
+ "stopFailed": "Failed to stop IM channels",
+ "config": {
+ "toggleConfig": "Configure {{name}}",
+ "keepCurrent": "Keep current ({{masked}})",
+ "secretNotSet": "Not set",
+ "clearSecret": "Clear",
+ "required": "Required",
+ "listPlaceholder": "Type a value and press Enter",
+ "removeValue": "Remove {{value}}",
+ "save": "Save configuration",
+ "hotApply": "Saving applies immediately — no restart needed.",
+ "saved": "Channel configuration saved",
+ "saveFailed": "Failed to save the channel configuration: {{message}}",
+ "test": "Test connection",
+ "testing": "Testing…",
+ "testOk": "Connection verified",
+ "testFailed": "Connection test failed: {{message}}",
+ "testCodeOk": "The provider accepted these credentials.",
+ "testCodeInvalidCredentials": "The provider rejected these credentials.",
+ "testCodeNetwork": "The provider could not be reached.",
+ "testCodeUnsupported": "This channel does not support connection tests.",
+ "testedSavedConfig": "Tested the saved configuration.",
+ "testedDraftConfig": "Tested the values currently in the form (not saved yet).",
+ "enable": "Enable channel",
+ "enableHint": "Disabling keeps the stored credentials — you can re-enable at any time.",
+ "enabledToast": "Channel enabled",
+ "disabledToast": "Channel disabled",
+ "enableFailed": "Failed to enable the channel: {{message}}",
+ "disableFailed": "Failed to disable the channel: {{message}}",
+ "enableRejected": "The provider rejected these credentials, so the channel was not enabled.",
+ "enableRejectedDetail": "Provider response: {{detail}}",
+ "enableAnyway": "Enable anyway",
+ "enableAnywayHint": "Enabling anyway skips the credential check — the channel may fail to connect.",
+ "notWritable": "Channel configuration is stored in a YAML file ({{path}}), which the web UI cannot edit. Edit that file directly to change credentials.",
+ "notWritableChip": "Read-only (YAML)",
+ "sdkMissing": "Runtime SDK not installed — {{hint}}",
+ "sdkMissingNoHint": "Runtime SDK not installed; the channel can be configured but may not start.",
+ "noFields": "This channel has no configurable fields.",
+ "loadFailed": "Could not load channel configuration."
+ },
+ "fields": {
+ "dingtalk": {
+ "client_id": {
+ "label": "Client ID (AppKey)",
+ "help": "The app's AppKey from the Credentials page of the DingTalk developer console."
+ },
+ "client_secret": {
+ "label": "Client Secret (AppSecret)",
+ "help": "The app's AppSecret. Stored server-side and never sent back to the browser."
+ },
+ "allow_from": {
+ "label": "Allowed senders",
+ "help": "Optional allowlist of DingTalk sender IDs that may talk to the agent (\"*\" allows everyone). Unpaired senders receive a pairing code in a direct message."
+ },
+ "allow_remote_media_redirects": {
+ "label": "Allow remote media redirects",
+ "help": "Follow provider redirects when downloading message media. Off by default."
+ },
+ "remote_media_redirect_allowed_hosts": {
+ "label": "Allowed redirect hosts",
+ "help": "Hosts allowed when remote media redirects are enabled. An empty list blocks every cross-host redirect."
+ },
+ "group_user_isolation": {
+ "label": "Per-user group sessions",
+ "help": "Give each member of a group chat their own agent session instead of sharing one."
+ },
+ "force_ipv4": {
+ "label": "Force IPv4",
+ "help": "Bind DingTalk API calls to IPv4. Useful when the app's egress-IP whitelist holds a stable IPv4 address while the IPv6 prefix keeps rotating."
+ }
+ }
+ },
+ "guides": {
+ "dingtalk": {
+ "title": "DingTalk setup guide",
+ "intro": "DingTalk bots use Stream Mode, so no public callback URL is needed.",
+ "step1": "Create an app in the DingTalk developer console (open-dev.dingtalk.com).",
+ "step2": "Add the bot capability to the app and enable Stream Mode for it.",
+ "step3": "Copy the app's AppKey into Client ID and its AppSecret into Client Secret.",
+ "step4": "Publish the app so it is available to your organization.",
+ "step5": "Return here, click Test connection, then enable the channel.",
+ "docsLabel": "Open the DingTalk developer console"
+ }
+ }
},
"generation": "Generation",
"dataSourceSettings": "Data Source Settings",
diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.json
index b556ec6b8..cb7fd7b90 100644
--- a/frontend/src/i18n/locales/es.json
+++ b/frontend/src/i18n/locales/es.json
@@ -421,7 +421,90 @@
"stoppedToast": "Canales de mensajería detenidos",
"refreshFailed": "Error al actualizar los canales de mensajería",
"startFailed": "Error al iniciar los canales de mensajería",
- "stopFailed": "Error al detener los canales de mensajería"
+ "stopFailed": "Error al detener los canales de mensajería",
+ "config": {
+ "toggleConfig": "Configurar {{name}}",
+ "keepCurrent": "Mantener el valor actual ({{masked}})",
+ "secretNotSet": "Sin definir",
+ "clearSecret": "Borrar",
+ "required": "Obligatorio",
+ "listPlaceholder": "Escribe un valor y pulsa Intro para añadirlo",
+ "removeValue": "Quitar {{value}}",
+ "save": "Guardar configuración",
+ "hotApply": "Guardar se aplica al instante: no hace falta reiniciar.",
+ "saved": "Configuración del canal guardada",
+ "saveFailed": "No se pudo guardar la configuración del canal: {{message}}",
+ "test": "Probar conexión",
+ "testing": "Probando…",
+ "testOk": "Conexión verificada",
+ "testFailed": "La prueba de conexión falló: {{message}}",
+ "testCodeOk": "El proveedor aceptó estas credenciales.",
+ "testCodeInvalidCredentials": "El proveedor rechazó estas credenciales.",
+ "testCodeNetwork": "No se pudo contactar con el proveedor.",
+ "testCodeUnsupported": "Este canal no admite pruebas de conexión.",
+ "testedSavedConfig": "Se probó la configuración guardada.",
+ "testedDraftConfig": "Se probaron los valores actuales del formulario (aún sin guardar).",
+ "enable": "Activar canal",
+ "enableHint": "Desactivarlo conserva las credenciales guardadas: puedes volver a activarlo cuando quieras.",
+ "enabledToast": "Canal activado",
+ "disabledToast": "Canal desactivado",
+ "enableFailed": "No se pudo activar el canal: {{message}}",
+ "disableFailed": "No se pudo desactivar el canal: {{message}}",
+ "enableRejected": "El proveedor rechazó estas credenciales, así que el canal no se activó.",
+ "enableRejectedDetail": "Respuesta del proveedor: {{detail}}",
+ "enableAnyway": "Activar igualmente",
+ "enableAnywayHint": "Activar igualmente omite la verificación de credenciales; el canal podría no conectarse.",
+ "notWritable": "La configuración del canal se guarda en un archivo YAML ({{path}}), que la interfaz web no puede editar. Edita ese archivo directamente para cambiar las credenciales.",
+ "notWritableChip": "Solo lectura (YAML)",
+ "sdkMissing": "SDK de ejecución no instalado — {{hint}}",
+ "sdkMissingNoHint": "El SDK de ejecución no está instalado; el canal se puede configurar, pero podría no iniciarse.",
+ "noFields": "Este canal no tiene campos configurables.",
+ "loadFailed": "No se pudo cargar la configuración del canal."
+ },
+ "fields": {
+ "dingtalk": {
+ "client_id": {
+ "label": "Client ID (AppKey)",
+ "help": "El AppKey de la app, en la página de credenciales de la consola de desarrolladores de DingTalk."
+ },
+ "client_secret": {
+ "label": "Client Secret (AppSecret)",
+ "help": "El AppSecret de la app. Se guarda en el servidor y nunca se devuelve al navegador."
+ },
+ "allow_from": {
+ "label": "Remitentes permitidos",
+ "help": "Lista opcional de IDs de remitente de DingTalk autorizados a hablar con el agente (\"*\" permite a todos). Los remitentes no emparejados reciben un código de emparejamiento por mensaje directo."
+ },
+ "allow_remote_media_redirects": {
+ "label": "Permitir redirecciones de medios",
+ "help": "Seguir las redirecciones del proveedor al descargar medios de los mensajes. Desactivado por defecto."
+ },
+ "remote_media_redirect_allowed_hosts": {
+ "label": "Hosts de redirección permitidos",
+ "help": "Hosts permitidos cuando se activan las redirecciones de medios. Una lista vacía bloquea todas las redirecciones entre hosts."
+ },
+ "group_user_isolation": {
+ "label": "Sesiones por usuario en grupos",
+ "help": "Dar a cada miembro del grupo su propia sesión del agente en lugar de una compartida."
+ },
+ "force_ipv4": {
+ "label": "Forzar IPv4",
+ "help": "Vincula las llamadas a la API de DingTalk a IPv4. Útil cuando la lista blanca de IP de salida tiene una IPv4 estable pero el prefijo IPv6 cambia constantemente."
+ }
+ }
+ },
+ "guides": {
+ "dingtalk": {
+ "title": "Guía de configuración de DingTalk",
+ "intro": "Los bots de DingTalk usan el modo Stream, así que no hace falta una URL de callback pública.",
+ "step1": "Crea una app en la consola de desarrolladores de DingTalk (open-dev.dingtalk.com).",
+ "step2": "Añade la capacidad de bot a la app y activa el modo Stream.",
+ "step3": "Copia el AppKey de la app en Client ID y su AppSecret en Client Secret.",
+ "step4": "Publica la app para que esté disponible en tu organización.",
+ "step5": "Vuelve aquí, pulsa «Probar conexión» y activa el canal.",
+ "docsLabel": "Abrir la consola de desarrolladores de DingTalk"
+ }
+ }
},
"generation": "Generación",
"dataSourceSettings": "Configuración de fuentes de datos",
diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.json
index d2b809194..61a4d1524 100644
--- a/frontend/src/i18n/locales/ja.json
+++ b/frontend/src/i18n/locales/ja.json
@@ -416,7 +416,90 @@
"stoppedToast": "IM チャンネルを停止しました",
"refreshFailed": "IM チャンネルの更新に失敗しました",
"startFailed": "IM チャンネルの開始に失敗しました",
- "stopFailed": "IM チャンネルの停止に失敗しました"
+ "stopFailed": "IM チャンネルの停止に失敗しました",
+ "config": {
+ "toggleConfig": "{{name}} を設定",
+ "keepCurrent": "現在の値を使用({{masked}})",
+ "secretNotSet": "未設定",
+ "clearSecret": "クリア",
+ "required": "必須",
+ "listPlaceholder": "値を入力して Enter で追加",
+ "removeValue": "{{value}} を削除",
+ "save": "設定を保存",
+ "hotApply": "保存するとすぐに反映されます。再起動は不要です。",
+ "saved": "チャンネル設定を保存しました",
+ "saveFailed": "チャンネル設定の保存に失敗しました: {{message}}",
+ "test": "接続テスト",
+ "testing": "テスト中…",
+ "testOk": "接続を確認しました",
+ "testFailed": "接続テストに失敗しました: {{message}}",
+ "testCodeOk": "プロバイダーがこの認証情報を受け付けました。",
+ "testCodeInvalidCredentials": "プロバイダーがこの認証情報を拒否しました。",
+ "testCodeNetwork": "プロバイダーに接続できませんでした。",
+ "testCodeUnsupported": "このチャンネルは接続テストに対応していません。",
+ "testedSavedConfig": "保存済みの設定をテストしました。",
+ "testedDraftConfig": "フォーム上の値(未保存)をテストしました。",
+ "enable": "チャンネルを有効化",
+ "enableHint": "無効化しても認証情報は保持され、いつでも再有効化できます。",
+ "enabledToast": "チャンネルを有効化しました",
+ "disabledToast": "チャンネルを無効化しました",
+ "enableFailed": "チャンネルの有効化に失敗しました: {{message}}",
+ "disableFailed": "チャンネルの無効化に失敗しました: {{message}}",
+ "enableRejected": "プロバイダーが認証情報を拒否したため、チャンネルは有効化されませんでした。",
+ "enableRejectedDetail": "プロバイダーの応答: {{detail}}",
+ "enableAnyway": "それでも有効化",
+ "enableAnywayHint": "それでも有効化すると認証情報の検証をスキップします。接続に失敗する可能性があります。",
+ "notWritable": "チャンネル設定は YAML ファイル({{path}})に保存されているため、Web UI からは編集できません。認証情報を変更するにはファイルを直接編集してください。",
+ "notWritableChip": "読み取り専用(YAML)",
+ "sdkMissing": "ランタイム SDK が未インストール — {{hint}}",
+ "sdkMissingNoHint": "ランタイム SDK が未インストールです。設定はできますが、起動できない場合があります。",
+ "noFields": "このチャンネルに設定可能な項目はありません。",
+ "loadFailed": "チャンネル設定を読み込めませんでした。"
+ },
+ "fields": {
+ "dingtalk": {
+ "client_id": {
+ "label": "Client ID(AppKey)",
+ "help": "DingTalk 開発者コンソールの「認証情報」ページにあるアプリの AppKey です。"
+ },
+ "client_secret": {
+ "label": "Client Secret(AppSecret)",
+ "help": "アプリの AppSecret。サーバー側に保存され、ブラウザーには返されません。"
+ },
+ "allow_from": {
+ "label": "許可する送信者",
+ "help": "エージェントと対話できる DingTalk 送信者 ID の許可リスト(「*」で全員許可)。未ペアの送信者には DM でペアリングコードが送られます。"
+ },
+ "allow_remote_media_redirects": {
+ "label": "メディアのリダイレクトを許可",
+ "help": "メッセージのメディアをダウンロードする際にプロバイダーのリダイレクトを追跡します(既定はオフ)。"
+ },
+ "remote_media_redirect_allowed_hosts": {
+ "label": "許可するリダイレクト先ホスト",
+ "help": "メディアリダイレクトを有効にしたときに許可するホスト。空の場合、クロスホストのリダイレクトはすべて拒否されます。"
+ },
+ "group_user_isolation": {
+ "label": "グループでユーザーごとにセッション分離",
+ "help": "グループチャットの各メンバーに個別のエージェントセッションを割り当てます。"
+ },
+ "force_ipv4": {
+ "label": "IPv4 を強制",
+ "help": "DingTalk API 呼び出しを IPv4 にバインドします。送信元 IP ホワイトリストがあり、IPv6 プレフィックスは変動するが IPv4 は安定している場合に有効にします。"
+ }
+ }
+ },
+ "guides": {
+ "dingtalk": {
+ "title": "DingTalk セットアップガイド",
+ "intro": "DingTalk ボットは Stream モードを使うため、公開コールバック URL は不要です。",
+ "step1": "DingTalk 開発者コンソール(open-dev.dingtalk.com)でアプリを作成します。",
+ "step2": "アプリにボット機能を追加し、Stream モードを有効にします。",
+ "step3": "アプリの AppKey を Client ID に、AppSecret を Client Secret に貼り付けます。",
+ "step4": "アプリを公開して、組織内で利用できるようにします。",
+ "step5": "ここに戻って「接続テスト」をクリックし、チャンネルを有効化します。",
+ "docsLabel": "DingTalk 開発者コンソールを開く"
+ }
+ }
},
"generation": "生成設定",
"dataSourceSettings": "データソース設定",
diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.json
index a114113d6..d41b28508 100644
--- a/frontend/src/i18n/locales/ko.json
+++ b/frontend/src/i18n/locales/ko.json
@@ -416,7 +416,90 @@
"stoppedToast": "IM 채널이 중지되었습니다",
"refreshFailed": "IM 채널 새로 고침 실패",
"startFailed": "IM 채널 시작 실패",
- "stopFailed": "IM 채널 중지 실패"
+ "stopFailed": "IM 채널 중지 실패",
+ "config": {
+ "toggleConfig": "{{name}} 설정",
+ "keepCurrent": "현재 값 유지({{masked}})",
+ "secretNotSet": "설정되지 않음",
+ "clearSecret": "지우기",
+ "required": "필수",
+ "listPlaceholder": "값을 입력하고 Enter로 추가",
+ "removeValue": "{{value}} 제거",
+ "save": "설정 저장",
+ "hotApply": "저장하면 즉시 적용됩니다. 재시작이 필요하지 않습니다.",
+ "saved": "채널 설정을 저장했습니다",
+ "saveFailed": "채널 설정 저장 실패: {{message}}",
+ "test": "연결 테스트",
+ "testing": "테스트 중…",
+ "testOk": "연결이 확인되었습니다",
+ "testFailed": "연결 테스트 실패: {{message}}",
+ "testCodeOk": "공급자가 이 자격 증명을 수락했습니다.",
+ "testCodeInvalidCredentials": "공급자가 이 자격 증명을 거부했습니다.",
+ "testCodeNetwork": "공급자에 연결할 수 없습니다.",
+ "testCodeUnsupported": "이 채널은 연결 테스트를 지원하지 않습니다.",
+ "testedSavedConfig": "저장된 설정을 테스트했습니다.",
+ "testedDraftConfig": "양식의 현재 값(아직 저장되지 않음)을 테스트했습니다.",
+ "enable": "채널 사용",
+ "enableHint": "사용을 중지해도 저장된 자격 증명은 유지되며 언제든 다시 사용할 수 있습니다.",
+ "enabledToast": "채널을 사용하도록 설정했습니다",
+ "disabledToast": "채널을 사용 중지했습니다",
+ "enableFailed": "채널 사용 설정 실패: {{message}}",
+ "disableFailed": "채널 사용 중지 실패: {{message}}",
+ "enableRejected": "공급자가 자격 증명을 거부하여 채널을 사용하도록 설정하지 않았습니다.",
+ "enableRejectedDetail": "공급자 응답: {{detail}}",
+ "enableAnyway": "그래도 사용",
+ "enableAnywayHint": "그래도 사용하면 자격 증명 검사를 건너뛰므로 채널이 연결되지 않을 수 있습니다.",
+ "notWritable": "채널 설정이 YAML 파일({{path}})에 저장되어 있어 웹 UI에서 편집할 수 없습니다. 자격 증명을 변경하려면 해당 파일을 직접 편집하세요.",
+ "notWritableChip": "읽기 전용(YAML)",
+ "sdkMissing": "런타임 SDK가 설치되지 않음 — {{hint}}",
+ "sdkMissingNoHint": "런타임 SDK가 설치되어 있지 않습니다. 설정은 가능하지만 시작하지 못할 수 있습니다.",
+ "noFields": "이 채널에는 구성할 수 있는 필드가 없습니다.",
+ "loadFailed": "채널 설정을 불러오지 못했습니다."
+ },
+ "fields": {
+ "dingtalk": {
+ "client_id": {
+ "label": "Client ID(AppKey)",
+ "help": "DingTalk 개발자 콘솔의 자격 증명 페이지에 있는 앱 AppKey입니다."
+ },
+ "client_secret": {
+ "label": "Client Secret(AppSecret)",
+ "help": "앱의 AppSecret입니다. 서버에 저장되며 브라우저로 다시 전송되지 않습니다."
+ },
+ "allow_from": {
+ "label": "허용된 발신자",
+ "help": "에이전트와 대화할 수 있는 DingTalk 발신자 ID 허용 목록입니다(\"*\"는 모두 허용). 페어링되지 않은 발신자는 DM으로 페어링 코드를 받습니다."
+ },
+ "allow_remote_media_redirects": {
+ "label": "미디어 리디렉션 허용",
+ "help": "메시지 미디어를 내려받을 때 공급자 리디렉션을 따릅니다. 기본값은 꺼짐입니다."
+ },
+ "remote_media_redirect_allowed_hosts": {
+ "label": "허용된 리디렉션 호스트",
+ "help": "미디어 리디렉션을 켰을 때 허용할 호스트입니다. 비어 있으면 모든 교차 호스트 리디렉션이 차단됩니다."
+ },
+ "group_user_isolation": {
+ "label": "그룹에서 사용자별 세션 분리",
+ "help": "그룹 채팅의 각 멤버에게 별도의 에이전트 세션을 제공합니다."
+ },
+ "force_ipv4": {
+ "label": "IPv4 강제",
+ "help": "DingTalk API 호출을 IPv4에 바인딩합니다. 발신 IP 화이트리스트를 사용 중이고 IPv6 접두사는 자주 바뀌지만 IPv4는 안정적일 때 활성화하세요."
+ }
+ }
+ },
+ "guides": {
+ "dingtalk": {
+ "title": "DingTalk 설정 가이드",
+ "intro": "DingTalk 봇은 Stream 모드를 사용하므로 공개 콜백 URL이 필요하지 않습니다.",
+ "step1": "DingTalk 개발자 콘솔(open-dev.dingtalk.com)에서 앱을 만듭니다.",
+ "step2": "앱에 봇 기능을 추가하고 Stream 모드를 사용 설정합니다.",
+ "step3": "앱의 AppKey를 Client ID에, AppSecret을 Client Secret에 붙여 넣습니다.",
+ "step4": "앱을 게시하여 조직에서 사용할 수 있게 합니다.",
+ "step5": "여기로 돌아와 '연결 테스트'를 클릭한 다음 채널을 사용 설정합니다.",
+ "docsLabel": "DingTalk 개발자 콘솔 열기"
+ }
+ }
},
"generation": "생성 설정",
"dataSourceSettings": "데이터 소스 설정",
diff --git a/frontend/src/i18n/locales/pt-BR.json b/frontend/src/i18n/locales/pt-BR.json
index dfedc3282..021b842dc 100644
--- a/frontend/src/i18n/locales/pt-BR.json
+++ b/frontend/src/i18n/locales/pt-BR.json
@@ -421,7 +421,90 @@
"stoppedToast": "Canais de IM parados",
"refreshFailed": "Falha ao atualizar canais de mensagens instantâneas",
"startFailed": "Falha ao iniciar canais de IM",
- "stopFailed": "Falha ao parar canais de mensagens instantâneas"
+ "stopFailed": "Falha ao parar canais de mensagens instantâneas",
+ "config": {
+ "toggleConfig": "Configurar {{name}}",
+ "keepCurrent": "Manter o valor atual ({{masked}})",
+ "secretNotSet": "Não definido",
+ "clearSecret": "Limpar",
+ "required": "Obrigatório",
+ "listPlaceholder": "Digite um valor e pressione Enter para adicionar",
+ "removeValue": "Remover {{value}}",
+ "save": "Salvar configuração",
+ "hotApply": "Salvar é aplicado imediatamente — não é preciso reiniciar.",
+ "saved": "Configuração do canal salva",
+ "saveFailed": "Falha ao salvar a configuração do canal: {{message}}",
+ "test": "Testar conexão",
+ "testing": "Testando…",
+ "testOk": "Conexão verificada",
+ "testFailed": "Falha no teste de conexão: {{message}}",
+ "testCodeOk": "O provedor aceitou estas credenciais.",
+ "testCodeInvalidCredentials": "O provedor rejeitou estas credenciais.",
+ "testCodeNetwork": "Não foi possível alcançar o provedor.",
+ "testCodeUnsupported": "Este canal não oferece teste de conexão.",
+ "testedSavedConfig": "Foi testada a configuração salva.",
+ "testedDraftConfig": "Foram testados os valores atuais do formulário (ainda não salvos).",
+ "enable": "Ativar canal",
+ "enableHint": "Desativar mantém as credenciais salvas — você pode reativar quando quiser.",
+ "enabledToast": "Canal ativado",
+ "disabledToast": "Canal desativado",
+ "enableFailed": "Falha ao ativar o canal: {{message}}",
+ "disableFailed": "Falha ao desativar o canal: {{message}}",
+ "enableRejected": "O provedor rejeitou estas credenciais, então o canal não foi ativado.",
+ "enableRejectedDetail": "Resposta do provedor: {{detail}}",
+ "enableAnyway": "Ativar mesmo assim",
+ "enableAnywayHint": "Ativar mesmo assim ignora a verificação de credenciais — o canal pode não conseguir conectar.",
+ "notWritable": "A configuração do canal fica em um arquivo YAML ({{path}}), que a interface web não pode editar. Edite o arquivo diretamente para alterar as credenciais.",
+ "notWritableChip": "Somente leitura (YAML)",
+ "sdkMissing": "SDK de execução não instalado — {{hint}}",
+ "sdkMissingNoHint": "O SDK de execução não está instalado; o canal pode ser configurado, mas talvez não inicie.",
+ "noFields": "Este canal não tem campos configuráveis.",
+ "loadFailed": "Não foi possível carregar a configuração do canal."
+ },
+ "fields": {
+ "dingtalk": {
+ "client_id": {
+ "label": "Client ID (AppKey)",
+ "help": "O AppKey do app, na página de credenciais do console de desenvolvedor do DingTalk."
+ },
+ "client_secret": {
+ "label": "Client Secret (AppSecret)",
+ "help": "O AppSecret do app. Fica no servidor e nunca é devolvido ao navegador."
+ },
+ "allow_from": {
+ "label": "Remetentes permitidos",
+ "help": "Lista opcional de IDs de remetentes do DingTalk autorizados a falar com o agente (\"*\" libera todos). Remetentes não emparelhados recebem um código de emparelhamento por mensagem direta."
+ },
+ "allow_remote_media_redirects": {
+ "label": "Permitir redirecionamentos de mídia",
+ "help": "Seguir redirecionamentos do provedor ao baixar mídia das mensagens. Desativado por padrão."
+ },
+ "remote_media_redirect_allowed_hosts": {
+ "label": "Hosts de redirecionamento permitidos",
+ "help": "Hosts permitidos quando os redirecionamentos de mídia estão ativos. Uma lista vazia bloqueia todo redirecionamento entre hosts."
+ },
+ "group_user_isolation": {
+ "label": "Sessões por usuário em grupos",
+ "help": "Dar a cada membro do grupo sua própria sessão do agente em vez de uma compartilhada."
+ },
+ "force_ipv4": {
+ "label": "Forçar IPv4",
+ "help": "Vincula as chamadas da API do DingTalk ao IPv4. Útil quando a lista de IPs de saída tem um IPv4 estável, mas o prefixo IPv6 muda constantemente."
+ }
+ }
+ },
+ "guides": {
+ "dingtalk": {
+ "title": "Guia de configuração do DingTalk",
+ "intro": "Os bots do DingTalk usam o modo Stream, então não é necessária uma URL de callback pública.",
+ "step1": "Crie um app no console de desenvolvedor do DingTalk (open-dev.dingtalk.com).",
+ "step2": "Adicione a capacidade de bot ao app e ative o modo Stream.",
+ "step3": "Copie o AppKey do app para o Client ID e o AppSecret para o Client Secret.",
+ "step4": "Publique o app para que ele fique disponível na sua organização.",
+ "step5": "Volte aqui, clique em “Testar conexão” e ative o canal.",
+ "docsLabel": "Abrir o console de desenvolvedor do DingTalk"
+ }
+ }
},
"generation": "Geração",
"dataSourceSettings": "Configurações de fonte de dados",
diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.json
index 73732b4b8..3dbc9e116 100644
--- a/frontend/src/i18n/locales/zh-CN.json
+++ b/frontend/src/i18n/locales/zh-CN.json
@@ -416,7 +416,90 @@
"stoppedToast": "IM 通道已停止",
"refreshFailed": "刷新 IM 通道失败",
"startFailed": "启动 IM 通道失败",
- "stopFailed": "停止 IM 通道失败"
+ "stopFailed": "停止 IM 通道失败",
+ "config": {
+ "toggleConfig": "配置 {{name}}",
+ "keepCurrent": "保留当前值({{masked}})",
+ "secretNotSet": "未设置",
+ "clearSecret": "清除",
+ "required": "必填",
+ "listPlaceholder": "输入后按回车添加",
+ "removeValue": "移除 {{value}}",
+ "save": "保存配置",
+ "hotApply": "保存后立即生效,无需重启。",
+ "saved": "渠道配置已保存",
+ "saveFailed": "保存渠道配置失败:{{message}}",
+ "test": "测试连接",
+ "testing": "测试中…",
+ "testOk": "连接验证通过",
+ "testFailed": "连接测试失败:{{message}}",
+ "testCodeOk": "服务商已接受这些凭据。",
+ "testCodeInvalidCredentials": "服务商拒绝了这些凭据。",
+ "testCodeNetwork": "无法连接到服务商。",
+ "testCodeUnsupported": "该渠道不支持连接测试。",
+ "testedSavedConfig": "测试的是已保存的配置。",
+ "testedDraftConfig": "测试的是表单中当前的值(尚未保存)。",
+ "enable": "启用渠道",
+ "enableHint": "停用会保留已保存的凭据,随时可以重新启用。",
+ "enabledToast": "渠道已启用",
+ "disabledToast": "渠道已停用",
+ "enableFailed": "启用渠道失败:{{message}}",
+ "disableFailed": "停用渠道失败:{{message}}",
+ "enableRejected": "服务商拒绝了这些凭据,渠道未启用。",
+ "enableRejectedDetail": "服务商响应:{{detail}}",
+ "enableAnyway": "仍然启用",
+ "enableAnywayHint": "仍然启用会跳过凭据校验,渠道可能无法连接。",
+ "notWritable": "渠道配置保存在 YAML 文件({{path}})中,Web UI 无法编辑。请直接修改该文件来更改凭据。",
+ "notWritableChip": "只读(YAML)",
+ "sdkMissing": "运行依赖未安装 — {{hint}}",
+ "sdkMissingNoHint": "运行依赖未安装;仍可配置该渠道,但可能无法启动。",
+ "noFields": "该渠道没有可配置的字段。",
+ "loadFailed": "无法加载渠道配置。"
+ },
+ "fields": {
+ "dingtalk": {
+ "client_id": {
+ "label": "Client ID(AppKey)",
+ "help": "钉钉开发者后台“凭据”页面中的应用 AppKey。"
+ },
+ "client_secret": {
+ "label": "Client Secret(AppSecret)",
+ "help": "应用的 AppSecret,保存在服务端,绝不会回传到浏览器。"
+ },
+ "allow_from": {
+ "label": "允许的发送者",
+ "help": "允许与智能体对话的钉钉发送者 ID 白名单(“*”表示全部允许)。未配对的用户会在私聊中收到配对码。"
+ },
+ "allow_remote_media_redirects": {
+ "label": "允许媒体重定向",
+ "help": "下载消息媒体时跟随服务商的重定向,默认关闭。"
+ },
+ "remote_media_redirect_allowed_hosts": {
+ "label": "允许重定向的主机",
+ "help": "开启媒体重定向后允许跳转的主机列表;为空时拒绝所有跨主机跳转。"
+ },
+ "group_user_isolation": {
+ "label": "群聊按用户隔离会话",
+ "help": "群聊中每个成员使用独立的智能体会话,而不是共享同一个会话。"
+ },
+ "force_ipv4": {
+ "label": "强制使用 IPv4",
+ "help": "将钉钉 API 调用绑定到 IPv4 出口。当应用配置了服务器出口 IP 白名单、IPv6 前缀会漂移而 IPv4 地址稳定时启用。"
+ }
+ }
+ },
+ "guides": {
+ "dingtalk": {
+ "title": "钉钉配置指南",
+ "intro": "钉钉机器人使用 Stream 模式,无需公网回调地址。",
+ "step1": "在钉钉开发者后台(open-dev.dingtalk.com)创建应用。",
+ "step2": "为应用添加机器人能力,并开启 Stream 模式。",
+ "step3": "将应用的 AppKey 填入 Client ID,AppSecret 填入 Client Secret。",
+ "step4": "发布应用,使其对组织内成员可用。",
+ "step5": "回到这里点击“测试连接”,然后启用渠道。",
+ "docsLabel": "打开钉钉开发者后台"
+ }
+ }
},
"generation": "生成设置",
"dataSourceSettings": "数据源设置",
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index a49e10938..db067f727 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -525,6 +525,18 @@ export const api = {
method: "POST",
body: JSON.stringify(body),
}),
+ // Web-based IM channel configuration; non-2xx (400/422) throws ApiError.
+ getChannelsConfig: () => request<ChannelsConfigResponse>("/channels/config"),
+ putChannelConfig: (name: string, body: ChannelPutBody) =>
+ request<ChannelPutResult>(`/channels/config/${encodeURIComponent(name)}`, {
+ method: "PUT",
+ body: JSON.stringify(body),
+ }),
+ testChannel: (name: string, body?: ChannelTestBody) =>
+ request<ChannelTestResult>(`/channels/${encodeURIComponent(name)}/test`, {
+ method: "POST",
+ body: JSON.stringify(body ?? {}),
+ }),
// Alpha Zoo API
listAlphas: (params: AlphaListParams = {}) => {
const q = new URLSearchParams();
@@ -847,6 +859,66 @@ export interface ChannelPairingCommandResponse {
reply: string;
}
+export interface ChannelFieldHint {
+ key: string;
+ type: "text" | "password" | "bool" | "list";
+ secret: boolean;
+ required: boolean;
+ help_key?: string | null;
+}
+
+export interface ChannelSecretStatus {
+ set: boolean;
+ masked: string;
+}
+
+export interface ChannelConfigEntry {
+ display_name: string;
+ available: boolean;
+ loaded: boolean;
+ install_hint: string;
+ error: string;
+ supports_test: boolean;
+ sdk_available: boolean;
+ fields: ChannelFieldHint[];
+ values: Record<string, unknown>;
+ secrets: Record<string, ChannelSecretStatus>;
+}
+
+export interface ChannelsConfigResponse {
+ config_path: string;
+ writable: boolean;
+ runtime_running: boolean;
+ channels: Record<string, ChannelConfigEntry>;
+}
+
+// Merge-patches one channel section: an absent secret field is kept as-is,
+// `clear_<field>: true` removes a stored secret, and an enable transition
+// auto-verifies credentials unless `skip_verify` is set.
+export type ChannelPutBody = {
+ config: Record<string, unknown>;
+ skip_verify?: boolean;
+} & {
+ [clearFlag: `clear_${string}`]: boolean | undefined;
+};
+
+export interface ChannelPutResult {
+ channel: ChannelConfigEntry;
+ applied: "hot_swapped" | "reset" | "deferred";
+}
+
+export interface ChannelTestBody {
+ config?: Record<string, unknown>;
+}
+
+export interface ChannelTestResult {
+ ok: boolean;
+ code: "ok" | "invalid_credentials" | "network" | "unsupported";
+ detail?: string;
+ sdk_available: boolean;
+ tested_saved_config: boolean;
+}
+
// --- Types matching backend API contracts ---
export interface RunListItem {
diff --git a/frontend/src/pages/Settings.tsx b/frontend/src/pages/Settings.tsx
index eb143f518..2bc85b5c6 100644
--- a/frontend/src/pages/Settings.tsx
+++ b/frontend/src/pages/Settings.tsx
@@ -1,11 +1,12 @@
import { useEffect, useMemo, useState, type FormEvent } from "react";
-import { Database, KeyRound, Loader2, MessageSquareMore, Play, RefreshCw, RotateCcw, Save, Server, SlidersHorizontal, Square } from "lucide-react";
+import { Database, KeyRound, Loader2, RefreshCw, RotateCcw, Save, Server, SlidersHorizontal } from "lucide-react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
+import { ChannelSettings } from "@/components/settings/ChannelSettings";
import { ModelPicker } from "@/components/settings/ModelPicker";
import { QVerisSettings } from "@/components/settings/QVerisSettings"; // QVERIS-INTEGRATION
import { SourcePrioritySettings } from "@/components/settings/SourcePrioritySettings";
-import { api, isAuthRequiredError, type ChannelRuntimeStatus, type DataSourceSettings, type LLMProviderOption, type LLMSettings } from "@/lib/api";
+import { api, isAuthRequiredError, type DataSourceSettings, type LLMProviderOption, type LLMSettings } from "@/lib/api";
import { getApiAuthKey, setApiAuthKey } from "@/lib/apiAuth";
interface LLMFormState {
@@ -40,7 +41,6 @@ export function Settings() {
const isDesktop = window.vibeDesktop?.isDesktop === true;
const [settings, setSettings] = useState<LLMSettings | null>(null);
const [dataSettings, setDataSettings] = useState<DataSourceSettings | null>(null);
- const [channelStatus, setChannelStatus] = useState<ChannelRuntimeStatus | null>(null);
const [form, setForm] = useState<LLMFormState | null>(null);
const [apiKey, setApiKey] = useState("");
const [modelOptions, setModelOptions] = useState<string[]>([]);
@@ -53,8 +53,6 @@ export function Settings() {
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [dataSaving, setDataSaving] = useState(false);
- const [channelRefreshing, setChannelRefreshing] = useState(false);
- const [channelAction, setChannelAction] = useState<"start" | "stop" | null>(null);
const [settingsLoadError, setSettingsLoadError] = useState<string | null>(null);
useEffect(() => {
@@ -63,9 +61,8 @@ export function Settings() {
Promise.allSettled([
api.getLLMSettings(),
api.getDataSourceSettings(),
- api.getChannelStatus(),
])
- .then(([llmResult, dataSourceResult, channelResult]) => {
+ .then(([llmResult, dataSourceResult]) => {
if (!alive) return;
if (llmResult.status === "fulfilled") {
@@ -100,16 +97,6 @@ export function Settings() {
toast.error(t("settings.loadDataSourceSettingsFailed", { message }));
}
}
-
- if (channelResult.status === "fulfilled") {
- setChannelStatus(channelResult.value);
- } else {
- const message = channelResult.reason instanceof Error
- ? channelResult.reason.message
- : t("settings.unknownError", { defaultValue: "Unknown error" });
- toast.error(`${t("settings.channels.refreshFailed")}: ${message}`);
- setChannelStatus(null);
- }
})
.finally(() => {
if (alive) setLoading(false);
@@ -120,30 +107,6 @@ export function Settings() {
};
}, [t]);
- const refreshChannelStatus = async () => {
- setChannelRefreshing(true);
- try {
- setChannelStatus(await api.getChannelStatus());
- } catch (error) {
- toast.error(`${t("settings.channels.refreshFailed")}: ${error instanceof Error ? error.message : t("settings.unknownError", { defaultValue: "Unknown error" })}`);
- } finally {
- setChannelRefreshing(false);
- }
- };
-
- const setChannelsRunning = async (action: "start" | "stop") => {
- setChannelAction(action);
- try {
- const updated = action === "start" ? await api.startChannels() : await api.stopChannels();
- setChannelStatus(updated);
- toast.success(action === "start" ? t("settings.channels.started") : t("settings.channels.stoppedToast"));
- } catch (error) {
- toast.error(`${action === "start" ? t("settings.channels.startFailed") : t("settings.channels.stopFailed")}: ${error instanceof Error ? error.message : t("settings.unknownError", { defaultValue: "Unknown error" })}`);
- } finally {
- setChannelAction(null);
- }
- };
-
const providers = settings?.providers ?? [];
const selectedProvider = useMemo<LLMProviderOption | undefined>(
() => providers.find((provider) => provider.name === form?.provider),
@@ -360,121 +323,7 @@ export function Settings() {
const tushareStatus = dataSettings.tushare_token_configured
? t("settings.configured")
: t("settings.keepCurrentToken");
- const channelRows = channelStatus
- ? Object.entries(channelStatus.channels ?? {}).sort(([a], [b]) => a.localeCompare(b))
- : [];
- const channelEnabledCount = channelRows.filter(([, item]) => item.enabled).length;
- const channelLoadedCount = channelRows.filter(([, item]) => item.loaded).length;
- const channelUnavailableCount = channelRows.filter(([, item]) => item.available === false).length;
- const channelBusy = channelRefreshing || channelAction !== null;
-
- const channelsSection = (
- <section className="rounded-lg border bg-card p-5 shadow-sm">
- <div className="mb-5 flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
- <div className="space-y-1">
- <div className="flex items-center gap-2">
- <MessageSquareMore className="h-4 w-4 text-primary" />
- <h2 className="text-base font-semibold">{t("settings.channels.title")}</h2>
- </div>
- <p className="max-w-3xl text-sm text-muted-foreground">{t("settings.channels.description")}</p>
- </div>
- <div className="flex flex-wrap gap-2">
- <button
- type="button"
- onClick={refreshChannelStatus}
- disabled={channelBusy}
- className="inline-flex items-center justify-center gap-2 rounded-md border px-3 py-2 text-sm text-muted-foreground transition hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-60"
- >
- {channelRefreshing ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
- {t("settings.channels.refresh")}
- </button>
- <button
- type="button"
- onClick={() => setChannelsRunning("start")}
- disabled={channelBusy || !channelStatus}
- className="inline-flex items-center justify-center gap-2 rounded-md bg-primary px-3 py-2 text-sm font-medium text-primary-foreground transition hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-60"
- >
- {channelAction === "start" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}
- {t("settings.channels.start")}
- </button>
- <button
- type="button"
- onClick={() => setChannelsRunning("stop")}
- disabled={channelBusy || !channelStatus}
- className="inline-flex items-center justify-center gap-2 rounded-md border px-3 py-2 text-sm text-muted-foreground transition hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-60"
- >
- {channelAction === "stop" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Square className="h-4 w-4" />}
- {t("settings.channels.stop")}
- </button>
- </div>
- </div>
- {channelStatus ? (
- <>
- <div className="mb-4 grid gap-3 md:grid-cols-4">
- <div className="rounded-md border bg-muted/20 px-3 py-2">
- <div className="text-xs text-muted-foreground">{t("settings.channels.runtime")}</div>
- <div className="text-sm font-medium">{channelStatus.running ? t("settings.channels.running") : t("settings.channels.stopped")}</div>
- </div>
- <div className="rounded-md border bg-muted/20 px-3 py-2">
- <div className="text-xs text-muted-foreground">{t("settings.channels.enabled")}</div>
- <div className="text-sm font-medium">{channelEnabledCount}</div>
- </div>
- <div className="rounded-md border bg-muted/20 px-3 py-2">
- <div className="text-xs text-muted-foreground">{t("settings.channels.loaded")}</div>
- <div className="text-sm font-medium">{channelLoadedCount}</div>
- </div>
- <div className="rounded-md border bg-muted/20 px-3 py-2">
- <div className="text-xs text-muted-foreground">{t("settings.channels.unavailable")}</div>
- <div className="text-sm font-medium">{channelUnavailableCount}</div>
- </div>
- </div>
-
- <div className="overflow-hidden rounded-md border">
- <table className="w-full text-sm">
- <thead className="bg-muted/40 text-xs text-muted-foreground">
- <tr>
- <th className="px-3 py-2 text-start font-medium">{t("settings.channels.channel")}</th>
- <th className="px-3 py-2 text-start font-medium">{t("settings.channels.state")}</th>
- <th className="px-3 py-2 text-start font-medium">{t("settings.channels.recovery")}</th>
- </tr>
- </thead>
- <tbody>
- {channelRows.map(([name, item]) => (
- <tr key={name} className="border-t">
- <td className="px-3 py-2 align-top">
- <div className="font-medium">{item.display_name || name}</div>
- <div className="text-xs text-muted-foreground">{name}</div>
- </td>
- <td className="px-3 py-2 align-top">
- <div className="flex flex-wrap gap-1.5">
- <span className={`rounded-full px-2 py-0.5 text-xs ${item.enabled ? "bg-primary/10 text-primary" : "bg-muted text-muted-foreground"}`}>
- {item.enabled ? t("settings.channels.enabled") : t("settings.channels.disabled")}
- </span>
- <span className={`rounded-full px-2 py-0.5 text-xs ${item.loaded ? "bg-success/10 text-success" : "bg-muted text-muted-foreground"}`}>
- {item.loaded ? t("settings.channels.loaded") : t("settings.channels.notLoaded")}
- </span>
- <span className={`rounded-full px-2 py-0.5 text-xs ${item.running ? "bg-success/10 text-success" : "bg-muted text-muted-foreground"}`}>
- {item.running ? t("settings.channels.running") : t("settings.channels.stopped")}
- </span>
- </div>
- </td>
- <td className="max-w-md px-3 py-2 align-top text-xs text-muted-foreground">
- {item.install_hint || item.error || t("settings.channels.noRecovery")}
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- </>
- ) : (
- <div className="rounded-md border bg-muted/20 px-4 py-6 text-center text-sm text-muted-foreground">
- {t("settings.channels.refreshFailed")}
- </div>
- )}
- </section>
- );
return (
<div className="mx-auto max-w-5xl space-y-6 p-6">
<div className="space-y-2">
@@ -487,7 +336,7 @@ export function Settings() {
{/* QVERIS-INTEGRATION */}
<QVerisSettings />
- {channelsSection}
+ <ChannelSettings />
<div className="space-y-2">
<h2 className="text-lg font-semibold tracking-tight">{t("settings.llmSettings")}</h2>
diff --git a/frontend/src/pages/__tests__/SettingsChannels.test.tsx b/frontend/src/pages/__tests__/SettingsChannels.test.tsx
index eb9bfa7eb..bc3469606 100644
--- a/frontend/src/pages/__tests__/SettingsChannels.test.tsx
+++ b/frontend/src/pages/__tests__/SettingsChannels.test.tsx
@@ -5,9 +5,12 @@ const apiMock = vi.hoisted(() => ({
getLLMSettings: vi.fn(),
getDataSourceSettings: vi.fn(),
getChannelStatus: vi.fn(),
+ getChannelsConfig: vi.fn(),
listLLMModels: vi.fn(),
startChannels: vi.fn(),
stopChannels: vi.fn(),
+ putChannelConfig: vi.fn(),
+ testChannel: vi.fn(),
updateLLMSettings: vi.fn(),
updateDataSourceSettings: vi.fn(),
}));
@@ -99,11 +102,34 @@ function channelStatus(overrides = {}) {
};
}
+function channelsConfig() {
+ return {
+ config_path: "agent/agent.json",
+ writable: true,
+ runtime_running: false,
+ channels: {
+ dingtalk: {
+ display_name: "DingTalk",
+ available: true,
+ loaded: true,
+ install_hint: "",
+ error: "",
+ supports_test: true,
+ sdk_available: true,
+ fields: [],
+ values: { enabled: false },
+ secrets: {},
+ },
+ },
+ };
+}
+
describe("Settings IM channels panel", () => {
beforeEach(() => {
apiMock.getLLMSettings.mockResolvedValue(llmSettings());
apiMock.getDataSourceSettings.mockResolvedValue(dataSourceSettings());
apiMock.getChannelStatus.mockResolvedValue(channelStatus());
+ apiMock.getChannelsConfig.mockResolvedValue(channelsConfig());
apiMock.listLLMModels.mockResolvedValue({
provider: "openrouter",
models: ["deepseek/deepseek-v3.2"],
@@ -118,7 +144,7 @@ describe("Settings IM channels panel", () => {
render(<Settings />);
expect(await screen.findByText("IM Channels")).toBeInTheDocument();
- expect(screen.getByText("websocket")).toBeInTheDocument();
+ expect(await screen.findByText("websocket")).toBeInTheDocument();
expect(screen.getByText("telegram")).toBeInTheDocument();
expect(screen.getByText("pip install 'vibe-trading-ai[telegram]'")).toBeInTheDocument();
@@ -129,7 +155,9 @@ describe("Settings IM channels panel", () => {
it("starts channels from the settings control surface", async () => {
render(<Settings />);
- await screen.findByText("IM Channels");
+ // Start stays disabled until the runtime status lands, so wait for the row
+ // the status request renders before clicking.
+ await screen.findByText("websocket");
fireEvent.click(screen.getByRole("button", { name: "Start channels" }));
diff --git a/frontend/src/pages/__tests__/SettingsQVeris.test.tsx b/frontend/src/pages/__tests__/SettingsQVeris.test.tsx
index 2b32186ef..f71d808f2 100644
--- a/frontend/src/pages/__tests__/SettingsQVeris.test.tsx
+++ b/frontend/src/pages/__tests__/SettingsQVeris.test.tsx
@@ -7,6 +7,7 @@ const apiMock = vi.hoisted(() => ({
getLLMSettings: vi.fn(),
getDataSourceSettings: vi.fn(),
getChannelStatus: vi.fn(),
+ getChannelsConfig: vi.fn(),
startChannels: vi.fn(),
stopChannels: vi.fn(),
updateLLMSettings: vi.fn(),
@@ -148,6 +149,12 @@ describe("Settings QVeris card", () => {
apiMock.getLLMSettings.mockResolvedValue(llmSettings());
apiMock.getDataSourceSettings.mockResolvedValue(dataSourceSettings());
apiMock.getChannelStatus.mockResolvedValue(channelStatus());
+ apiMock.getChannelsConfig.mockResolvedValue({
+ config_path: "agent/agent.json",
+ writable: true,
+ runtime_running: false,
+ channels: {},
+ });
apiMock.startChannels.mockResolvedValue(channelStatus());
apiMock.stopChannels.mockResolvedValue(channelStatus());
});