diff --git a/README.ja-JP.md b/README.ja-JP.md index 11664e63f..fe6c4c64c 100644 --- a/README.ja-JP.md +++ b/README.ja-JP.md @@ -103,6 +103,7 @@ ClawXは公式の**OpenClaw**コアを直接ベースに構築されています ### 📡 マルチチャネル管理 複数のAIチャネルを同時に設定・監視できます。各チャネルは独立して動作するため、異なるタスクに特化したエージェントを実行できます。 +現在は各チャンネルで複数アカウントを扱え、Channels ページでアカウントの Agent 紐付けやデフォルトアカウント切替を直接管理できます。 ### ⏰ Cronベースの自動化 AIタスクを自動的に実行するようスケジュール設定できます。トリガーを定義し、間隔を設定することで、手動介入なしにAIエージェントを24時間稼働させることができます。 diff --git a/README.md b/README.md index df5b9d9b4..930c14a22 100644 --- a/README.md +++ b/README.md @@ -103,6 +103,7 @@ When you target another agent with `@agent`, ClawX switches into that agent's ow ### 📡 Multi-Channel Management Configure and monitor multiple AI channels simultaneously. Each channel operates independently, allowing you to run specialized agents for different tasks. +Each channel now supports multiple accounts, per-account agent binding, and switching the channel default account directly from the Channels page. ### ⏰ Cron-Based Automation Schedule AI tasks to run automatically. Define triggers, set intervals, and let your AI agents work around the clock without manual intervention. diff --git a/README.zh-CN.md b/README.zh-CN.md index 4253f9e8f..13d93c2bc 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -104,6 +104,7 @@ ClawX 直接基于官方 **OpenClaw** 核心构建。无需单独安装,我们 ### 📡 多频道管理 同时配置和监控多个 AI 频道。每个频道独立运行,允许你为不同任务运行专门的智能体。 +现在每个频道支持多个账号,并可在 Channels 页面直接完成账号绑定到 Agent 与默认账号切换。 ### ⏰ 定时任务自动化 调度 AI 任务自动执行。定义触发器、设置时间间隔,让 AI 智能体 7×24 小时不间断工作。 diff --git a/electron/api/routes/agents.ts b/electron/api/routes/agents.ts index 963c0e108..e5dbbdb7d 100644 --- a/electron/api/routes/agents.ts +++ b/electron/api/routes/agents.ts @@ -188,9 +188,27 @@ export async function handleAgentRoutes( try { const agentId = decodeURIComponent(parts[0]); const channelType = decodeURIComponent(parts[2]); - const accountId = resolveAccountIdForAgent(agentId); - await deleteChannelAccountConfig(channelType, accountId); - const snapshot = await clearChannelBinding(channelType, accountId); + const ownerId = agentId.trim().toLowerCase(); + const snapshotBefore = await listAgentsSnapshot(); + const ownedAccountIds = Object.entries(snapshotBefore.channelAccountOwners) + .filter(([channelAccountKey, owner]) => { + if (owner !== ownerId) return false; + return channelAccountKey.startsWith(`${channelType}:`); + }) + .map(([channelAccountKey]) => channelAccountKey.slice(channelAccountKey.indexOf(':') + 1)); + // Backward compatibility for legacy agentId->accountId mapping. + if (ownedAccountIds.length === 0) { + const legacyAccountId = resolveAccountIdForAgent(agentId); + if (snapshotBefore.channelAccountOwners[`${channelType}:${legacyAccountId}`] === ownerId) { + ownedAccountIds.push(legacyAccountId); + } + } + + for (const accountId of ownedAccountIds) { + await deleteChannelAccountConfig(channelType, accountId); + await clearChannelBinding(channelType, accountId); + } + const snapshot = await listAgentsSnapshot(); scheduleGatewayReload(ctx, 'remove-agent-channel'); sendJson(res, 200, { success: true, ...snapshot }); } catch (error) { diff --git a/electron/api/routes/channels.ts b/electron/api/routes/channels.ts index 755ded5b5..ff8deedaa 100644 --- a/electron/api/routes/channels.ts +++ b/electron/api/routes/channels.ts @@ -1,20 +1,29 @@ import type { IncomingMessage, ServerResponse } from 'http'; import { + deleteChannelAccountConfig, deleteChannelConfig, getChannelFormValues, + listConfiguredChannelAccounts, listConfiguredChannels, + readOpenClawConfig, saveChannelConfig, + setChannelDefaultAccount, setChannelEnabled, validateChannelConfig, validateChannelCredentials, } from '../../utils/channel-config'; +import { + assignChannelAccountToAgent, + clearAllBindingsForChannel, + clearChannelBinding, + listAgentsSnapshot, +} from '../../utils/agent-config'; import { ensureDingTalkPluginInstalled, ensureFeishuPluginInstalled, ensureQQBotPluginInstalled, ensureWeComPluginInstalled, } from '../../utils/plugin-install'; -import { assignChannelToAgent, clearAllBindingsForChannel } from '../../utils/agent-config'; import { whatsAppLoginManager } from '../../utils/whatsapp-login'; import type { HostApiContext } from '../context'; import { parseJsonBody, sendJson } from '../route-utils'; @@ -79,16 +88,167 @@ function isSameConfigValues( return true; } -function inferAgentIdFromAccountId(accountId: string): string { - if (accountId === 'default') return 'main'; - return accountId; -} - async function ensureScopedChannelBinding(channelType: string, accountId?: string): Promise { // Multi-agent safety: only bind when the caller explicitly scopes the account. // Global channel saves (no accountId) must not override routing to "main". if (!accountId) return; - await assignChannelToAgent(inferAgentIdFromAccountId(accountId), channelType).catch(() => undefined); + const agents = await listAgentsSnapshot(); + if (!agents.entries || agents.entries.length === 0) return; + + // Keep backward compatibility for the legacy default account. + if (accountId === 'default') { + if (agents.entries.some((entry) => entry.id === 'main')) { + await assignChannelAccountToAgent('main', channelType, 'default'); + } + return; + } + + // Legacy compatibility: if accountId matches an existing agentId, keep auto-binding. + if (agents.entries.some((entry) => entry.id === accountId)) { + await assignChannelAccountToAgent(accountId, channelType, accountId); + } +} + +interface GatewayChannelStatusPayload { + channelOrder?: string[]; + channels?: Record; + channelAccounts?: Record>; + channelDefaultAccountId?: Record; +} + +interface ChannelAccountView { + accountId: string; + name: string; + configured: boolean; + connected: boolean; + running: boolean; + linked: boolean; + lastError?: string; + status: 'connected' | 'connecting' | 'disconnected' | 'error'; + isDefault: boolean; + agentId?: string; +} + +interface ChannelAccountsView { + channelType: string; + defaultAccountId: string; + status: 'connected' | 'connecting' | 'disconnected' | 'error'; + accounts: ChannelAccountView[]; +} + +function computeAccountStatus(account: { + connected?: boolean; + linked?: boolean; + running?: boolean; + lastError?: string; + lastConnectedAt?: number | null; + lastInboundAt?: number | null; + lastOutboundAt?: number | null; +}): 'connected' | 'connecting' | 'disconnected' | 'error' { + const now = Date.now(); + const recentMs = 10 * 60 * 1000; + const hasRecentActivity = + (typeof account.lastInboundAt === 'number' && now - account.lastInboundAt < recentMs) + || (typeof account.lastOutboundAt === 'number' && now - account.lastOutboundAt < recentMs) + || (typeof account.lastConnectedAt === 'number' && now - account.lastConnectedAt < recentMs); + + if (account.connected === true || account.linked === true || hasRecentActivity) return 'connected'; + if (account.running === true && !account.lastError) return 'connecting'; + if (account.lastError) return 'error'; + return 'disconnected'; +} + +function pickChannelStatus(accounts: ChannelAccountView[]): 'connected' | 'connecting' | 'disconnected' | 'error' { + if (accounts.some((account) => account.status === 'connected')) return 'connected'; + if (accounts.some((account) => account.status === 'error')) return 'error'; + if (accounts.some((account) => account.status === 'connecting')) return 'connecting'; + return 'disconnected'; +} + +async function buildChannelAccountsView(ctx: HostApiContext): Promise { + const [configuredChannels, configuredAccounts, openClawConfig, agentsSnapshot] = await Promise.all([ + listConfiguredChannels(), + listConfiguredChannelAccounts(), + readOpenClawConfig(), + listAgentsSnapshot(), + ]); + + let gatewayStatus: GatewayChannelStatusPayload | null; + try { + gatewayStatus = await ctx.gatewayManager.rpc('channels.status', { probe: true }); + } catch { + gatewayStatus = null; + } + + const channelTypes = new Set([ + ...configuredChannels, + ...Object.keys(configuredAccounts), + ...Object.keys(gatewayStatus?.channelAccounts || {}), + ]); + + const channels: ChannelAccountsView[] = []; + for (const channelType of channelTypes) { + const channelAccountsFromConfig = configuredAccounts[channelType]?.accountIds ?? []; + const hasLocalConfig = configuredChannels.includes(channelType) || Boolean(configuredAccounts[channelType]); + const channelSection = openClawConfig.channels?.[channelType]; + const fallbackDefault = + typeof channelSection?.defaultAccount === 'string' && channelSection.defaultAccount.trim() + ? channelSection.defaultAccount + : 'default'; + const defaultAccountId = configuredAccounts[channelType]?.defaultAccountId + ?? gatewayStatus?.channelDefaultAccountId?.[channelType] + ?? fallbackDefault; + const runtimeAccounts = gatewayStatus?.channelAccounts?.[channelType] ?? []; + const hasRuntimeConfigured = runtimeAccounts.some((account) => account.configured === true); + if (!hasLocalConfig && !hasRuntimeConfigured) { + continue; + } + const runtimeAccountIds = runtimeAccounts + .map((account) => account.accountId) + .filter((accountId): accountId is string => typeof accountId === 'string' && accountId.trim().length > 0); + const accountIds = Array.from(new Set([...channelAccountsFromConfig, ...runtimeAccountIds, defaultAccountId])); + + const accounts: ChannelAccountView[] = accountIds.map((accountId) => { + const runtime = runtimeAccounts.find((item) => item.accountId === accountId); + const status = computeAccountStatus(runtime ?? {}); + return { + accountId, + name: runtime?.name || accountId, + configured: channelAccountsFromConfig.includes(accountId) || runtime?.configured === true, + connected: runtime?.connected === true, + running: runtime?.running === true, + linked: runtime?.linked === true, + lastError: typeof runtime?.lastError === 'string' ? runtime.lastError : undefined, + status, + isDefault: accountId === defaultAccountId, + agentId: agentsSnapshot.channelAccountOwners[`${channelType}:${accountId}`], + }; + }).sort((left, right) => { + if (left.accountId === defaultAccountId) return -1; + if (right.accountId === defaultAccountId) return 1; + return left.accountId.localeCompare(right.accountId); + }); + + channels.push({ + channelType, + defaultAccountId, + status: pickChannelStatus(accounts), + accounts, + }); + } + + return channels.sort((left, right) => left.channelType.localeCompare(right.channelType)); } export async function handleChannelRoutes( @@ -102,6 +262,52 @@ export async function handleChannelRoutes( return true; } + if (url.pathname === '/api/channels/accounts' && req.method === 'GET') { + try { + const channels = await buildChannelAccountsView(ctx); + sendJson(res, 200, { success: true, channels }); + } catch (error) { + sendJson(res, 500, { success: false, error: String(error) }); + } + return true; + } + + if (url.pathname === '/api/channels/default-account' && req.method === 'PUT') { + try { + const body = await parseJsonBody<{ channelType: string; accountId: string }>(req); + await setChannelDefaultAccount(body.channelType, body.accountId); + scheduleGatewayChannelSaveRefresh(ctx, body.channelType, `channel:setDefaultAccount:${body.channelType}`); + sendJson(res, 200, { success: true }); + } catch (error) { + sendJson(res, 500, { success: false, error: String(error) }); + } + return true; + } + + if (url.pathname === '/api/channels/binding' && req.method === 'PUT') { + try { + const body = await parseJsonBody<{ channelType: string; accountId: string; agentId: string }>(req); + await assignChannelAccountToAgent(body.agentId, body.channelType, body.accountId); + scheduleGatewayChannelSaveRefresh(ctx, body.channelType, `channel:setBinding:${body.channelType}`); + sendJson(res, 200, { success: true }); + } catch (error) { + sendJson(res, 500, { success: false, error: String(error) }); + } + return true; + } + + if (url.pathname === '/api/channels/binding' && req.method === 'DELETE') { + try { + const body = await parseJsonBody<{ channelType: string; accountId: string }>(req); + await clearChannelBinding(body.channelType, body.accountId); + scheduleGatewayChannelSaveRefresh(ctx, body.channelType, `channel:clearBinding:${body.channelType}`); + sendJson(res, 200, { success: true }); + } catch (error) { + sendJson(res, 500, { success: false, error: String(error) }); + } + return true; + } + if (url.pathname === '/api/channels/config/validate' && req.method === 'POST') { try { const body = await parseJsonBody<{ channelType: string }>(req); @@ -219,9 +425,16 @@ export async function handleChannelRoutes( if (url.pathname.startsWith('/api/channels/config/') && req.method === 'DELETE') { try { const channelType = decodeURIComponent(url.pathname.slice('/api/channels/config/'.length)); - await deleteChannelConfig(channelType); - await clearAllBindingsForChannel(channelType); - scheduleGatewayChannelRestart(ctx, `channel:deleteConfig:${channelType}`); + const accountId = url.searchParams.get('accountId') || undefined; + if (accountId) { + await deleteChannelAccountConfig(channelType, accountId); + await clearChannelBinding(channelType, accountId); + scheduleGatewayChannelSaveRefresh(ctx, channelType, `channel:deleteAccount:${channelType}`); + } else { + await deleteChannelConfig(channelType); + await clearAllBindingsForChannel(channelType); + scheduleGatewayChannelRestart(ctx, `channel:deleteConfig:${channelType}`); + } sendJson(res, 200, { success: true }); } catch (error) { sendJson(res, 500, { success: false, error: String(error) }); diff --git a/electron/utils/agent-config.ts b/electron/utils/agent-config.ts index 49c9b7aaf..fd6ae31e1 100644 --- a/electron/utils/agent-config.ts +++ b/electron/utils/agent-config.ts @@ -92,6 +92,7 @@ export interface AgentsSnapshot { defaultAgentId: string; configuredChannelTypes: string[]; channelOwners: Record; + channelAccountOwners: Record; } function formatModelLabel(model: unknown): string | null { @@ -266,10 +267,16 @@ function upsertBindingsForChannel( agentId: string | null, accountId?: string, ): BindingConfig[] | undefined { + const normalizedAgentId = agentId ? normalizeAgentIdForBinding(agentId) : ''; const nextBindings = Array.isArray(bindings) ? [...bindings as BindingConfig[]].filter((binding) => { if (!isChannelBinding(binding)) return true; if (binding.match?.channel !== channelType) return true; + // Keep a single account binding per (agent, channelType). Rebinding to + // another account should replace the previous one. + if (normalizedAgentId && normalizeAgentIdForBinding(binding.agentId || '') === normalizedAgentId) { + return false; + } // Only remove binding that matches the exact accountId scope if (accountId) { return binding.match?.accountId !== accountId; @@ -290,6 +297,30 @@ function upsertBindingsForChannel( return nextBindings.length > 0 ? nextBindings : undefined; } +function assertAgentNotBoundToOtherChannel( + bindings: unknown, + agentId: string, + nextChannelType: string, +): void { + if (!Array.isArray(bindings)) return; + const normalizedAgentId = normalizeAgentIdForBinding(agentId); + if (!normalizedAgentId) return; + + const conflictChannels = new Set(); + for (const binding of bindings) { + if (!isChannelBinding(binding)) continue; + if (normalizeAgentIdForBinding(binding.agentId || '') !== normalizedAgentId) continue; + const boundChannel = binding.match?.channel; + if (!boundChannel || boundChannel === nextChannelType) continue; + conflictChannels.add(boundChannel); + } + + if (conflictChannels.size > 0) { + const channels = Array.from(conflictChannels).sort().join(', '); + throw new Error(`Agent "${agentId}" is already bound to channel(s): ${channels}. One agent can only bind one channel.`); + } +} + async function listExistingAgentIdsOnDisk(): Promise> { const ids = new Set(); const agentsDir = join(getOpenClawConfigDir(), 'agents'); @@ -429,6 +460,7 @@ async function buildSnapshotFromConfig(config: AgentConfigDocument): Promise = {}; + const channelAccountOwners: Record = {}; // Build per-agent channel lists from account-scoped bindings const agentChannelSets = new Map>(); @@ -436,16 +468,24 @@ async function buildSnapshotFromConfig(config: AgentConfigDocument): Promise + accountToAgent.has(`${channelType}:${accountId}`), + ); for (const accountId of accountIds) { const owner = accountToAgent.get(`${channelType}:${accountId}`) - || (accountId === DEFAULT_ACCOUNT_ID ? (channelToAgent.get(channelType) || defaultAgentIdNorm) : undefined); + || ( + accountId === DEFAULT_ACCOUNT_ID && !hasExplicitAccountBindingForChannel + ? (channelToAgent.get(channelType) || defaultAgentIdNorm) + : undefined + ); if (!owner) { continue; } + channelAccountOwners[`${channelType}:${accountId}`] = owner; primaryOwner ??= owner; const existing = agentChannelSets.get(owner) ?? new Set(); existing.add(channelType); @@ -486,6 +526,7 @@ async function buildSnapshotFromConfig(config: AgentConfigDocument): Promise entry.id === agentId); const nextEntries = entries.filter((entry) => entry.id !== agentId); if (!removedEntry || nextEntries.length === entries.length) { @@ -596,8 +638,20 @@ export async function deleteAgentConfig(agentId: string): Promise<{ snapshot: Ag }; } + const normalizedAgentId = normalizeAgentIdForBinding(agentId); + const legacyAccountId = resolveAccountIdForAgent(agentId); + const ownedLegacyAccounts = new Set( + Object.entries(snapshotBeforeDeletion.channelAccountOwners) + .filter(([channelAccountKey, owner]) => { + if (owner !== normalizedAgentId) return false; + const accountId = channelAccountKey.slice(channelAccountKey.indexOf(':') + 1); + return accountId === legacyAccountId; + }) + .map(([channelAccountKey]) => channelAccountKey), + ); + await writeOpenClawConfig(config); - await deleteAgentChannelAccounts(agentId); + await deleteAgentChannelAccounts(agentId, ownedLegacyAccounts); await removeAgentRuntimeDirectory(agentId); // NOTE: workspace directory is NOT deleted here intentionally. // The caller (route handler) defers workspace removal until after @@ -618,6 +672,7 @@ export async function assignChannelToAgent(agentId: string, channelType: string) throw new Error(`Agent "${agentId}" not found`); } + assertAgentNotBoundToOtherChannel(config.bindings, agentId, channelType); const accountId = resolveAccountIdForAgent(agentId); config.bindings = upsertBindingsForChannel(config.bindings, channelType, agentId, accountId); await writeOpenClawConfig(config); @@ -626,6 +681,29 @@ export async function assignChannelToAgent(agentId: string, channelType: string) }); } +export async function assignChannelAccountToAgent( + agentId: string, + channelType: string, + accountId: string, +): Promise { + return withConfigLock(async () => { + const config = await readOpenClawConfig() as AgentConfigDocument; + const { entries } = normalizeAgentsConfig(config); + if (!entries.some((entry) => entry.id === agentId)) { + throw new Error(`Agent "${agentId}" not found`); + } + if (!accountId.trim()) { + throw new Error('accountId is required'); + } + + assertAgentNotBoundToOtherChannel(config.bindings, agentId, channelType); + config.bindings = upsertBindingsForChannel(config.bindings, channelType, agentId, accountId.trim()); + await writeOpenClawConfig(config); + logger.info('Assigned channel account to agent', { agentId, channelType, accountId: accountId.trim() }); + return buildSnapshotFromConfig(config); + }); +} + export async function clearChannelBinding(channelType: string, accountId?: string): Promise { return withConfigLock(async () => { const config = await readOpenClawConfig() as AgentConfigDocument; diff --git a/electron/utils/channel-config.ts b/electron/utils/channel-config.ts index 83fe95a50..ba3ea9d62 100644 --- a/electron/utils/channel-config.ts +++ b/electron/utils/channel-config.ts @@ -16,8 +16,7 @@ import { withConfigLock } from './config-mutex'; const OPENCLAW_DIR = join(homedir(), '.openclaw'); const CONFIG_FILE = join(OPENCLAW_DIR, 'openclaw.json'); const WECOM_PLUGIN_ID = 'wecom'; -const FEISHU_PLUGIN_ID = 'openclaw-lark'; -const LEGACY_FEISHU_PLUGIN_ID = 'feishu-openclaw-plugin'; +const FEISHU_PLUGIN_ID_CANDIDATES = ['openclaw-lark', 'feishu-openclaw-plugin'] as const; const DEFAULT_ACCOUNT_ID = 'default'; const CHANNEL_TOP_LEVEL_KEYS_TO_KEEP = new Set(['accounts', 'defaultAccount', 'enabled']); @@ -53,6 +52,24 @@ function normalizeCredentialValue(value: string): string { return value.trim(); } +async function resolveFeishuPluginId(): Promise { + const extensionRoot = join(homedir(), '.openclaw', 'extensions'); + for (const dirName of FEISHU_PLUGIN_ID_CANDIDATES) { + const manifestPath = join(extensionRoot, dirName, 'openclaw.plugin.json'); + try { + const raw = await readFile(manifestPath, 'utf-8'); + const parsed = JSON.parse(raw) as { id?: unknown }; + if (typeof parsed.id === 'string' && parsed.id.trim()) { + return parsed.id.trim(); + } + } catch { + // ignore and try next candidate + } + } + // Fallback to the modern id when extension manifests are not available yet. + return FEISHU_PLUGIN_ID_CANDIDATES[0]; +} + // ── Types ──────────────────────────────────────────────────────── export interface ChannelConfigData { @@ -121,14 +138,15 @@ export async function writeOpenClawConfig(config: OpenClawConfig): Promise // ── Channel operations ─────────────────────────────────────────── -function ensurePluginAllowlist(currentConfig: OpenClawConfig, channelType: string): void { +async function ensurePluginAllowlist(currentConfig: OpenClawConfig, channelType: string): Promise { if (channelType === 'feishu') { + const feishuPluginId = await resolveFeishuPluginId(); if (!currentConfig.plugins) { currentConfig.plugins = { - allow: [FEISHU_PLUGIN_ID], + allow: [feishuPluginId], enabled: true, entries: { - [FEISHU_PLUGIN_ID]: { enabled: true } + [feishuPluginId]: { enabled: true } } }; } else { @@ -136,12 +154,12 @@ function ensurePluginAllowlist(currentConfig: OpenClawConfig, channelType: strin const allow: string[] = Array.isArray(currentConfig.plugins.allow) ? (currentConfig.plugins.allow as string[]) : []; - // Remove legacy IDs: 'feishu' (built-in) and old 'feishu-openclaw-plugin' + // Keep only one active feishu plugin id to avoid doctor validation conflicts. const normalizedAllow = allow.filter( - (pluginId) => pluginId !== 'feishu' && pluginId !== LEGACY_FEISHU_PLUGIN_ID + (pluginId) => pluginId !== 'feishu' && !FEISHU_PLUGIN_ID_CANDIDATES.includes(pluginId as typeof FEISHU_PLUGIN_ID_CANDIDATES[number]) ); - if (!normalizedAllow.includes(FEISHU_PLUGIN_ID)) { - currentConfig.plugins.allow = [...normalizedAllow, FEISHU_PLUGIN_ID]; + if (!normalizedAllow.includes(feishuPluginId)) { + currentConfig.plugins.allow = [...normalizedAllow, feishuPluginId]; } else if (normalizedAllow.length !== allow.length) { currentConfig.plugins.allow = normalizedAllow; } @@ -149,14 +167,18 @@ function ensurePluginAllowlist(currentConfig: OpenClawConfig, channelType: strin if (!currentConfig.plugins.entries) { currentConfig.plugins.entries = {}; } - // Remove legacy entries that would conflict with the current plugin ID + // Remove conflicting feishu entries; keep only the resolved plugin id. delete currentConfig.plugins.entries['feishu']; - delete currentConfig.plugins.entries[LEGACY_FEISHU_PLUGIN_ID]; - - if (!currentConfig.plugins.entries[FEISHU_PLUGIN_ID]) { - currentConfig.plugins.entries[FEISHU_PLUGIN_ID] = {}; + for (const candidateId of FEISHU_PLUGIN_ID_CANDIDATES) { + if (candidateId !== feishuPluginId) { + delete currentConfig.plugins.entries[candidateId]; + } } - currentConfig.plugins.entries[FEISHU_PLUGIN_ID].enabled = true; + + if (!currentConfig.plugins.entries[feishuPluginId]) { + currentConfig.plugins.entries[feishuPluginId] = {}; + } + currentConfig.plugins.entries[feishuPluginId].enabled = true; } } @@ -407,7 +429,7 @@ export async function saveChannelConfig( const currentConfig = await readOpenClawConfig(); const resolvedAccountId = accountId || DEFAULT_ACCOUNT_ID; - ensurePluginAllowlist(currentConfig, channelType); + await ensurePluginAllowlist(currentConfig, channelType); // Plugin-based channels (e.g. WhatsApp) go under plugins.entries, not channels if (PLUGIN_CHANNELS.includes(channelType)) { @@ -587,9 +609,23 @@ export async function deleteChannelAccountConfig(channelType: string, accountId: if (Object.keys(accounts).length === 0) { delete currentConfig.channels![channelType]; } else { + if (channelSection.defaultAccount === accountId) { + const nextDefaultAccountId = Object.keys(accounts).sort((a, b) => { + if (a === DEFAULT_ACCOUNT_ID) return -1; + if (b === DEFAULT_ACCOUNT_ID) return 1; + return a.localeCompare(b); + })[0]; + if (nextDefaultAccountId) { + channelSection.defaultAccount = nextDefaultAccountId; + } + } // Re-mirror default account credentials to top level after migration // stripped them (same rationale as saveChannelConfig). - const defaultAccountData = accounts[DEFAULT_ACCOUNT_ID]; + const mirroredAccountId = + typeof channelSection.defaultAccount === 'string' && channelSection.defaultAccount.trim() + ? channelSection.defaultAccount + : DEFAULT_ACCOUNT_ID; + const defaultAccountData = accounts[mirroredAccountId] ?? accounts[DEFAULT_ACCOUNT_ID]; if (defaultAccountData) { for (const [key, value] of Object.entries(defaultAccountData)) { channelSection[key] = value; @@ -686,7 +722,85 @@ export async function listConfiguredChannels(): Promise { return channels; } -export async function deleteAgentChannelAccounts(agentId: string): Promise { +export interface ConfiguredChannelAccounts { + defaultAccountId: string; + accountIds: string[]; +} + +export async function listConfiguredChannelAccounts(): Promise> { + const config = await readOpenClawConfig(); + const result: Record = {}; + + if (!config.channels) { + return result; + } + + for (const [channelType, section] of Object.entries(config.channels)) { + if (!section || section.enabled === false) continue; + + const accountIds = section.accounts && typeof section.accounts === 'object' + ? Object.keys(section.accounts).filter(Boolean) + : []; + + const defaultAccountId = typeof section.defaultAccount === 'string' && section.defaultAccount.trim() + ? section.defaultAccount + : DEFAULT_ACCOUNT_ID; + + if (accountIds.length === 0) { + const hasAnyPayload = Object.keys(section).some((key) => !CHANNEL_TOP_LEVEL_KEYS_TO_KEEP.has(key)); + if (!hasAnyPayload) continue; + result[channelType] = { + defaultAccountId, + accountIds: [DEFAULT_ACCOUNT_ID], + }; + continue; + } + + result[channelType] = { + defaultAccountId, + accountIds: accountIds.sort((a, b) => { + if (a === DEFAULT_ACCOUNT_ID) return -1; + if (b === DEFAULT_ACCOUNT_ID) return 1; + return a.localeCompare(b); + }), + }; + } + + return result; +} + +export async function setChannelDefaultAccount(channelType: string, accountId: string): Promise { + return withConfigLock(async () => { + const trimmedAccountId = accountId.trim(); + if (!trimmedAccountId) { + throw new Error('accountId is required'); + } + + const currentConfig = await readOpenClawConfig(); + const channelSection = currentConfig.channels?.[channelType]; + if (!channelSection) { + throw new Error(`Channel "${channelType}" is not configured`); + } + + migrateLegacyChannelConfigToAccounts(channelSection, DEFAULT_ACCOUNT_ID); + const accounts = channelSection.accounts as Record | undefined; + if (!accounts || !accounts[trimmedAccountId]) { + throw new Error(`Account "${trimmedAccountId}" is not configured for channel "${channelType}"`); + } + + channelSection.defaultAccount = trimmedAccountId; + + const defaultAccountData = accounts[trimmedAccountId]; + for (const [key, value] of Object.entries(defaultAccountData)) { + channelSection[key] = value; + } + + await writeOpenClawConfig(currentConfig); + logger.info('Set channel default account', { channelType, accountId: trimmedAccountId }); + }); +} + +export async function deleteAgentChannelAccounts(agentId: string, ownedChannelAccounts?: Set): Promise { return withConfigLock(async () => { const currentConfig = await readOpenClawConfig(); if (!currentConfig.channels) return; @@ -699,14 +813,31 @@ export async function deleteAgentChannelAccounts(agentId: string): Promise migrateLegacyChannelConfigToAccounts(section, DEFAULT_ACCOUNT_ID); const accounts = section.accounts as Record | undefined; if (!accounts?.[accountId]) continue; + if (ownedChannelAccounts && !ownedChannelAccounts.has(`${channelType}:${accountId}`)) { + continue; + } delete accounts[accountId]; if (Object.keys(accounts).length === 0) { delete currentConfig.channels[channelType]; } else { + if (section.defaultAccount === accountId) { + const nextDefaultAccountId = Object.keys(accounts).sort((a, b) => { + if (a === DEFAULT_ACCOUNT_ID) return -1; + if (b === DEFAULT_ACCOUNT_ID) return 1; + return a.localeCompare(b); + })[0]; + if (nextDefaultAccountId) { + section.defaultAccount = nextDefaultAccountId; + } + } // Re-mirror default account credentials to top level after migration // stripped them (same rationale as saveChannelConfig). - const defaultAccountData = accounts[DEFAULT_ACCOUNT_ID]; + const mirroredAccountId = + typeof section.defaultAccount === 'string' && section.defaultAccount.trim() + ? section.defaultAccount + : DEFAULT_ACCOUNT_ID; + const defaultAccountData = accounts[mirroredAccountId] ?? accounts[DEFAULT_ACCOUNT_ID]; if (defaultAccountData) { for (const [key, value] of Object.entries(defaultAccountData)) { section[key] = value; diff --git a/electron/utils/openclaw-auth.ts b/electron/utils/openclaw-auth.ts index 330f45ebc..730cf59a9 100644 --- a/electron/utils/openclaw-auth.ts +++ b/electron/utils/openclaw-auth.ts @@ -131,12 +131,25 @@ async function discoverAgentIds(): Promise { // ── OpenClaw Config Helpers ────────────────────────────────────── const OPENCLAW_CONFIG_PATH = join(homedir(), '.openclaw', 'openclaw.json'); +const FEISHU_PLUGIN_ID_CANDIDATES = ['openclaw-lark', 'feishu-openclaw-plugin'] as const; const VALID_COMPACTION_MODES = new Set(['default', 'safeguard']); async function readOpenClawJson(): Promise> { return (await readJsonFile>(OPENCLAW_CONFIG_PATH)) ?? {}; } +async function resolveInstalledFeishuPluginId(): Promise { + const extensionRoot = join(homedir(), '.openclaw', 'extensions'); + for (const dirName of FEISHU_PLUGIN_ID_CANDIDATES) { + const manifestPath = join(extensionRoot, dirName, 'openclaw.plugin.json'); + const manifest = await readJsonFile<{ id?: unknown }>(manifestPath); + if (typeof manifest?.id === 'string' && manifest.id.trim()) { + return manifest.id.trim(); + } + } + return null; +} + function normalizeAgentsDefaultsCompactionMode(config: Record): void { const agents = (config.agents && typeof config.agents === 'object' ? config.agents as Record @@ -1016,44 +1029,59 @@ export async function sanitizeOpenClawConfig(): Promise { } // ── plugins.entries.feishu cleanup ────────────────────────────── - // The official feishu plugin registers its channel AS 'feishu' via - // openclaw.plugin.json. An explicit entries.feishu.enabled=false - // (set by older ClawX to disable the legacy built-in) blocks the - // official plugin's channel from starting. Only clean up when the - // new openclaw-lark plugin is already configured (to avoid removing - // a legitimate old-style feishu plugin from users who haven't upgraded). + // Normalize feishu plugin ids dynamically based on installed manifest. + // Different environments may report either "openclaw-lark" or + // "feishu-openclaw-plugin" as the runtime plugin id. if (typeof plugins === 'object' && !Array.isArray(plugins)) { const pluginsObj = plugins as Record; - const pEntries = pluginsObj.entries as Record> | undefined; + const pEntries = ( + pluginsObj.entries && typeof pluginsObj.entries === 'object' && !Array.isArray(pluginsObj.entries) + ? pluginsObj.entries + : {} + ) as Record>; + if (!pluginsObj.entries || typeof pluginsObj.entries !== 'object' || Array.isArray(pluginsObj.entries)) { + pluginsObj.entries = pEntries; + } - // ── feishu-openclaw-plugin → openclaw-lark migration ──────── - // Plugin @larksuite/openclaw-lark ≥2026.3.12 changed its manifest - // id from 'feishu-openclaw-plugin' to 'openclaw-lark'. Migrate - // both plugins.allow and plugins.entries so Gateway validation - // doesn't reject the config with "plugin not found". - const LEGACY_FEISHU_ID = 'feishu-openclaw-plugin'; - const NEW_FEISHU_ID = 'openclaw-lark'; - if (Array.isArray(pluginsObj.allow)) { - const allowArr = pluginsObj.allow as string[]; - const legacyIdx = allowArr.indexOf(LEGACY_FEISHU_ID); - if (legacyIdx !== -1) { - if (!allowArr.includes(NEW_FEISHU_ID)) { - allowArr[legacyIdx] = NEW_FEISHU_ID; - } else { - allowArr.splice(legacyIdx, 1); - } - console.log(`[sanitize] Migrated plugins.allow: ${LEGACY_FEISHU_ID} → ${NEW_FEISHU_ID}`); + const allowArr = Array.isArray(pluginsObj.allow) ? pluginsObj.allow as string[] : []; + if (!Array.isArray(pluginsObj.allow)) { + pluginsObj.allow = allowArr; + } + + const installedFeishuId = await resolveInstalledFeishuPluginId(); + const configuredFeishuId = + FEISHU_PLUGIN_ID_CANDIDATES.find((id) => allowArr.includes(id)) + || FEISHU_PLUGIN_ID_CANDIDATES.find((id) => Boolean(pEntries[id])); + const canonicalFeishuId = installedFeishuId || configuredFeishuId || FEISHU_PLUGIN_ID_CANDIDATES[0]; + + const existingFeishuEntry = + FEISHU_PLUGIN_ID_CANDIDATES.map((id) => pEntries[id]).find(Boolean) + || pEntries.feishu; + + const normalizedAllow = allowArr.filter( + (id) => id !== 'feishu' && !FEISHU_PLUGIN_ID_CANDIDATES.includes(id as typeof FEISHU_PLUGIN_ID_CANDIDATES[number]), + ); + normalizedAllow.push(canonicalFeishuId); + if (JSON.stringify(normalizedAllow) !== JSON.stringify(allowArr)) { + pluginsObj.allow = normalizedAllow; + modified = true; + console.log(`[sanitize] Normalized plugins.allow for feishu -> ${canonicalFeishuId}`); + } + + if (existingFeishuEntry || !pEntries[canonicalFeishuId]) { + pEntries[canonicalFeishuId] = { + ...(existingFeishuEntry || {}), + ...(pEntries[canonicalFeishuId] || {}), + enabled: true, + }; + modified = true; + } + for (const id of FEISHU_PLUGIN_ID_CANDIDATES) { + if (id !== canonicalFeishuId && pEntries[id]) { + delete pEntries[id]; modified = true; } } - if (pEntries?.[LEGACY_FEISHU_ID]) { - if (!pEntries[NEW_FEISHU_ID]) { - pEntries[NEW_FEISHU_ID] = pEntries[LEGACY_FEISHU_ID]; - } - delete pEntries[LEGACY_FEISHU_ID]; - console.log(`[sanitize] Migrated plugins.entries: ${LEGACY_FEISHU_ID} → ${NEW_FEISHU_ID}`); - modified = true; - } // ── wecom-openclaw-plugin → wecom migration ──────────────── const LEGACY_WECOM_ID = 'wecom-openclaw-plugin'; @@ -1080,27 +1108,27 @@ export async function sanitizeOpenClawConfig(): Promise { modified = true; } - // ── Remove bare 'feishu' when openclaw-lark is present ───────── + // ── Remove bare 'feishu' when canonical feishu plugin is present ── // The Gateway binary automatically adds bare 'feishu' to plugins.allow - // because the openclaw-lark plugin registers the 'feishu' channel. + // because the official plugin registers the 'feishu' channel. // However, there's no plugin with id='feishu', so Gateway validation // fails with "plugin not found: feishu". Remove it from allow[] and // disable the entries.feishu entry to prevent Gateway from re-adding it. const allowArr2 = Array.isArray(pluginsObj.allow) ? pluginsObj.allow as string[] : []; - const hasNewFeishu = allowArr2.includes(NEW_FEISHU_ID) || !!pEntries?.[NEW_FEISHU_ID]; - if (hasNewFeishu) { + const hasCanonicalFeishu = allowArr2.includes(canonicalFeishuId) || !!pEntries[canonicalFeishuId]; + if (hasCanonicalFeishu) { // Remove bare 'feishu' from plugins.allow const bareFeishuIdx = allowArr2.indexOf('feishu'); if (bareFeishuIdx !== -1) { allowArr2.splice(bareFeishuIdx, 1); - console.log('[sanitize] Removed bare "feishu" from plugins.allow (openclaw-lark is configured)'); + console.log('[sanitize] Removed bare "feishu" from plugins.allow (feishu plugin is configured)'); modified = true; } // Disable bare 'feishu' in plugins.entries so Gateway won't re-add it - if (pEntries?.feishu) { + if (pEntries.feishu) { if (pEntries.feishu.enabled !== false) { pEntries.feishu.enabled = false; - console.log('[sanitize] Disabled bare plugins.entries.feishu (openclaw-lark is configured)'); + console.log('[sanitize] Disabled bare plugins.entries.feishu (feishu plugin is configured)'); modified = true; } } diff --git a/src/components/channels/ChannelConfigModal.tsx b/src/components/channels/ChannelConfigModal.tsx index 204a99b28..10e1c6f71 100644 --- a/src/components/channels/ChannelConfigModal.tsx +++ b/src/components/channels/ChannelConfigModal.tsx @@ -47,7 +47,11 @@ interface ChannelConfigModalProps { configuredTypes?: string[]; showChannelName?: boolean; allowExistingConfig?: boolean; + allowEditAccountId?: boolean; + existingAccountIds?: string[]; + initialConfigValues?: Record; agentId?: string; + accountId?: string; onClose: () => void; onChannelSaved?: (channelType: ChannelType) => void | Promise; } @@ -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(initialSelectedType); const [configValues, setConfigValues] = useState>({}); const [channelName, setChannelName] = useState(''); + const [accountIdInput, setAccountIdInput] = useState(accountId || ''); const [connecting, setConnecting] = useState(false); const [showSecrets, setShowSecrets] = useState>({}); const [qrCode, setQrCode] = useState(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 }>( `/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 = { ...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({ )} + {allowEditAccountId && ( +
+ + setAccountIdInput(event.target.value)} + placeholder={t('account.customIdPlaceholder')} + className={inputClasses} + /> +

