Refactor channel account management: move binding/editing to Channels, align Agents display, and simplify UX (#523)
This commit is contained in:
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user