Refactor channel account management: move binding/editing to Channels, align Agents display, and simplify UX (#523)

This commit is contained in:
Felix
2026-03-16 18:20:11 +08:00
committed by GitHub
Unverified
parent db480dff17
commit 4be679ac56
20 changed files with 1192 additions and 346 deletions

View File

@@ -47,7 +47,11 @@ interface ChannelConfigModalProps {
configuredTypes?: string[];
showChannelName?: boolean;
allowExistingConfig?: boolean;
allowEditAccountId?: boolean;
existingAccountIds?: string[];
initialConfigValues?: Record<string, string>;
agentId?: string;
accountId?: string;
onClose: () => void;
onChannelSaved?: (channelType: ChannelType) => void | Promise<void>;
}
@@ -62,7 +66,11 @@ export function ChannelConfigModal({
configuredTypes = [],
showChannelName = true,
allowExistingConfig = true,
allowEditAccountId = false,
existingAccountIds = [],
initialConfigValues,
agentId,
accountId,
onClose,
onChannelSaved,
}: ChannelConfigModalProps) {
@@ -71,6 +79,7 @@ export function ChannelConfigModal({
const [selectedType, setSelectedType] = useState<ChannelType | null>(initialSelectedType);
const [configValues, setConfigValues] = useState<Record<string, string>>({});
const [channelName, setChannelName] = useState('');
const [accountIdInput, setAccountIdInput] = useState(accountId || '');
const [connecting, setConnecting] = useState(false);
const [showSecrets, setShowSecrets] = useState<Record<string, boolean>>({});
const [qrCode, setQrCode] = useState<string | null>(null);
@@ -86,11 +95,18 @@ export function ChannelConfigModal({
const meta: ChannelMeta | null = selectedType ? CHANNEL_META[selectedType] : null;
const shouldUseCredentialValidation = selectedType !== 'feishu';
const resolvedAccountId = allowEditAccountId
? accountIdInput.trim()
: (accountId ?? (agentId ? (agentId === 'main' ? 'default' : agentId) : undefined));
useEffect(() => {
setSelectedType(initialSelectedType);
}, [initialSelectedType]);
useEffect(() => {
setAccountIdInput(accountId || '');
}, [accountId]);
useEffect(() => {
if (!selectedType) {
setConfigValues({});
@@ -112,13 +128,21 @@ export function ChannelConfigModal({
return;
}
if (initialConfigValues) {
setConfigValues(initialConfigValues);
setIsExistingConfig(Object.keys(initialConfigValues).length > 0);
setLoadingConfig(false);
setChannelName(showChannelName ? CHANNEL_NAMES[selectedType] : '');
return;
}
let cancelled = false;
setLoadingConfig(true);
setChannelName(showChannelName ? CHANNEL_NAMES[selectedType] : '');
(async () => {
try {
const accountParam = agentId ? `?accountId=${encodeURIComponent(agentId === 'main' ? 'default' : agentId)}` : '';
const accountParam = resolvedAccountId ? `?accountId=${encodeURIComponent(resolvedAccountId)}` : '';
const result = await hostApiFetch<{ success: boolean; values?: Record<string, string> }>(
`/api/channels/config/${encodeURIComponent(selectedType)}${accountParam}`
);
@@ -144,7 +168,7 @@ export function ChannelConfigModal({
return () => {
cancelled = true;
};
}, [agentId, allowExistingConfig, configuredTypes, selectedType, showChannelName]);
}, [allowExistingConfig, configuredTypes, initialConfigValues, resolvedAccountId, selectedType, showChannelName]);
useEffect(() => {
if (selectedType && !loadingConfig && showChannelName && firstInputRef.current) {
@@ -187,13 +211,18 @@ export function ChannelConfigModal({
try {
const saveResult = await hostApiFetch<{ success?: boolean; error?: string }>('/api/channels/config', {
method: 'POST',
body: JSON.stringify({ channelType: 'whatsapp', config: { enabled: true } }),
body: JSON.stringify({ channelType: 'whatsapp', config: { enabled: true }, accountId: resolvedAccountId }),
});
if (!saveResult?.success) {
throw new Error(saveResult?.error || 'Failed to save WhatsApp config');
}
await finishSave('whatsapp');
try {
await finishSave('whatsapp');
} catch (postSaveError) {
toast.warning(t('toast.savedButRefreshFailed'));
console.warn('Channel saved but post-save refresh failed:', postSaveError);
}
// Gateway restart is already triggered by scheduleGatewayChannelRestart
// in the POST /api/channels/config route handler (debounced). Calling
// restart() here directly races with that debounced restart and the
@@ -222,7 +251,7 @@ export function ChannelConfigModal({
removeErrorListener();
hostApiFetch('/api/channels/whatsapp/cancel', { method: 'POST' }).catch(() => { });
};
}, [selectedType, finishSave, onClose, t]);
}, [finishSave, onClose, resolvedAccountId, selectedType, t]);
const handleValidate = async () => {
if (!selectedType || !shouldUseCredentialValidation) return;
@@ -273,10 +302,25 @@ export function ChannelConfigModal({
setValidationResult(null);
try {
if (allowEditAccountId) {
const nextAccountId = accountIdInput.trim();
if (!nextAccountId) {
toast.error(t('account.invalidId'));
setConnecting(false);
return;
}
const duplicateExists = existingAccountIds.some((id) => id === nextAccountId && id !== (accountId || '').trim());
if (duplicateExists) {
toast.error(t('account.accountIdExists', { accountId: nextAccountId }));
setConnecting(false);
return;
}
}
if (meta.connectionType === 'qr') {
await hostApiFetch('/api/channels/whatsapp/start', {
method: 'POST',
body: JSON.stringify({ accountId: 'default' }),
body: JSON.stringify({ accountId: resolvedAccountId || 'default' }),
});
return;
}
@@ -319,7 +363,6 @@ export function ChannelConfigModal({
}
const config: Record<string, unknown> = { ...configValues };
const resolvedAccountId = agentId ? (agentId === 'main' ? 'default' : agentId) : undefined;
const saveResult = await hostApiFetch<{
success?: boolean;
error?: string;
@@ -335,7 +378,12 @@ export function ChannelConfigModal({
toast.warning(saveResult.warning);
}
await finishSave(selectedType);
try {
await finishSave(selectedType);
} catch (postSaveError) {
toast.warning(t('toast.savedButRefreshFailed'));
console.warn('Channel saved but post-save refresh failed:', postSaveError);
}
toast.success(t('toast.channelSaved', { name: meta.name }));
toast.success(t('toast.channelConnecting', { name: meta.name }));
@@ -534,6 +582,20 @@ export function ChannelConfigModal({
</div>
)}
{allowEditAccountId && (
<div className="space-y-2.5">
<Label htmlFor="account-id" className={labelClasses}>{t('account.customIdLabel')}</Label>
<Input
id="account-id"
value={accountIdInput}
onChange={(event) => setAccountIdInput(event.target.value)}
placeholder={t('account.customIdPlaceholder')}
className={inputClasses}
/>
<p className="text-[12px] text-muted-foreground">{t('account.customIdHint')}</p>
</div>
)}
<div className="space-y-4">
{meta?.configFields.map((field) => (
<ConfigField
@@ -623,7 +685,7 @@ export function ChannelConfigModal({
onClick={() => {
void handleConnect();
}}
disabled={connecting || !isFormValid()}
disabled={connecting || !isFormValid() || (allowEditAccountId && !accountIdInput.trim())}
className={primaryButtonClasses}
>
{connecting ? (

View File

@@ -29,7 +29,9 @@
"agentIdLabel": "Agent ID",
"modelLabel": "Model",
"channelsTitle": "Channels",
"channelsDescription": "Each channel type has a single ClawX configuration. Saving a configured channel here moves ownership to this agent.",
"channelsDescription": "This list is read-only. Manage channel accounts and bindings in the Channels page.",
"mainAccount": "Main account",
"channelsManagedInChannels": "This agent is linked to channel types. Manage exact account bindings in the Channels page.",
"addChannel": "Add Channel",
"noChannels": "No channels are assigned to this agent yet."
},
@@ -49,4 +51,4 @@
"channelRemoved": "{{channel}} removed",
"channelRemoveFailed": "Failed to remove channel: {{error}}"
}
}
}

View File

@@ -1,6 +1,6 @@
{
"title": "Messaging Channels",
"subtitle": "Manage your messaging channels and connections. The configuration is only effective for the main Agent.",
"subtitle": "Manage messaging channels, accounts, account-to-agent bindings, and each channel's default account.",
"refresh": "Refresh",
"addChannel": "Add Channel",
"stats": {
@@ -24,8 +24,45 @@
"whatsappFailed": "WhatsApp connection failed: {{error}}",
"channelSaved": "Channel {{name}} saved",
"channelConnecting": "Connecting to {{name}}...",
"savedButRefreshFailed": "Configuration was saved, but refreshing page data failed. Please refresh manually.",
"restartManual": "Please restart the gateway manually",
"configFailed": "Configuration failed: {{error}}"
"configFailed": "Configuration failed: {{error}}",
"bindingUpdated": "Account binding updated",
"defaultUpdated": "Default account updated",
"accountDeleted": "Account deleted",
"channelDeleted": "Channel deleted"
},
"account": {
"add": "Add Account",
"edit": "Edit",
"delete": "Delete Account",
"deleteChannel": "Delete channel",
"deleteConfirm": "Are you sure you want to delete this account?",
"default": "Current Default",
"setDefault": "Set as channel default",
"unassigned": "Unassigned",
"mainAccount": "Primary Account",
"customIdLabel": "Account ID",
"customIdPlaceholder": "e.g. feishu-sales-bot",
"customIdHint": "Use a custom account ID to distinguish multiple accounts under one channel.",
"invalidId": "Account ID cannot be empty",
"idLabel": "ID: {{id}}",
"boundTo": "Bound to: {{agent}}",
"handledBy": "Handled by {{agent}}",
"bindingStatusLabel": "Binding: {{status}}",
"connectionStatusLabel": "Connection: {{status}}",
"bindingStatus": {
"bound": "Bound",
"unbound": "Unbound"
},
"connectionStatus": {
"connected": "Connected",
"connecting": "Connecting",
"disconnected": "Disconnected",
"error": "Error"
},
"accountIdPrompt": "Enter a new account ID for this channel",
"accountIdExists": "Account ID {{accountId}} already exists"
},
"dialog": {
"updateTitle": "Update {{name}}",
@@ -338,4 +375,4 @@
}
},
"viewDocs": "View Documentation"
}
}

View File

@@ -29,7 +29,9 @@
"agentIdLabel": "Agent ID",
"modelLabel": "Model",
"channelsTitle": "Channels",
"channelsDescription": "各 Channel 種別は ClawX で 1 つだけ設定されます。ここで既存の Channel を保存すると、この Agent に所属が移動します。",
"channelsDescription": "この一覧は読み取り専用です。チャンネルアカウントと紐付けは Channels ページで管理してください。",
"mainAccount": "メインアカウント",
"channelsManagedInChannels": "この Agent はチャンネル種別に紐付いています。アカウント単位の紐付けは Channels ページで管理してください。",
"addChannel": "Channel を追加",
"noChannels": "この Agent にはまだ Channel が割り当てられていません。"
},
@@ -49,4 +51,4 @@
"channelRemoved": "{{channel}} を削除しました",
"channelRemoveFailed": "Channel の削除に失敗しました: {{error}}"
}
}
}

View File

@@ -1,6 +1,6 @@
{
"title": "メッセージングチャンネル",
"subtitle": "メッセージングチャンネルと接続を管理。設定はメイン Agent のみ有効です",
"subtitle": "メッセージングチャンネル、アカウント、Agent への紐付け、チャンネルのデフォルトアカウントを一元管理します",
"refresh": "更新",
"addChannel": "チャンネルを追加",
"stats": {
@@ -24,8 +24,45 @@
"whatsappFailed": "WhatsApp 接続に失敗しました: {{error}}",
"channelSaved": "チャンネル {{name}} が保存されました",
"channelConnecting": "{{name}} に接続中...",
"savedButRefreshFailed": "設定は保存されましたが、画面データの更新に失敗しました。手動で再読み込みしてください。",
"restartManual": "ゲートウェイを手動で再起動してください",
"configFailed": "設定に失敗しました: {{error}}"
"configFailed": "設定に失敗しました: {{error}}",
"bindingUpdated": "アカウントの紐付けを保存しました",
"defaultUpdated": "デフォルトアカウントを更新しました",
"accountDeleted": "アカウントを削除しました",
"channelDeleted": "チャンネルを削除しました"
},
"account": {
"add": "アカウントを追加",
"edit": "編集",
"delete": "アカウントを削除",
"deleteChannel": "チャンネルを削除",
"deleteConfirm": "このアカウントを削除してもよろしいですか?",
"default": "現在の既定",
"setDefault": "チャンネル既定に設定",
"unassigned": "未割り当て",
"mainAccount": "メインアカウント",
"customIdLabel": "アカウント ID",
"customIdPlaceholder": "例: feishu-sales-bot",
"customIdHint": "同じチャンネル内の複数アカウントを区別するため、任意の ID を設定できます。",
"invalidId": "アカウント ID は空にできません",
"idLabel": "ID: {{id}}",
"boundTo": "割り当て先: {{agent}}",
"handledBy": "{{agent}} が処理",
"bindingStatusLabel": "紐付け状態:{{status}}",
"connectionStatusLabel": "接続状態:{{status}}",
"bindingStatus": {
"bound": "紐付け済み",
"unbound": "未紐付け"
},
"connectionStatus": {
"connected": "接続済み",
"connecting": "接続中",
"disconnected": "未接続",
"error": "異常"
},
"accountIdPrompt": "このチャンネルの新しいアカウント ID を入力してください",
"accountIdExists": "アカウント ID {{accountId}} はすでに存在します"
},
"dialog": {
"updateTitle": "{{name}} を更新",
@@ -338,4 +375,4 @@
}
},
"viewDocs": "ドキュメントを表示"
}
}

View File

@@ -29,7 +29,9 @@
"agentIdLabel": "Agent ID",
"modelLabel": "Model",
"channelsTitle": "频道",
"channelsDescription": "每种频道类型在 ClawX 中只保留一份配置。在这里保存已配置的频道会将归属切换到当前 Agent。",
"channelsDescription": "该列表为只读。频道账号与绑定关系请在 Channels 页面管理。",
"mainAccount": "主账号",
"channelsManagedInChannels": "该 Agent 绑定了频道类型,但具体账号绑定请在 Channels 页面查看。",
"addChannel": "添加频道",
"noChannels": "这个 Agent 还没有分配任何频道。"
},
@@ -49,4 +51,4 @@
"channelRemoved": "{{channel}} 已移除",
"channelRemoveFailed": "移除频道失败:{{error}}"
}
}
}

View File

@@ -1,6 +1,6 @@
{
"title": "消息频道",
"subtitle": "连接到消息平台,配置仅对主 Agent 生效",
"subtitle": "统一管理消息频道、账号、账号与智能体的绑定关系,以及频道默认账号",
"refresh": "刷新",
"addChannel": "添加频道",
"stats": {
@@ -24,8 +24,45 @@
"whatsappFailed": "WhatsApp 连接失败: {{error}}",
"channelSaved": "频道 {{name}} 已保存",
"channelConnecting": "正在连接 {{name}}...",
"savedButRefreshFailed": "配置已保存,但刷新页面数据失败,请手动刷新查看最新状态",
"restartManual": "请手动重启网关",
"configFailed": "配置失败: {{error}}"
"configFailed": "配置失败: {{error}}",
"bindingUpdated": "账号绑定已更新",
"defaultUpdated": "默认账号已更新",
"accountDeleted": "账号已删除",
"channelDeleted": "频道已删除"
},
"account": {
"add": "添加账号",
"edit": "编辑",
"delete": "删除账号",
"deleteChannel": "删除频道",
"deleteConfirm": "确定要删除该账号吗?",
"default": "当前默认",
"setDefault": "设为频道默认账号",
"unassigned": "未绑定",
"mainAccount": "主账号",
"customIdLabel": "账号 ID",
"customIdPlaceholder": "例如feishu-sales-bot",
"customIdHint": "可自定义账号 ID用于区分同一频道下的多个账号。",
"invalidId": "账号 ID 不能为空",
"idLabel": "ID: {{id}}",
"boundTo": "绑定对象:{{agent}}",
"handledBy": "由 {{agent}} 处理",
"bindingStatusLabel": "绑定状态:{{status}}",
"connectionStatusLabel": "连接状态:{{status}}",
"bindingStatus": {
"bound": "已绑定",
"unbound": "未绑定"
},
"connectionStatus": {
"connected": "已连接",
"connecting": "连接中",
"disconnected": "未连接",
"error": "异常"
},
"accountIdPrompt": "请输入该频道的新账号 ID",
"accountIdExists": "账号 ID {{accountId}} 已存在"
},
"dialog": {
"updateTitle": "更新 {{name}}",
@@ -339,4 +376,4 @@
}
},
"viewDocs": "查看文档"
}
}

View File

@@ -1,4 +1,4 @@
import { useEffect, useMemo, useState } from 'react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { AlertCircle, Bot, Check, Plus, RefreshCw, Settings2, Trash2, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
@@ -6,12 +6,10 @@ import { Label } from '@/components/ui/label';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { StatusBadge } from '@/components/common/StatusBadge';
import { LoadingSpinner } from '@/components/common/LoadingSpinner';
import { ChannelConfigModal } from '@/components/channels/ChannelConfigModal';
import { useAgentsStore } from '@/stores/agents';
import { useChannelsStore } from '@/stores/channels';
import { useGatewayStore } from '@/stores/gateway';
import { hostApiFetch } from '@/lib/host-api';
import { CHANNEL_ICONS, CHANNEL_NAMES, type ChannelType } from '@/types/channel';
import type { AgentSummary } from '@/types/agent';
import { useTranslation } from 'react-i18next';
@@ -25,6 +23,23 @@ import feishuIcon from '@/assets/channels/feishu.svg';
import wecomIcon from '@/assets/channels/wecom.svg';
import qqIcon from '@/assets/channels/qq.svg';
interface ChannelAccountItem {
accountId: string;
name: string;
configured: boolean;
status: 'connected' | 'connecting' | 'disconnected' | 'error';
lastError?: string;
isDefault: boolean;
agentId?: string;
}
interface ChannelGroupItem {
channelType: string;
defaultAccountId: string;
status: 'connected' | 'connecting' | 'disconnected' | 'error';
accounts: ChannelAccountItem[];
}
export function Agents() {
const { t } = useTranslation('agents');
const gatewayStatus = useGatewayStore((state) => state.status);
@@ -36,21 +51,31 @@ export function Agents() {
createAgent,
deleteAgent,
} = useAgentsStore();
const { channels, fetchChannels } = useChannelsStore();
const [channelGroups, setChannelGroups] = useState<ChannelGroupItem[]>([]);
const [showAddDialog, setShowAddDialog] = useState(false);
const [activeAgentId, setActiveAgentId] = useState<string | null>(null);
const [agentToDelete, setAgentToDelete] = useState<AgentSummary | null>(null);
const fetchChannelAccounts = useCallback(async () => {
try {
const response = await hostApiFetch<{ success: boolean; channels?: ChannelGroupItem[] }>('/api/channels/accounts');
setChannelGroups(response.channels || []);
} catch {
setChannelGroups([]);
}
}, []);
useEffect(() => {
void Promise.all([fetchAgents(), fetchChannels()]);
}, [fetchAgents, fetchChannels]);
// eslint-disable-next-line react-hooks/set-state-in-effect
void Promise.all([fetchAgents(), fetchChannelAccounts()]);
}, [fetchAgents, fetchChannelAccounts]);
const activeAgent = useMemo(
() => agents.find((agent) => agent.id === activeAgentId) ?? null,
[activeAgentId, agents],
);
const handleRefresh = () => {
void Promise.all([fetchAgents(), fetchChannels()]);
void Promise.all([fetchAgents(), fetchChannelAccounts()]);
};
if (loading) {
@@ -117,6 +142,7 @@ export function Agents() {
<AgentCard
key={agent.id}
agent={agent}
channelGroups={channelGroups}
onOpenSettings={() => setActiveAgentId(agent.id)}
onDelete={() => setAgentToDelete(agent)}
/>
@@ -139,7 +165,7 @@ export function Agents() {
{activeAgent && (
<AgentSettingsModal
agent={activeAgent}
channels={channels}
channelGroups={channelGroups}
onClose={() => setActiveAgentId(null)}
/>
)}
@@ -173,16 +199,30 @@ export function Agents() {
function AgentCard({
agent,
channelGroups,
onOpenSettings,
onDelete,
}: {
agent: AgentSummary;
channelGroups: ChannelGroupItem[];
onOpenSettings: () => void;
onDelete: () => void;
}) {
const { t } = useTranslation('agents');
const channelsText = agent.channelTypes.length > 0
? agent.channelTypes.map((channelType) => CHANNEL_NAMES[channelType as ChannelType] || channelType).join(', ')
const boundChannelAccounts = channelGroups.flatMap((group) =>
group.accounts
.filter((account) => account.agentId === agent.id)
.map((account) => {
const channelName = CHANNEL_NAMES[group.channelType as ChannelType] || group.channelType;
const accountLabel =
account.accountId === 'default'
? t('settingsDialog.mainAccount')
: account.name || account.accountId;
return `${channelName} · ${accountLabel}`;
}),
);
const channelsText = boundChannelAccounts.length > 0
? boundChannelAccounts.join(', ')
: t('none');
return (
@@ -350,30 +390,22 @@ function AddAgentDialog({
function AgentSettingsModal({
agent,
channels,
channelGroups,
onClose,
}: {
agent: AgentSummary;
channels: Array<{ type: string; name: string; status: 'connected' | 'connecting' | 'disconnected' | 'error'; error?: string }>;
channelGroups: ChannelGroupItem[];
onClose: () => void;
}) {
const { t } = useTranslation('agents');
const { updateAgent, assignChannel, removeChannel } = useAgentsStore();
const { fetchChannels } = useChannelsStore();
const { updateAgent } = useAgentsStore();
const [name, setName] = useState(agent.name);
const [savingName, setSavingName] = useState(false);
const [showChannelModal, setShowChannelModal] = useState(false);
const [channelToRemove, setChannelToRemove] = useState<ChannelType | null>(null);
useEffect(() => {
setName(agent.name);
}, [agent.name]);
const runtimeChannelsByType = useMemo(
() => Object.fromEntries(channels.map((channel) => [channel.type, channel])),
[channels],
);
const handleSaveName = async () => {
if (!name.trim() || name.trim() === agent.name) return;
setSavingName(true);
@@ -387,26 +419,19 @@ function AgentSettingsModal({
}
};
const handleChannelSaved = async (channelType: ChannelType) => {
try {
await assignChannel(agent.id, channelType);
await fetchChannels();
toast.success(t('toast.channelAssigned', { channel: CHANNEL_NAMES[channelType] || channelType }));
} catch (error) {
toast.error(t('toast.channelAssignFailed', { error: String(error) }));
throw error;
}
};
const assignedChannels = agent.channelTypes.map((channelType) => {
const runtimeChannel = runtimeChannelsByType[channelType];
return {
channelType: channelType as ChannelType,
name: runtimeChannel?.name || CHANNEL_NAMES[channelType as ChannelType] || channelType,
status: runtimeChannel?.status || 'disconnected',
error: runtimeChannel?.error,
};
});
const assignedChannels = channelGroups.flatMap((group) =>
group.accounts
.filter((account) => account.agentId === agent.id)
.map((account) => ({
channelType: group.channelType as ChannelType,
accountId: account.accountId,
name:
account.accountId === 'default'
? t('settingsDialog.mainAccount')
: account.name || account.accountId,
error: account.lastError,
})),
);
return (
<div className="fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4">
@@ -485,23 +510,16 @@ function AgentSettingsModal({
</h3>
<p className="text-[14px] text-foreground/70 mt-1">{t('settingsDialog.channelsDescription')}</p>
</div>
<Button
onClick={() => setShowChannelModal(true)}
className="h-9 text-[13px] font-medium rounded-full px-4 shadow-none"
>
<Plus className="h-3.5 w-3.5 mr-2" />
{t('settingsDialog.addChannel')}
</Button>
</div>
{assignedChannels.length === 0 ? (
{assignedChannels.length === 0 && agent.channelTypes.length === 0 ? (
<div className="rounded-2xl border border-dashed border-black/10 dark:border-white/10 bg-black/5 dark:bg-white/5 p-4 text-[13.5px] text-muted-foreground">
{t('settingsDialog.noChannels')}
</div>
) : (
<div className="space-y-3">
{assignedChannels.map((channel) => (
<div key={channel.channelType} className="flex items-center justify-between rounded-2xl bg-black/5 dark:bg-white/5 border border-transparent p-4">
<div key={`${channel.channelType}-${channel.accountId}`} className="flex items-center justify-between rounded-2xl bg-black/5 dark:bg-white/5 border border-transparent p-4">
<div className="flex items-center gap-3 min-w-0">
<div className="h-[40px] w-[40px] shrink-0 flex items-center justify-center text-foreground bg-black/5 dark:bg-white/5 border border-black/5 dark:border-white/10 rounded-full shadow-sm">
<ChannelLogo type={channel.channelType} />
@@ -509,67 +527,26 @@ function AgentSettingsModal({
<div className="min-w-0">
<p className="text-[15px] font-semibold text-foreground">{channel.name}</p>
<p className="text-[13.5px] text-muted-foreground">
{CHANNEL_NAMES[channel.channelType]}
{CHANNEL_NAMES[channel.channelType]} · {channel.accountId === 'default' ? t('settingsDialog.mainAccount') : channel.accountId}
</p>
{channel.error && (
<p className="text-xs text-destructive mt-1">{channel.error}</p>
)}
</div>
</div>
<div className="flex items-center gap-2 shrink-0">
<StatusBadge status={channel.status} />
<Button
variant="ghost"
size="icon"
className="h-7 w-7 text-muted-foreground hover:text-destructive hover:bg-destructive/10"
onClick={() => setChannelToRemove(channel.channelType)}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
<div className="shrink-0" />
</div>
))}
{assignedChannels.length === 0 && agent.channelTypes.length > 0 && (
<div className="rounded-2xl border border-dashed border-black/10 dark:border-white/10 bg-black/5 dark:bg-white/5 p-4 text-[13.5px] text-muted-foreground">
{t('settingsDialog.channelsManagedInChannels')}
</div>
)}
</div>
)}
</div>
</CardContent>
</Card>
{showChannelModal && (
<ChannelConfigModal
configuredTypes={agent.channelTypes}
showChannelName={false}
allowExistingConfig
agentId={agent.id}
onClose={() => setShowChannelModal(false)}
onChannelSaved={async (channelType) => {
await handleChannelSaved(channelType);
setShowChannelModal(false);
}}
/>
)}
<ConfirmDialog
open={!!channelToRemove}
title={t('removeChannelDialog.title')}
message={channelToRemove ? t('removeChannelDialog.message', { name: CHANNEL_NAMES[channelToRemove] || channelToRemove }) : ''}
confirmLabel={t('common:actions.delete')}
cancelLabel={t('common:actions.cancel')}
variant="destructive"
onConfirm={async () => {
if (!channelToRemove) return;
try {
await removeChannel(agent.id, channelToRemove);
await fetchChannels();
toast.success(t('toast.channelRemoved', { channel: CHANNEL_NAMES[channelToRemove] || channelToRemove }));
} catch (error) {
toast.error(t('toast.channelRemoveFailed', { error: String(error) }));
} finally {
setChannelToRemove(null);
}
}}
onCancel={() => setChannelToRemove(null)}
/>
</div>
);
}

View File

@@ -1,13 +1,8 @@
/**
* Channels Page
* Manage messaging channel connections with configuration UI
*/
import { useState, useEffect, useCallback } from 'react';
import { RefreshCw, Trash2, AlertCircle } from 'lucide-react';
import { useState, useEffect, useCallback, useMemo } from 'react';
import { RefreshCw, Trash2, AlertCircle, Plus } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { useChannelsStore } from '@/stores/channels';
import { useGatewayStore } from '@/stores/gateway';
import { LoadingSpinner } from '@/components/common/LoadingSpinner';
import { hostApiFetch } from '@/lib/host-api';
@@ -20,9 +15,9 @@ import {
CHANNEL_META,
getPrimaryChannels,
type ChannelType,
type Channel,
} from '@/types/channel';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import telegramIcon from '@/assets/channels/telegram.svg';
import discordIcon from '@/assets/channels/discord.svg';
@@ -32,57 +27,182 @@ import feishuIcon from '@/assets/channels/feishu.svg';
import wecomIcon from '@/assets/channels/wecom.svg';
import qqIcon from '@/assets/channels/qq.svg';
interface ChannelAccountItem {
accountId: string;
name: string;
configured: boolean;
status: 'connected' | 'connecting' | 'disconnected' | 'error';
lastError?: string;
isDefault: boolean;
agentId?: string;
}
interface ChannelGroupItem {
channelType: string;
defaultAccountId: string;
status: 'connected' | 'connecting' | 'disconnected' | 'error';
accounts: ChannelAccountItem[];
}
interface AgentItem {
id: string;
name: string;
}
interface DeleteTarget {
channelType: string;
accountId?: string;
}
function removeDeletedTarget(groups: ChannelGroupItem[], target: DeleteTarget): ChannelGroupItem[] {
if (target.accountId) {
return groups
.map((group) => {
if (group.channelType !== target.channelType) return group;
return {
...group,
accounts: group.accounts.filter((account) => account.accountId !== target.accountId),
};
})
.filter((group) => group.accounts.length > 0);
}
return groups.filter((group) => group.channelType !== target.channelType);
}
export function Channels() {
const { t } = useTranslation('channels');
const { channels, loading, error, fetchChannels, deleteChannel } = useChannelsStore();
const gatewayStatus = useGatewayStore((state) => state.status);
const [showAddDialog, setShowAddDialog] = useState(false);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [channelGroups, setChannelGroups] = useState<ChannelGroupItem[]>([]);
const [agents, setAgents] = useState<AgentItem[]>([]);
const [showConfigModal, setShowConfigModal] = useState(false);
const [selectedChannelType, setSelectedChannelType] = useState<ChannelType | null>(null);
const [configuredTypes, setConfiguredTypes] = useState<string[]>([]);
const [channelToDelete, setChannelToDelete] = useState<{ id: string } | null>(null);
const [selectedAccountId, setSelectedAccountId] = useState<string | undefined>(undefined);
const [allowExistingConfigInModal, setAllowExistingConfigInModal] = useState(true);
const [allowEditAccountIdInModal, setAllowEditAccountIdInModal] = useState(false);
const [existingAccountIdsForModal, setExistingAccountIdsForModal] = useState<string[]>([]);
const [initialConfigValuesForModal, setInitialConfigValuesForModal] = useState<Record<string, string> | undefined>(undefined);
const [deleteTarget, setDeleteTarget] = useState<DeleteTarget | null>(null);
useEffect(() => {
void fetchChannels();
}, [fetchChannels]);
const displayedChannelTypes = getPrimaryChannels();
const fetchConfiguredTypes = useCallback(async () => {
const fetchPageData = useCallback(async () => {
setLoading(true);
setError(null);
try {
const result = await hostApiFetch<{
success: boolean;
channels?: string[];
}>('/api/channels/configured');
if (result.success && result.channels) {
setConfiguredTypes(result.channels);
const [channelsRes, agentsRes] = await Promise.all([
hostApiFetch<{ success: boolean; channels?: ChannelGroupItem[]; error?: string }>('/api/channels/accounts'),
hostApiFetch<{ success: boolean; agents?: AgentItem[]; error?: string }>('/api/agents'),
]);
if (!channelsRes.success) {
throw new Error(channelsRes.error || 'Failed to load channels');
}
} catch {
// Ignore refresh errors here and keep the last known state.
if (!agentsRes.success) {
throw new Error(agentsRes.error || 'Failed to load agents');
}
setChannelGroups(channelsRes.channels || []);
setAgents(agentsRes.agents || []);
} catch (fetchError) {
setError(String(fetchError));
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
const timer = window.setTimeout(() => {
void fetchConfiguredTypes();
}, 0);
return () => window.clearTimeout(timer);
}, [fetchConfiguredTypes]);
void fetchPageData();
}, [fetchPageData]);
useEffect(() => {
const unsubscribe = subscribeHostEvent('gateway:channel-status', () => {
void fetchChannels();
void fetchConfiguredTypes();
void fetchPageData();
});
return () => {
if (typeof unsubscribe === 'function') {
unsubscribe();
}
};
}, [fetchChannels, fetchConfiguredTypes]);
}, [fetchPageData]);
const displayedChannelTypes = getPrimaryChannels();
const configuredTypes = useMemo(
() => channelGroups.map((group) => group.channelType),
[channelGroups],
);
const groupedByType = useMemo(() => {
return Object.fromEntries(channelGroups.map((group) => [group.channelType, group]));
}, [channelGroups]);
const configuredGroups = useMemo(() => {
const known = displayedChannelTypes
.map((type) => groupedByType[type])
.filter((group): group is ChannelGroupItem => Boolean(group));
const unknown = channelGroups.filter((group) => !displayedChannelTypes.includes(group.channelType as ChannelType));
return [...known, ...unknown];
}, [channelGroups, displayedChannelTypes, groupedByType]);
const unsupportedGroups = displayedChannelTypes.filter((type) => !configuredTypes.includes(type));
const handleRefresh = () => {
void Promise.all([fetchChannels(), fetchConfiguredTypes()]);
void fetchPageData();
};
const handleBindAgent = async (channelType: string, accountId: string, agentId: string) => {
try {
if (!agentId) {
await hostApiFetch<{ success: boolean; error?: string }>('/api/channels/binding', {
method: 'DELETE',
body: JSON.stringify({ channelType, accountId }),
});
} else {
await hostApiFetch<{ success: boolean; error?: string }>('/api/channels/binding', {
method: 'PUT',
body: JSON.stringify({ channelType, accountId, agentId }),
});
}
await fetchPageData();
toast.success(t('toast.bindingUpdated'));
} catch (bindError) {
toast.error(t('toast.configFailed', { error: String(bindError) }));
}
};
const handleDelete = async () => {
if (!deleteTarget) return;
try {
const suffix = deleteTarget.accountId
? `?accountId=${encodeURIComponent(deleteTarget.accountId)}`
: '';
await hostApiFetch(`/api/channels/config/${encodeURIComponent(deleteTarget.channelType)}${suffix}`, {
method: 'DELETE',
});
setChannelGroups((prev) => removeDeletedTarget(prev, deleteTarget));
toast.success(deleteTarget.accountId ? t('toast.accountDeleted') : t('toast.channelDeleted'));
// Channel reload is debounced in main process; pull again shortly to
// converge with runtime state without flashing deleted rows back in.
window.setTimeout(() => {
void fetchPageData();
}, 1200);
} catch (deleteError) {
toast.error(t('toast.configFailed', { error: String(deleteError) }));
} finally {
setDeleteTarget(null);
}
};
const createNewAccountId = (channelType: string, existingAccounts: string[]): string => {
// Generate a collision-safe default account id for user editing.
let nextAccountId = `${channelType}-${crypto.randomUUID().slice(0, 8)}`;
while (existingAccounts.includes(nextAccountId)) {
nextAccountId = `${channelType}-${crypto.randomUUID().slice(0, 8)}`;
}
return nextAccountId;
};
if (loading) {
@@ -93,17 +213,6 @@ export function Channels() {
);
}
const safeChannels = Array.isArray(channels) ? channels : [];
const configuredPlaceholderChannels: Channel[] = displayedChannelTypes
.filter((type) => configuredTypes.includes(type) && !safeChannels.some((channel) => channel.type === type))
.map((type) => ({
id: `${type}-default`,
type,
name: CHANNEL_NAMES[type] || CHANNEL_META[type].name,
status: 'disconnected',
}));
const availableChannels = [...safeChannels, ...configuredPlaceholderChannels];
return (
<div className="flex flex-col -m-6 dark:bg-background h-[calc(100vh-2.5rem)] overflow-hidden">
<div className="w-full max-w-5xl mx-auto flex flex-col h-full p-10 pt-16">
@@ -124,7 +233,7 @@ export function Channels() {
disabled={gatewayStatus.state !== 'running'}
className="h-9 text-[13px] font-medium rounded-full px-4 border-black/10 dark:border-white/10 bg-transparent hover:bg-black/5 dark:hover:bg-white/5 shadow-none text-foreground/80 hover:text-foreground transition-colors"
>
<RefreshCw className={cn("h-3.5 w-3.5 mr-2", loading && "animate-spin")} />
<RefreshCw className="h-3.5 w-3.5 mr-2" />
{t('refresh')}
</Button>
</div>
@@ -149,22 +258,147 @@ export function Channels() {
</div>
)}
{availableChannels.length > 0 && (
{configuredGroups.length > 0 && (
<div className="mb-12">
<h2 className="text-3xl font-serif text-foreground mb-6 font-normal tracking-tight" style={{ fontFamily: 'Georgia, Cambria, "Times New Roman", Times, serif' }}>
{t('availableChannels')}
{t('configured')}
</h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-4">
{availableChannels.map((channel) => (
<ChannelCard
key={channel.id}
channel={channel}
onClick={() => {
setSelectedChannelType(channel.type);
setShowAddDialog(true);
}}
onDelete={() => setChannelToDelete({ id: channel.id })}
/>
<div className="space-y-4">
{configuredGroups.map((group) => (
<div key={group.channelType} className="rounded-2xl border border-black/10 dark:border-white/10 p-4 bg-transparent">
<div className="flex items-center justify-between gap-2 mb-3">
<div className="flex items-center gap-3 min-w-0">
<div className="h-[40px] w-[40px] shrink-0 flex items-center justify-center text-foreground bg-black/5 dark:bg-white/5 border border-black/5 dark:border-white/10 rounded-full shadow-sm">
<ChannelLogo type={group.channelType as ChannelType} />
</div>
<div className="min-w-0">
<h3 className="text-[16px] font-semibold text-foreground truncate">
{CHANNEL_NAMES[group.channelType as ChannelType] || group.channelType}
</h3>
<p className="text-[12px] text-muted-foreground">{group.channelType}</p>
</div>
<div
className={cn(
'w-2 h-2 rounded-full shrink-0',
group.status === 'connected'
? 'bg-green-500'
: group.status === 'connecting'
? 'bg-yellow-500 animate-pulse'
: group.status === 'error'
? 'bg-destructive'
: 'bg-muted-foreground'
)}
/>
</div>
<div className="flex items-center gap-2">
<Button
size="sm"
variant="outline"
className="h-8 text-xs rounded-full"
onClick={() => {
const nextAccountId = createNewAccountId(
group.channelType,
group.accounts.map((item) => item.accountId),
);
setSelectedChannelType(group.channelType as ChannelType);
setSelectedAccountId(nextAccountId);
setAllowExistingConfigInModal(false);
setAllowEditAccountIdInModal(true);
setExistingAccountIdsForModal(group.accounts.map((item) => item.accountId));
setInitialConfigValuesForModal(undefined);
setShowConfigModal(true);
}}
>
<Plus className="h-3.5 w-3.5 mr-1" />
{t('account.add')}
</Button>
<Button
size="icon"
variant="ghost"
className="h-7 w-7 text-muted-foreground hover:text-destructive hover:bg-destructive/10"
onClick={() => setDeleteTarget({ channelType: group.channelType })}
title={t('account.deleteChannel')}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
<div className="space-y-2">
{group.accounts.map((account) => {
const displayName =
account.accountId === 'default' && account.name === account.accountId
? t('account.mainAccount')
: account.name;
return (
<div key={`${group.channelType}-${account.accountId}`} className="rounded-xl bg-black/5 dark:bg-white/5 px-3 py-2">
<div className="flex items-center justify-between gap-3">
<div className="min-w-0">
<div className="flex items-center gap-2">
<p className="text-[13px] font-medium text-foreground truncate">{displayName}</p>
</div>
{account.lastError && (
<div className="text-[12px] text-destructive mt-1">{account.lastError}</div>
)}
</div>
<div className="flex items-center gap-2">
<select
className="h-8 rounded-lg border border-black/10 dark:border-white/10 bg-background px-2 text-xs"
value={account.agentId || ''}
onChange={(event) => {
void handleBindAgent(group.channelType, account.accountId, event.target.value);
}}
>
<option value="">{t('account.unassigned')}</option>
{agents.map((agent) => (
<option key={agent.id} value={agent.id}>{agent.name}</option>
))}
</select>
<Button
size="sm"
variant="outline"
className="h-8 text-xs rounded-full"
onClick={() => {
void (async () => {
try {
const accountParam = `?accountId=${encodeURIComponent(account.accountId)}`;
const result = await hostApiFetch<{ success: boolean; values?: Record<string, string> }>(
`/api/channels/config/${encodeURIComponent(group.channelType)}${accountParam}`
);
setInitialConfigValuesForModal(result.success ? (result.values || {}) : undefined);
} catch {
// Fall back to modal-side loading when prefetch fails.
setInitialConfigValuesForModal(undefined);
}
setSelectedChannelType(group.channelType as ChannelType);
setSelectedAccountId(account.accountId);
setAllowExistingConfigInModal(true);
setAllowEditAccountIdInModal(false);
setExistingAccountIdsForModal([]);
setShowConfigModal(true);
})();
}}
>
{t('account.edit')}
</Button>
<Button
size="icon"
variant="ghost"
className="h-7 w-7 text-muted-foreground hover:text-destructive hover:bg-destructive/10"
onClick={() => setDeleteTarget({ channelType: group.channelType, accountId: account.accountId })}
title={t('account.delete')}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
</div>
);
})}
</div>
</div>
))}
</div>
</div>
@@ -176,17 +410,19 @@ export function Channels() {
</h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-4">
{displayedChannelTypes.map((type) => {
{unsupportedGroups.map((type) => {
const meta = CHANNEL_META[type];
const isAvailable = availableChannels.some((channel) => channel.type === type);
if (isAvailable) return null;
return (
<button
key={type}
onClick={() => {
setSelectedChannelType(type);
setShowAddDialog(true);
setSelectedAccountId(undefined);
setAllowExistingConfigInModal(true);
setAllowEditAccountIdInModal(false);
setExistingAccountIdsForModal([]);
setInitialConfigValuesForModal(undefined);
setShowConfigModal(true);
}}
className={cn(
'group flex items-start gap-4 p-4 rounded-2xl transition-all text-left border relative overflow-hidden bg-transparent border-transparent hover:bg-black/5 dark:hover:bg-white/5'
@@ -216,38 +452,49 @@ export function Channels() {
</div>
</div>
{showAddDialog && (
{showConfigModal && (
<ChannelConfigModal
initialSelectedType={selectedChannelType}
accountId={selectedAccountId}
configuredTypes={configuredTypes}
allowExistingConfig={allowExistingConfigInModal}
allowEditAccountId={allowEditAccountIdInModal}
existingAccountIds={existingAccountIdsForModal}
initialConfigValues={initialConfigValuesForModal}
showChannelName={false}
onClose={() => {
setShowAddDialog(false);
setShowConfigModal(false);
setSelectedChannelType(null);
setSelectedAccountId(undefined);
setAllowExistingConfigInModal(true);
setAllowEditAccountIdInModal(false);
setExistingAccountIdsForModal([]);
setInitialConfigValuesForModal(undefined);
}}
onChannelSaved={async () => {
await Promise.all([fetchChannels(), fetchConfiguredTypes()]);
setShowAddDialog(false);
await fetchPageData();
setShowConfigModal(false);
setSelectedChannelType(null);
setSelectedAccountId(undefined);
setAllowExistingConfigInModal(true);
setAllowEditAccountIdInModal(false);
setExistingAccountIdsForModal([]);
setInitialConfigValuesForModal(undefined);
}}
/>
)}
<ConfirmDialog
open={!!channelToDelete}
open={!!deleteTarget}
title={t('common.confirm', 'Confirm')}
message={t('deleteConfirm')}
message={deleteTarget?.accountId ? t('account.deleteConfirm') : t('deleteConfirm')}
confirmLabel={t('common.delete', 'Delete')}
cancelLabel={t('common.cancel', 'Cancel')}
variant="destructive"
onConfirm={async () => {
if (channelToDelete) {
await deleteChannel(channelToDelete.id);
const [channelType] = channelToDelete.id.split('-');
setConfiguredTypes((prev) => prev.filter((type) => type !== channelType));
setChannelToDelete(null);
}
onConfirm={() => {
void handleDelete();
}}
onCancel={() => setChannelToDelete(null)}
onCancel={() => setDeleteTarget(null)}
/>
</div>
);
@@ -274,76 +521,4 @@ function ChannelLogo({ type }: { type: ChannelType }) {
}
}
interface ChannelCardProps {
channel: Channel;
onClick: () => void;
onDelete: () => void;
}
function ChannelCard({ channel, onClick, onDelete }: ChannelCardProps) {
const { t } = useTranslation('channels');
const meta = CHANNEL_META[channel.type];
return (
<div
onClick={onClick}
className="group flex items-start gap-4 p-4 rounded-2xl transition-all text-left border relative overflow-hidden bg-transparent border-transparent hover:bg-black/5 dark:hover:bg-white/5 cursor-pointer"
>
<div className="h-[46px] w-[46px] shrink-0 flex items-center justify-center text-foreground bg-black/5 dark:bg-white/5 border border-black/5 dark:border-white/10 rounded-full shadow-sm mb-3">
<ChannelLogo type={channel.type} />
</div>
<div className="flex flex-col flex-1 min-w-0 py-0.5 mt-1">
<div className="flex items-center justify-between gap-2 mb-1">
<div className="flex items-center gap-2 min-w-0">
<h3 className="text-[16px] font-semibold text-foreground truncate">{channel.name}</h3>
{meta?.isPlugin && (
<Badge
variant="secondary"
className="font-mono text-[10px] font-medium px-2 py-0.5 rounded-full bg-black/[0.04] dark:bg-white/[0.08] border-0 shadow-none text-foreground/70"
>
{t('pluginBadge', 'Plugin')}
</Badge>
)}
<div
className={cn(
'w-2 h-2 rounded-full shrink-0',
channel.status === 'connected'
? 'bg-green-500'
: channel.status === 'connecting'
? 'bg-yellow-500 animate-pulse'
: channel.status === 'error'
? 'bg-destructive'
: 'bg-muted-foreground'
)}
title={channel.status}
/>
</div>
<Button
variant="ghost"
size="icon"
className="opacity-0 group-hover:opacity-100 h-7 w-7 text-muted-foreground hover:text-destructive hover:bg-destructive/10 transition-all shrink-0 -mr-2"
onClick={(event) => {
event.stopPropagation();
onDelete();
}}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
{channel.error ? (
<p className="text-[13.5px] text-destructive line-clamp-2 leading-[1.5]">
{channel.error}
</p>
) : (
<p className="text-[13.5px] text-muted-foreground line-clamp-2 leading-[1.5]">
{meta ? t(meta.description.replace('channels:', '')) : CHANNEL_NAMES[channel.type]}
</p>
)}
</div>
</div>
);
}
export default Channels;

View File

@@ -8,6 +8,7 @@ interface AgentsState {
defaultAgentId: string;
configuredChannelTypes: string[];
channelOwners: Record<string, string>;
channelAccountOwners: Record<string, string>;
loading: boolean;
error: string | null;
fetchAgents: () => Promise<void>;
@@ -25,6 +26,7 @@ function applySnapshot(snapshot: AgentsSnapshot | undefined) {
defaultAgentId: snapshot.defaultAgentId,
configuredChannelTypes: snapshot.configuredChannelTypes,
channelOwners: snapshot.channelOwners,
channelAccountOwners: snapshot.channelAccountOwners,
} : {};
}
@@ -33,6 +35,7 @@ export const useAgentsStore = create<AgentsState>((set) => ({
defaultAgentId: 'main',
configuredChannelTypes: [],
channelOwners: {},
channelAccountOwners: {},
loading: false,
error: null,

View File

@@ -15,4 +15,5 @@ export interface AgentsSnapshot {
defaultAgentId: string;
configuredChannelTypes: string[];
channelOwners: Record<string, string>;
channelAccountOwners: Record<string, string>;
}