{t('account.customIdHint')}

+
+ )} +
{meta?.configFields.map((field) => ( { void handleConnect(); }} - disabled={connecting || !isFormValid()} + disabled={connecting || !isFormValid() || (allowEditAccountId && !accountIdInput.trim())} className={primaryButtonClasses} > {connecting ? ( diff --git a/src/i18n/locales/en/agents.json b/src/i18n/locales/en/agents.json index 31fcf8c49..f5abab7c0 100644 --- a/src/i18n/locales/en/agents.json +++ b/src/i18n/locales/en/agents.json @@ -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}}" } -} \ No newline at end of file +} diff --git a/src/i18n/locales/en/channels.json b/src/i18n/locales/en/channels.json index 4225371a0..55c34083b 100644 --- a/src/i18n/locales/en/channels.json +++ b/src/i18n/locales/en/channels.json @@ -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" -} \ No newline at end of file +} diff --git a/src/i18n/locales/ja/agents.json b/src/i18n/locales/ja/agents.json index d1b9403d3..0bd89e91b 100644 --- a/src/i18n/locales/ja/agents.json +++ b/src/i18n/locales/ja/agents.json @@ -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}}" } -} \ No newline at end of file +} diff --git a/src/i18n/locales/ja/channels.json b/src/i18n/locales/ja/channels.json index cb0e3463e..a98b115ef 100644 --- a/src/i18n/locales/ja/channels.json +++ b/src/i18n/locales/ja/channels.json @@ -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": "ドキュメントを表示" -} \ No newline at end of file +} diff --git a/src/i18n/locales/zh/agents.json b/src/i18n/locales/zh/agents.json index b1cd6ef6d..8212029bb 100644 --- a/src/i18n/locales/zh/agents.json +++ b/src/i18n/locales/zh/agents.json @@ -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}}" } -} \ No newline at end of file +} diff --git a/src/i18n/locales/zh/channels.json b/src/i18n/locales/zh/channels.json index f219b55cc..82d99908b 100644 --- a/src/i18n/locales/zh/channels.json +++ b/src/i18n/locales/zh/channels.json @@ -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": "查看文档" -} \ No newline at end of file +} diff --git a/src/pages/Agents/index.tsx b/src/pages/Agents/index.tsx index 90728f579..58eacfbeb 100644 --- a/src/pages/Agents/index.tsx +++ b/src/pages/Agents/index.tsx @@ -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([]); const [showAddDialog, setShowAddDialog] = useState(false); const [activeAgentId, setActiveAgentId] = useState(null); const [agentToDelete, setAgentToDelete] = useState(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() { setActiveAgentId(agent.id)} onDelete={() => setAgentToDelete(agent)} /> @@ -139,7 +165,7 @@ export function Agents() { {activeAgent && ( 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(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 (
@@ -485,23 +510,16 @@ function AgentSettingsModal({

{t('settingsDialog.channelsDescription')}

-
- {assignedChannels.length === 0 ? ( + {assignedChannels.length === 0 && agent.channelTypes.length === 0 ? (
{t('settingsDialog.noChannels')}
) : (
{assignedChannels.map((channel) => ( -
+
@@ -509,67 +527,26 @@ function AgentSettingsModal({

{channel.name}

- {CHANNEL_NAMES[channel.channelType]} + {CHANNEL_NAMES[channel.channelType]} · {channel.accountId === 'default' ? t('settingsDialog.mainAccount') : channel.accountId}

{channel.error && (

{channel.error}

)}
-
- - -
+
))} + {assignedChannels.length === 0 && agent.channelTypes.length > 0 && ( +
+ {t('settingsDialog.channelsManagedInChannels')} +
+ )}
)}
- - {showChannelModal && ( - setShowChannelModal(false)} - onChannelSaved={async (channelType) => { - await handleChannelSaved(channelType); - setShowChannelModal(false); - }} - /> - )} - - { - 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)} - />
); } diff --git a/src/pages/Channels/index.tsx b/src/pages/Channels/index.tsx index 2bad99d45..dcabe9720 100644 --- a/src/pages/Channels/index.tsx +++ b/src/pages/Channels/index.tsx @@ -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(null); + const [channelGroups, setChannelGroups] = useState([]); + const [agents, setAgents] = useState([]); + const [showConfigModal, setShowConfigModal] = useState(false); const [selectedChannelType, setSelectedChannelType] = useState(null); - const [configuredTypes, setConfiguredTypes] = useState([]); - const [channelToDelete, setChannelToDelete] = useState<{ id: string } | null>(null); + const [selectedAccountId, setSelectedAccountId] = useState(undefined); + const [allowExistingConfigInModal, setAllowExistingConfigInModal] = useState(true); + const [allowEditAccountIdInModal, setAllowEditAccountIdInModal] = useState(false); + const [existingAccountIdsForModal, setExistingAccountIdsForModal] = useState([]); + const [initialConfigValuesForModal, setInitialConfigValuesForModal] = useState | undefined>(undefined); + const [deleteTarget, setDeleteTarget] = useState(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 (
@@ -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" > - + {t('refresh')}
@@ -149,22 +258,147 @@ export function Channels() {
)} - {availableChannels.length > 0 && ( + {configuredGroups.length > 0 && (

- {t('availableChannels')} + {t('configured')}

-
- {availableChannels.map((channel) => ( - { - setSelectedChannelType(channel.type); - setShowAddDialog(true); - }} - onDelete={() => setChannelToDelete({ id: channel.id })} - /> +
+ {configuredGroups.map((group) => ( +
+
+
+
+ +
+
+

+ {CHANNEL_NAMES[group.channelType as ChannelType] || group.channelType} +

+

{group.channelType}

+
+
+
+ +
+ + +
+
+ +
+ {group.accounts.map((account) => { + const displayName = + account.accountId === 'default' && account.name === account.accountId + ? t('account.mainAccount') + : account.name; + return ( +
+
+
+
+

{displayName}

+
+ {account.lastError && ( +
{account.lastError}
+ )} +
+ +
+ + + +
+
+
+ ); + })} +
+
))}
@@ -176,17 +410,19 @@ export function Channels() {
- {displayedChannelTypes.map((type) => { + {unsupportedGroups.map((type) => { const meta = CHANNEL_META[type]; - const isAvailable = availableChannels.some((channel) => channel.type === type); - if (isAvailable) return null; - return (
- {showAddDialog && ( + {showConfigModal && ( { - 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); }} /> )} { - 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)} />
); @@ -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 ( -
-
- -
-
-
-
-

{channel.name}

- {meta?.isPlugin && ( - - {t('pluginBadge', 'Plugin')} - - )} -
-
- - -
- - {channel.error ? ( -

- {channel.error} -

- ) : ( -

- {meta ? t(meta.description.replace('channels:', '')) : CHANNEL_NAMES[channel.type]} -

- )} -
-
- ); -} - export default Channels; diff --git a/src/stores/agents.ts b/src/stores/agents.ts index 6533ce26f..da52d68ba 100644 --- a/src/stores/agents.ts +++ b/src/stores/agents.ts @@ -8,6 +8,7 @@ interface AgentsState { defaultAgentId: string; configuredChannelTypes: string[]; channelOwners: Record; + channelAccountOwners: Record; loading: boolean; error: string | null; fetchAgents: () => Promise; @@ -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((set) => ({ defaultAgentId: 'main', configuredChannelTypes: [], channelOwners: {}, + channelAccountOwners: {}, loading: false, error: null, diff --git a/src/types/agent.ts b/src/types/agent.ts index e9218be79..b154833f3 100644 --- a/src/types/agent.ts +++ b/src/types/agent.ts @@ -15,4 +15,5 @@ export interface AgentsSnapshot { defaultAgentId: string; configuredChannelTypes: string[]; channelOwners: Record; + channelAccountOwners: Record; } diff --git a/tests/unit/agent-config.test.ts b/tests/unit/agent-config.test.ts index 0a6bf8341..145290fdf 100644 --- a/tests/unit/agent-config.test.ts +++ b/tests/unit/agent-config.test.ts @@ -220,4 +220,44 @@ describe('agent config lifecycle', () => { warnSpy.mockRestore(); infoSpy.mockRestore(); }); + + it('does not delete a legacy-named account when it is owned by another agent', async () => { + await writeOpenClawJson({ + agents: { + list: [ + { id: 'main', name: 'Main', default: true }, + { id: 'test2', name: 'test2' }, + { id: 'test3', name: 'test3' }, + ], + }, + channels: { + feishu: { + enabled: true, + defaultAccount: 'default', + accounts: { + default: { enabled: true, appId: 'main-app' }, + test2: { enabled: true, appId: 'legacy-test2-app' }, + }, + }, + }, + bindings: [ + { + agentId: 'test3', + match: { + channel: 'feishu', + accountId: 'test2', + }, + }, + ], + }); + + const { deleteAgentConfig } = await import('@electron/utils/agent-config'); + await deleteAgentConfig('test2'); + + const config = await readOpenClawJson(); + const feishu = (config.channels as Record).feishu as { + accounts?: Record; + }; + expect(feishu.accounts?.test2).toBeDefined(); + }); });