🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(topic): separate Bot and Channel sources in the agent topics filter (#23094)
AmAzing-71e6c2e36559
diff --git a/locales/en-US/topic.json b/locales/en-US/topic.jsonindex e700adcf7aa..1a17c65a85e 100644--- a/locales/en-US/topic.json+++ b/locales/en-US/topic.json@@ -182,6 +182,8 @@"management.bulk.selectedCount_other": "{{count}} selected","management.bulk.unarchive": "Unarchive","management.card.noPreview": "No preview available",+ "management.channels.desc": "Channels this agent is a member of. Open one to read the whole conversation.",+ "management.channels.title": "Channels","management.columns.project": "Project","management.columns.status": "Status","management.columns.title": "Title",@@ -193,8 +195,8 @@"management.empty.noTopics.action": "Start new chat","management.empty.noTopics.desc": "Start a conversation with this agent to create your first topic.","management.empty.noTopics.title": "No topics yet",- "management.filters.botChannel.empty": "No channels",- "management.filters.botChannel.label": "Channel",+ "management.filters.botChannel.empty": "No bot platforms",+ "management.filters.botChannel.label": "Bot platform","management.filters.project.empty": "No projects","management.filters.project.label": "Project","management.filters.status.active": "Active",@@ -209,7 +211,8 @@"management.filters.time.today": "Today","management.filters.time.week": "Past week","management.filters.trigger.api": "API",- "management.filters.trigger.bot": "Channel",+ "management.filters.trigger.bot": "Bot",+ "management.filters.trigger.channel": "Channel","management.filters.trigger.chat": "Chat","management.filters.trigger.eval": "Eval","management.filters.trigger.label": "Trigger",diff --git a/locales/zh-CN/topic.json b/locales/zh-CN/topic.jsonindex c2c91765e0c..d238315bec3 100644--- a/locales/zh-CN/topic.json+++ b/locales/zh-CN/topic.json@@ -182,6 +182,8 @@"management.bulk.selectedCount_other": "已选 {{count}} 项","management.bulk.unarchive": "取消归档","management.card.noPreview": "暂无预览内容",+ "management.channels.desc": "这个助手所在的频道,打开频道查看完整对话。",+ "management.channels.title": "频道","management.columns.project": "项目","management.columns.status": "状态","management.columns.title": "标题",@@ -193,8 +195,8 @@"management.empty.noTopics.action": "开始新对话","management.empty.noTopics.desc": "和这个助手聊聊,创建第一个话题。","management.empty.noTopics.title": "还没有话题",- "management.filters.botChannel.empty": "暂无频道",- "management.filters.botChannel.label": "频道",+ "management.filters.botChannel.empty": "暂无机器人平台",+ "management.filters.botChannel.label": "机器人平台","management.filters.project.empty": "暂无项目","management.filters.project.label": "项目","management.filters.status.active": "活跃",@@ -209,7 +211,8 @@"management.filters.time.today": "今天","management.filters.time.week": "最近一周","management.filters.trigger.api": "API",- "management.filters.trigger.bot": "频道",+ "management.filters.trigger.bot": "机器人",+ "management.filters.trigger.channel": "频道","management.filters.trigger.chat": "对话","management.filters.trigger.eval": "评测","management.filters.trigger.label": "来源",diff --git a/packages/database/src/repositories/channel/__tests__/listAvatars.test.ts b/packages/database/src/repositories/channel/__tests__/listAvatars.test.tsindex 5e741ade3ff..ab8116a8003 100644--- a/packages/database/src/repositories/channel/__tests__/listAvatars.test.ts+++ b/packages/database/src/repositories/channel/__tests__/listAvatars.test.ts@@ -52,4 +52,22 @@ describe('Channel list avatars', () => {const rows = await asOwner.list();expect(rows.find((row) => row.id === channel.id)?.memberAvatars).toEqual([]);});++ // The avatars stop at the first few members; an Agent's page must still find every Channel+ // it takes part in, and not ones it has left.+ it('lists every active Agent member beyond the avatar cap', async () => {+ const { asOwner, channel } = await fixture.createTeamChannel();+ const agents = [];+ for (let index = 0; index < CHANNEL_AVATAR_MEMBERS + 1; index++)+ agents.push(await fixture.addAgent(channel.id, `Agent ${index}`));+ const removed = await fixture.addAgent(channel.id, 'Removed');+ await db+ .update(channelMembers)+ .set({ status: 'removed' })+ .where(eq(channelMembers.id, removed.id));++ const row = (await asOwner.list()).find((item) => item.id === channel.id);+ expect(row?.agentIds).toEqual(agents.map((agent) => agent.agentId));+ expect(row?.agentIds).not.toContain(removed.agentId);+ });});diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.tsindex 6fcac321db6..38554527419 100644--- a/packages/database/src/repositories/channel/index.ts+++ b/packages/database/src/repositories/channel/index.ts@@ -6,7 +6,7 @@ import type {ChannelVisibility,} from '@lobechat/types';import { agentDisplayName } from '@lobechat/types';-import { and, desc, eq, inArray, isNull, or, sql } from 'drizzle-orm';+import { and, desc, eq, inArray, isNotNull, isNull, or, sql } from 'drizzle-orm';import { TrashModel } from '../../models/trash';import type { ChannelItem, ChannelJobItem, ChannelMessageItem } from '../../schemas';@@ -435,6 +435,7 @@ export class ChannelRepository {list = async (): Promise<Array<ChannelItem & {+ agentIds: string[];canDelete: boolean;lastMessage: { content: string; createdAt: Date } | null;memberAvatars: ChannelAvatarMember[];@@ -554,8 +555,35 @@ export class ChannelRepository {this.userId,);+ // Every active Agent member, so a page about one Agent can list the Channels it takes part in;+ // the avatars above are capped and leave later members out.+ const agentMembers = rows.length+ ? await this.db+ .select({ agentId: channelMembers.agentId, channelId: channelMembers.channelId })+ .from(channelMembers)+ .where(+ and(+ inArray(+ channelMembers.channelId,+ rows.map(({ channel }) => channel.id),+ ),+ eq(channelMembers.actorType, 'agent'),+ eq(channelMembers.status, 'active'),+ isNotNull(channelMembers.agentId),+ ),+ )+ .orderBy(channelMembers.createdAt)+ : [];+ const agentIdsOf = new Map<string, string[]>();+ for (const { agentId, channelId } of agentMembers) {+ const ids = agentIdsOf.get(channelId) ?? [];+ ids.push(agentId!);+ agentIdsOf.set(channelId, ids);+ }+return rows.map(({ agentOwnerId, channel, lastReadSequence, role }) => ({...channel,+ agentIds: agentIdsOf.get(channel.id) ?? [],sharedAgent: !!channel.agentId && !channel.workspaceId && agentOwnerId !== this.userId,canDelete: hasRole(role, 'admin'),lastMessage: lastMessageOf.get(channel.id) ?? null,diff --git a/packages/locales/src/default/topic.ts b/packages/locales/src/default/topic.tsindex a6e995626d5..8268b23716a 100644--- a/packages/locales/src/default/topic.ts+++ b/packages/locales/src/default/topic.ts@@ -238,6 +238,9 @@ export default {'management.bulk.selectedCount_other': '{{count}} selected','management.bulk.unarchive': 'Unarchive','management.card.noPreview': 'No preview available',+ 'management.channels.desc':+ 'Channels this agent is a member of. Open one to read the whole conversation.',+ 'management.channels.title': 'Channels','management.columns.project': 'Project','management.columns.status': 'Status','management.columns.title': 'Title',@@ -250,8 +253,8 @@ export default {'management.empty.noTopics.desc':'Start a conversation with this agent to create your first topic.','management.empty.noTopics.title': 'No topics yet',- 'management.filters.botChannel.empty': 'No channels',- 'management.filters.botChannel.label': 'Channel',+ 'management.filters.botChannel.empty': 'No bot platforms',+ 'management.filters.botChannel.label': 'Bot platform','management.filters.project.empty': 'No projects','management.filters.project.label': 'Project','management.filters.status.active': 'Active',@@ -266,7 +269,8 @@ export default {'management.filters.time.today': 'Today','management.filters.time.week': 'Past week','management.filters.trigger.api': 'API',- 'management.filters.trigger.bot': 'Channel',+ 'management.filters.trigger.bot': 'Bot',+ 'management.filters.trigger.channel': 'Channel','management.filters.trigger.chat': 'Chat','management.filters.trigger.eval': 'Eval','management.filters.trigger.label': 'Trigger',diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.tsindex 91749e5ad4d..e8eff5ed233 100644--- a/packages/types/src/channel.ts+++ b/packages/types/src/channel.ts@@ -453,6 +453,11 @@ export interface ChannelAvatarMember {export interface ChannelListItem {/** The bound Agent of a direct conversation; null for a group. */agentId: string | null;+ /**+ * Every active Agent member, oldest first, so a page about one Agent can list the Channels it+ * takes part in; set by the Channel list.+ */+ agentIds?: string[];/** Server-computed for the current member. */canDelete: boolean;createdAt: Date;diff --git a/src/features/AgentTopicManager/ChannelSection.tsx b/src/features/AgentTopicManager/ChannelSection.tsxnew file mode 100644index 00000000000..9cfcfadf650--- /dev/null+++ b/src/features/AgentTopicManager/ChannelSection.tsx@@ -0,0 +1,126 @@+'use client';++import { CHANNEL_URL } from '@lobechat/const';+import type { ChannelListItem } from '@lobechat/types';+import { Block, Flexbox, Icon, Tag, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import { media } from '@lobehub/ui/stylex/media.stylex';+import * as stylex from '@stylexjs/stylex';+import { Hash } from 'lucide-react';+import { type KeyboardEvent, memo } from 'react';+import { useTranslation } from 'react-i18next';++import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { useActivityTime } from '@/hooks/useActivityTime';++const styles = stylex.create({+ // Same column rules as the topic grid, so Channel cards line up with the topics below them.+ grid: {+ display: 'grid',+ gap: 12,+ gridTemplateColumns: {+ default: 'repeat(auto-fill, minmax(min(280px, 100%), 1fr))',+ [media.md]: 'repeat(auto-fill, minmax(min(240px, 100%), 1fr))',+ },+ minWidth: 0,+ width: '100%',+ },+ card: {+ cursor: 'pointer',+ minHeight: 96,+ padding: 14,+ transform: { 'default': null, ':hover': 'translateY(-1px)' },+ boxShadow: { 'default': null, ':hover': '0 4px 12px rgb(0 0 0 / 6%)' },+ transitionDuration: '0.18s',+ transitionProperty: 'transform, box-shadow',+ },+ icon: { color: cssVar.colorTextDescription, flexShrink: 0 },+ title: {+ flex: '1',+ minWidth: 0,+ },+ preview: {+ display: '-webkit-box',+ overflow: 'hidden',+ WebkitBoxOrient: 'vertical',+ WebkitLineClamp: 2,+ },+ footer: {+ color: cssVar.colorTextQuaternary,+ fontSize: 11,+ marginBlockStart: 'auto',+ },+});++const ChannelCard = memo<{ channel: ChannelListItem }>(({ channel }) => {+ const { t } = useTranslation('topic');+ const navigate = useWorkspaceAwareNavigate();+ const activity = useActivityTime(channel.updatedAt ?? channel.createdAt);+ const open = () => navigate(CHANNEL_URL(channel.id, null, channel.projectId));+ const preview = channel.lastMessage?.content?.trim();++ return (+ <Block+ className={stylex.props(styles.card).className}+ gap={8}+ role={'link'}+ tabIndex={0}+ variant={'outlined'}+ onClick={open}+ onKeyDown={(event: KeyboardEvent) => {+ if (event.key === 'Enter') open();+ }}+ >+ <Flexbox horizontal align={'center'} gap={6}>+ <Icon className={stylex.props(styles.icon).className} icon={Hash} size={14} />+ <Text ellipsis className={stylex.props(styles.title).className} fontSize={14} weight={600}>+ {channel.title}+ </Text>+ {channel.status === 'archived' && (+ <Tag size={'small'}>{t('management.filters.status.archived')}</Tag>+ )}+ </Flexbox>+ {preview && (+ <Text className={stylex.props(styles.preview).className} fontSize={12} type={'secondary'}>+ {preview}+ </Text>+ )}+ <span title={activity.title} {...stylex.props(styles.footer)}>+ {activity.text}+ </span>+ </Block>+ );+});++ChannelCard.displayName = 'AgentTopicManagerChannelCard';++/**+ * The group Channels an Agent takes part in. Its run topics there are private execution+ * context and never listed, so the Channel itself is the entry to those conversations.+ */+const ChannelSection = memo<{ channels: ChannelListItem[] }>(({ channels }) => {+ const { t } = useTranslation('topic');+ if (channels.length === 0) return null;++ return (+ <Flexbox gap={12}>+ <Flexbox gap={2}>+ <Text fontSize={13} type={'secondary'} weight={500}>+ {t('management.channels.title')}+ </Text>+ <Text fontSize={12} type={'secondary'}>+ {t('management.channels.desc')}+ </Text>+ </Flexbox>+ <div {...stylex.props(styles.grid)}>+ {channels.map((channel) => (+ <ChannelCard channel={channel} key={channel.id} />+ ))}+ </div>+ </Flexbox>+ );+});++ChannelSection.displayName = 'AgentTopicManagerChannelSection';++export default ChannelSection;diff --git a/src/features/AgentTopicManager/Toolbar.tsx b/src/features/AgentTopicManager/Toolbar.tsxindex 51a5acb201b..e9b8b965f2d 100644--- a/src/features/AgentTopicManager/Toolbar.tsx+++ b/src/features/AgentTopicManager/Toolbar.tsx@@ -16,6 +16,7 @@ import {} from '@lobehub/ui';import {Archive,+ Bot,CalendarRange,ChevronDown,FolderClosed,@@ -36,6 +37,7 @@ import { memo, type ReactNode, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { getPlatformIcon } from '@/features/AgentChannel/const';+import { useChannelsEnabled } from '@/features/Channels/useChannelsEnabled';import { useChatStore } from '@/store/chat';import { topicSelectors } from '@/store/chat/selectors';@@ -164,11 +166,12 @@ const STATUS_OPTIONS: { key: StatusFilter; labelKey: string }[] = [{ key: 'completed', labelKey: 'management.filters.status.completed' },];-const TRIGGER_OPTIONS: TriggerFilter[] = ['chat', 'bot', 'api', 'task', 'eval'];+const TRIGGER_OPTIONS: TriggerFilter[] = ['chat', 'channel', 'bot', 'api', 'task', 'eval'];const TRIGGER_ICON: Record<TriggerFilter, LucideIcon> = {api: Webhook,- bot: Hash,+ bot: Bot,+ channel: Hash,chat: MessageCircle,eval: TestTubeIcon,task: ListTodoIcon,@@ -250,16 +253,17 @@ const Toolbar = memo<ToolbarProps>(({ projects, statusCounts, botChannelOptionsconst viewMode = useTopicsViewStore((s) => s.viewMode);const setViewMode = useTopicsViewStore((s) => s.setViewMode);+ const channelsEnabled = useChannelsEnabled();const triggerItems: DropdownItem[] = useMemo(() =>- TRIGGER_OPTIONS.map((tr) => ({+ TRIGGER_OPTIONS.filter((tr) => tr !== 'channel' || channelsEnabled).map((tr) => ({extra: <CheckMark visible={triggers.includes(tr)} />,icon: <Icon icon={TRIGGER_ICON[tr]} size={14} />,key: tr,label: t(`management.filters.trigger.${tr}` as any) as string,onClick: () => toggleTrigger(tr),})),- [triggers, t, toggleTrigger],+ [channelsEnabled, triggers, t, toggleTrigger],);const projectItems: DropdownItem[] = useMemo(() => {@@ -289,7 +293,7 @@ const Toolbar = memo<ToolbarProps>(({ projects, statusCounts, botChannelOptionsconst PlatformIcon = getPlatformIcon(option.key);return {extra: <CheckMark visible={botChannels.includes(option.key)} />,- icon: PlatformIcon ? <PlatformIcon size={14} /> : <Icon icon={Hash} size={14} />,+ icon: PlatformIcon ? <PlatformIcon size={14} /> : <Icon icon={Bot} size={14} />,key: option.key,label: option.label,onClick: () => toggleBotChannel(option.key),@@ -359,7 +363,7 @@ const Toolbar = memo<ToolbarProps>(({ projects, statusCounts, botChannelOptionsif (!botChannelApplied) {items.push({children: botChannelItems,- icon: <Icon icon={Hash} size={14} />,+ icon: <Icon icon={Bot} size={14} />,key: 'botChannel',label: t('management.filters.botChannel.label'),type: 'submenu',@@ -407,9 +411,9 @@ const Toolbar = memo<ToolbarProps>(({ projects, statusCounts, botChannelOptions}, [botChannels, botChannelOptions]);const botChannelChipIcon = useMemo(() => {- if (botChannels.length !== 1) return <Icon icon={Hash} size={12} />;+ if (botChannels.length !== 1) return <Icon icon={Bot} size={12} />;const PlatformIcon = getPlatformIcon(botChannels[0]);- return PlatformIcon ? <PlatformIcon size={12} /> : <Icon icon={Hash} size={12} />;+ return PlatformIcon ? <PlatformIcon size={12} /> : <Icon icon={Bot} size={12} />;}, [botChannels]);const handleArchiveStale = useCallback(() => {diff --git a/src/features/AgentTopicManager/TopicListView.tsx b/src/features/AgentTopicManager/TopicListView.tsxindex 5fc382ff72f..5e226f2642f 100644--- a/src/features/AgentTopicManager/TopicListView.tsx+++ b/src/features/AgentTopicManager/TopicListView.tsx@@ -28,7 +28,7 @@ import { useTopicsViewStore } from './store';import type { GroupBy, TriggerFilter } from './types';import { getProjectGroupTitle, getProjectLabel, getTimeGroupTitle } from './utils';-const KNOWN_TRIGGERS: readonly TriggerFilter[] = ['chat', 'api', 'task', 'eval'];+const KNOWN_TRIGGERS: readonly TriggerFilter[] = ['chat', 'bot', 'api', 'task', 'eval'];const styles = createStaticStyles(({ css }) => ({cell: css`diff --git a/src/features/AgentTopicManager/index.tsx b/src/features/AgentTopicManager/index.tsxindex ffbe3256a3c..4a2afde0cd9 100644--- a/src/features/AgentTopicManager/index.tsx+++ b/src/features/AgentTopicManager/index.tsx@@ -11,27 +11,36 @@ import { useTranslation } from 'react-i18next';import AsyncError from '@/components/AsyncError';import TopicsSkeleton from '@/components/Skeleton/Topics';+import { useChannelsEnabled } from '@/features/Channels/useChannelsEnabled';import { useLocalMachineDeviceIds } from '@/hooks/useLocalMachineDeviceIds';+import { channelActions, channelSelectors, useChannelStore } from '@/store/channel';import { useChatStore } from '@/store/chat';import { topicSelectors } from '@/store/chat/selectors';import { shinyTextStyles } from '@/styles/loading';import type { ChatTopic } from '@/types/topic';import BulkActionBar from './BulkActionBar';+import ChannelSection from './ChannelSection';import EmptyState from './EmptyState';import Header from './Header';import { useTopicsViewStore } from './store';import Toolbar from './Toolbar';import TopicGrid from './TopicGrid';import TopicListView from './TopicListView';+import type { StatusFilter } from './types';import {+ agentGroupChannels,buildBotChannelOptions,+ channelListState,getProjectFilterLabel,matchesBotChannel,+ matchesChannelSearch,+ matchesChannelStatus,matchesGroup,matchesStatus,matchesTimeRange,matchesTrigger,+ sortChannelsBy,sortTopics,} from './utils';@@ -97,6 +106,20 @@ const AgentTopicManager = memo(() => {// Rows come from the store; the hook only reports fetch progress.const isLoading = !isHydrated || isValidating;+ // Channel conversations are listed as Channels: the Agent's run topics there stay hidden.+ const channelsEnabled = useChannelsEnabled();+ const showChannels = channelsEnabled && triggers.includes('channel');+ const channelSync = channelActions.useFetchList(showChannels);+ const allChannels = useChannelStore(channelSelectors.list);+ const { error: channelsError, loading: channelsLoading } = channelListState(+ showChannels,+ allChannels,+ channelSync.error,+ );+ const retryChannels = () => {+ void channelActions.refreshList().catch(() => {});+ };+const trimmedSearch = search.trim();const { data: searchResults } = useSearchTopics(trimmedSearch.length > 0 ? trimmedSearch : undefined,@@ -128,18 +151,41 @@ const AgentTopicManager = memo(() => {return sortTopics(out, sortBy);}, [preStatusPool, status, sortBy]);- const statusCounts = useMemo(- () => ({- active: preStatusPool.filter((t) => matchesStatus(t, 'active')).length,- all: preStatusPool.length,+ // Project and bot-platform filters describe topics only, so no Channel matches them.+ const channelPool = useMemo(+ () =>+ showChannels && activeAgentId && groupIds.length === 0 && botChannels.length === 0+ ? agentGroupChannels(allChannels, activeAgentId).filter(+ (channel) =>+ matchesChannelSearch(channel, trimmedSearch) && matchesTimeRange(channel, timeRange),+ )+ : [],+ [showChannels, activeAgentId, groupIds, botChannels, allChannels, trimmedSearch, timeRange],+ );++ const visibleChannels = useMemo(+ () =>+ sortChannelsBy(+ channelPool.filter((channel) => matchesChannelStatus(channel, status)),+ sortBy,+ ),+ [channelPool, status, sortBy],+ );++ const statusCounts = useMemo(() => {+ const count = (tab: StatusFilter) =>+ preStatusPool.filter((t) => matchesStatus(t, tab)).length ++ channelPool.filter((channel) => matchesChannelStatus(channel, tab)).length;+ return {+ active: count('active'),+ all: count('all'),// 'archived' has no visible tab today, but StatusFilter still includes it// — count it so the Record satisfies the type for any future tab.- archived: preStatusPool.filter((t) => matchesStatus(t, 'archived')).length,- completed: preStatusPool.filter((t) => matchesStatus(t, 'completed')).length,- running: preStatusPool.filter((t) => matchesStatus(t, 'running')).length,- }),- [preStatusPool],- );+ archived: count('archived'),+ completed: count('completed'),+ running: count('running'),+ };+ }, [preStatusPool, channelPool]);// Search results are flat — grouping by time confuses the relevance order// returned by the BM25 keyword search.@@ -252,9 +298,12 @@ const AgentTopicManager = memo(() => {void revalidate();}}/>- ) : isLoading && baseTopics.length === 0 ? (+ ) : (isLoading && baseTopics.length === 0) ||+ (channelsLoading && totalAfterFilter === 0) ? (<TopicsSkeleton chrome={'body'} />- ) : totalAfterFilter === 0 ? (+ ) : channelsError && totalAfterFilter === 0 ? (+ <AsyncError error={channelsError} variant={'block'} onRetry={retryChannels} />+ ) : totalAfterFilter === 0 && visibleChannels.length === 0 ? (<EmptyStateagentId={activeAgentId}hasFilters={hasActiveFilters}@@ -262,7 +311,12 @@ const AgentTopicManager = memo(() => {/>) : (<>- {viewMode === 'card' ? (+ {channelsError ? (+ <AsyncError error={channelsError} variant={'inline'} onRetry={retryChannels} />+ ) : (+ <ChannelSection channels={visibleChannels} />+ )}+ {totalAfterFilter === 0 ? null : viewMode === 'card' ? (<TopicGridagentId={activeAgentId}groupBy={groupBy}diff --git a/src/features/AgentTopicManager/types.ts b/src/features/AgentTopicManager/types.tsindex cdf78e88b0e..8b51fda3e34 100644--- a/src/features/AgentTopicManager/types.ts+++ b/src/features/AgentTopicManager/types.ts@@ -2,7 +2,11 @@ export type ViewMode = 'card' | 'list';export type StatusFilter = 'all' | 'active' | 'running' | 'completed' | 'archived';-export type TriggerFilter = 'chat' | 'api' | 'task' | 'eval' | 'bot';+/**+ * `bot` is an IM bot platform (Discord, Telegram, …); `channel` is a multi-agent Channel, whose+ * conversations are listed as Channels rather than as topics.+ */+export type TriggerFilter = 'chat' | 'api' | 'task' | 'eval' | 'bot' | 'channel';export type TimeRangeFilter = 'all' | 'today' | 'week' | 'month';diff --git a/src/features/AgentTopicManager/utils.test.ts b/src/features/AgentTopicManager/utils.test.tsindex 5c403daee57..bc5f7d5b4ba 100644--- a/src/features/AgentTopicManager/utils.test.ts+++ b/src/features/AgentTopicManager/utils.test.ts@@ -1,17 +1,38 @@+import type { ChannelListItem } from '@lobechat/types';+import type { ChatTopic } from '@/types/topic';import {+ agentGroupChannels,areAllTopicsArchived,buildBotChannelOptions,+ channelListState,getBotPlatformName,getProjectFilterLabel,getProjectInfo,getProjectLabel,matchesBotChannel,+ matchesChannelSearch,+ matchesChannelStatus,matchesGroup,matchesTrigger,+ sortChannelsBy,} from './utils';+const createChannel = (overrides: Partial<ChannelListItem> = {}): ChannelListItem => ({+ agentId: null,+ agentIds: [],+ canDelete: true,+ createdAt: new Date('2026-01-01T00:00:00Z'),+ id: 'chn_1',+ projectId: null,+ sequence: 1,+ status: 'active',+ title: 'Channel',+ workspaceId: null,+ ...overrides,+});+const createTopic = (metadata: ChatTopic['metadata'],overrides: Partial<ChatTopic> = {},@@ -25,6 +46,34 @@ const createTopic = (});describe('AgentTopicManager utils', () => {+ describe('channelListState', () => {+ it('stays idle while the Channel source is not selected', () => {+ expect(channelListState(false, undefined, new Error('x'))).toEqual({+ error: undefined,+ loading: false,+ });+ });++ it('loads until the first list arrives', () => {+ expect(channelListState(true, undefined, undefined)).toEqual({+ error: undefined,+ loading: true,+ });+ });++ it('reports a failed first fetch instead of loading forever', () => {+ const error = new Error('network');+ expect(channelListState(true, undefined, error)).toEqual({ error, loading: false });+ });++ it('keeps showing a loaded list when a refresh fails', () => {+ expect(channelListState(true, [], new Error('network'))).toEqual({+ error: undefined,+ loading: false,+ });+ });+ });+it('offers unarchive only when every selected topic is archived', () => {const topics = [createTopic(undefined, { id: 'a', status: 'completed' }),@@ -132,4 +181,60 @@ describe('AgentTopicManager utils', () => {expect(getBotPlatformName('dingtalk')).toBe('DingTalk');expect(getBotPlatformName('unknown-platform')).toBe('unknown-platform');});++ // The `channel` trigger lists the Agent's group Channels; its run topics there stay hidden.+ it('lists only group Channels the agent is a member of', () => {+ const member = createChannel({ agentIds: ['agt_a', 'agt_b'], id: 'member' });+ const other = createChannel({ agentIds: ['agt_b'], id: 'other' });+ const direct = createChannel({ agentId: 'agt_a', agentIds: ['agt_a'], id: 'direct' });+ const stale = createChannel({ agentIds: undefined, id: 'stale' });++ expect(agentGroupChannels([member, other, direct, stale], 'agt_a')).toEqual([member]);+ expect(agentGroupChannels(undefined, 'agt_a')).toEqual([]);+ });++ it('maps Channel status onto the topic status tabs', () => {+ const active = createChannel();+ const archived = createChannel({ status: 'archived' });+ const running = createChannel({+ replyJobs: [+ {+ blockedCode: null,+ id: 'job',+ memberId: 'm',+ publicationRevoked: false,+ status: 'running',+ threadId: null,+ writerHeld: true,+ },+ ],+ });++ expect(matchesChannelStatus(active, 'active')).toBe(true);+ expect(matchesChannelStatus(archived, 'active')).toBe(false);+ expect(matchesChannelStatus(archived, 'completed')).toBe(true);+ expect(matchesChannelStatus(active, 'completed')).toBe(false);+ expect(matchesChannelStatus(running, 'running')).toBe(true);+ expect(matchesChannelStatus(active, 'running')).toBe(false);+ expect(matchesChannelStatus(archived, 'all')).toBe(true);+ });++ it('searches Channels by title and sorts them like topics', () => {+ const alpha = createChannel({+ id: 'a',+ title: 'Alpha Launch',+ updatedAt: new Date('2026-01-02T00:00:00Z'),+ });+ const beta = createChannel({+ createdAt: new Date('2026-01-03T00:00:00Z'),+ id: 'b',+ title: 'Beta',+ });++ expect(matchesChannelSearch(alpha, ' launch ')).toBe(true);+ expect(matchesChannelSearch(beta, 'launch')).toBe(false);+ expect(matchesChannelSearch(beta, '')).toBe(true);+ expect(sortChannelsBy([alpha, beta], 'updatedAt').map((c) => c.id)).toEqual(['b', 'a']);+ expect(sortChannelsBy([beta, alpha], 'title').map((c) => c.id)).toEqual(['a', 'b']);+ });});diff --git a/src/features/AgentTopicManager/utils.ts b/src/features/AgentTopicManager/utils.tsindex 4cd9a98f7ce..98f932ddcea 100644--- a/src/features/AgentTopicManager/utils.ts+++ b/src/features/AgentTopicManager/utils.ts@@ -1,4 +1,4 @@-import type { GroupedTopic } from '@lobechat/types';+import type { ChannelListItem, GroupedTopic } from '@lobechat/types';import {getTopicWorkingDirectoryEffectivePath,getTopicWorkingDirectorySourcePath,@@ -78,9 +78,12 @@ export const matchesBotChannel = (topic: ChatTopic, botChannels: BotChannelFiltereturn !!platform && botChannels.includes(platform);};-export const matchesTimeRange = (topic: ChatTopic, range: TimeRangeFilter): boolean => {+export const matchesTimeRange = (+ item: { updatedAt?: Date | number | string | null },+ range: TimeRangeFilter,+): boolean => {if (range === 'all') return true;- const updated = topic.updatedAt ? new Date(topic.updatedAt).getTime() : 0;+ const updated = item.updatedAt ? new Date(item.updatedAt).getTime() : 0;if (!updated) return false;const now = Date.now();const diff = now - updated;@@ -100,6 +103,56 @@ export const matchesTimeRange = (topic: ChatTopic, range: TimeRangeFilter): bool}};+/**+ * A Channel's status as the topic status tabs read it: archived Channels sit under the+ * Archived (`completed`) tab, and one with a reply under way also counts as running.+ */+export const matchesChannelStatus = (channel: ChannelListItem, status: StatusFilter): boolean => {+ switch (status) {+ case 'all': {+ return true;+ }+ case 'archived':+ case 'completed': {+ return channel.status === 'archived';+ }+ case 'running': {+ return (+ channel.status !== 'archived' &&+ !!channel.replyJobs?.some((job) => job.status === 'running')+ );+ }+ default: {+ return channel.status !== 'archived';+ }+ }+};++/**+ * Group Channels the Agent is an active member of. Its run topics there stay hidden from+ * topic lists (they carry other members' messages), so the page lists the Channels instead.+ * Direct conversations open from the Agent itself and are left out.+ */+export const agentGroupChannels = (+ channels: ChannelListItem[] | undefined,+ agentId: string,+): ChannelListItem[] =>+ channels?.filter((channel) => !channel.agentId && !!channel.agentIds?.includes(agentId)) ?? [];++export const matchesChannelSearch = (channel: ChannelListItem, search: string): boolean => {+ const keyword = search.trim().toLowerCase();+ return !keyword || channel.title.toLowerCase().includes(keyword);+};++export const sortChannelsBy = (channels: ChannelListItem[], sortBy: SortBy): ChannelListItem[] => {+ const time = (value: Date | string | undefined) => (value ? new Date(value).getTime() : 0);+ return [...channels].sort((a, b) => {+ if (sortBy === 'title') return a.title.localeCompare(b.title);+ if (sortBy === 'createdAt') return time(b.createdAt) - time(a.createdAt);+ return time(b.updatedAt ?? b.createdAt) - time(a.updatedAt ?? a.createdAt);+ });+};+export const sortTopics = (topics: ChatTopic[], sortBy: SortBy): ChatTopic[] => {const sorted = [...topics];switch (sortBy) {@@ -229,3 +282,17 @@ export const getProjectGroupTitle = (group: GroupedTopic, t: LooseT): string =>if (label) return label;return group.id.replace(/^(project-id|project-directory|project):/, '');};++/**+ * Whether the Channel list is still loading or failed. A failed first fetch leaves no list+ * behind, so it must surface as an error instead of loading forever; a failed refresh keeps+ * showing the list already loaded.+ */+export const channelListState = (+ enabled: boolean,+ channels: readonly unknown[] | undefined,+ error: unknown,+): { error: unknown; loading: boolean } => {+ if (!enabled || channels) return { error: undefined, loading: false };+ return error ? { error, loading: false } : { error: undefined, loading: true };+};diff --git a/src/store/channel/action.ts b/src/store/channel/action.tsindex 5f74e0ffa13..8fbb48f7738 100644--- a/src/store/channel/action.ts+++ b/src/store/channel/action.ts@@ -47,11 +47,12 @@ class ChannelActionImpl {useClientDataSWR(channelKeys.userCandidates(channelId, search), () =>channelService.userCandidates(channelId, search),);- useFetchList = () => {+ /** Pass `false` where the list is only needed behind a user choice, so nothing polls before. */+ useFetchList = (enabled = true) => {const pending = useChannelStore(channelSelectors.listHasPendingWork);return this.#private.list.useSync({},- { refreshInterval: pending ? CHANNEL_ACTIVE_REFRESH_MS : CHANNEL_IDLE_REFRESH_MS },+ { enabled, refreshInterval: pending ? CHANNEL_ACTIVE_REFRESH_MS : CHANNEL_IDLE_REFRESH_MS },);};useFetchDetail = (params: ChannelViewParams | null) => {