🤯 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
✨ feat(channel): open conversations as channels in the IM message list (#22205)
Arvin Xu3e09633a40c8
diff --git a/apps/server/src/routers/lambda/channel.ts b/apps/server/src/routers/lambda/channel.tsindex a9d2872e6da..d085e58f545 100644--- a/apps/server/src/routers/lambda/channel.ts+++ b/apps/server/src/routers/lambda/channel.ts@@ -132,6 +132,18 @@ export const channelRouter = router({data: await ctx.channelService.detail(input.channelId, input),success: true,})),+ /**+ * The caller's direct conversation with an Agent, opened on first use for Agents that predate+ * direct Channels. Null when the Agent cannot answer in a Channel (no reachable device).+ */+ openDirect: channelProcedure+ .input(z.object({ agentId: z.string().min(1), localDeviceId: z.string().min(1).optional() }))+ .mutation(async ({ ctx, input }) => {+ const access = await ctx.channelService.openDirect(input.agentId, {+ localDeviceId: input.localDeviceId,+ });+ return { data: access?.channel.id ?? null, success: true };+ }),list: channelProcedure.query(async ({ ctx }) => ({data: await ctx.channelService.repository.list(),success: true,diff --git a/apps/server/src/services/channel/ChannelService.direct.test.ts b/apps/server/src/services/channel/ChannelService.direct.test.tsindex 421ea2a8398..9e0cd84f88b 100644--- a/apps/server/src/services/channel/ChannelService.direct.test.ts+++ b/apps/server/src/services/channel/ChannelService.direct.test.ts@@ -11,6 +11,7 @@ const {createGroupFromDirect,findAccess,findDevice,+ findDirectAccess,getAgent,notify,querySystemInfo,@@ -20,6 +21,7 @@ const {createGroupFromDirect: vi.fn(),findAccess: vi.fn(),findDevice: vi.fn(),+ findDirectAccess: vi.fn(),getAgent: vi.fn(),notify: vi.fn(),querySystemInfo: vi.fn(),@@ -31,6 +33,7 @@ vi.mock('@/database/repositories/channel', async (original) => ({create = create;createGroupFromDirect = createGroupFromDirect;findAccess = findAccess;+ findDirectAccess = findDirectAccess;},}));vi.mock('@/database/models/project', () => ({ ProjectModel: class {} }));@@ -146,15 +149,20 @@ describe('the direct Channel of a new Agent', () => {{ ...claudeCode, executionTarget: 'sandbox' },'desktop',],- [- 'a runtime Channels do not support',- { heterogeneousProvider: { type: 'openclaw' } },- 'desktop',- ],- ])('opens nothing for %s', async (_, agencyConfig, localDeviceId) => {- getAgent.mockResolvedValue({ agencyConfig, name: 'Agent' });- await expect(createDirect(localDeviceId)).resolves.toBeUndefined();+ ])('opens the conversation without a device for %s', async (_, agencyConfig, localDeviceId) => {+ getAgent.mockResolvedValue({ agencyConfig, name: 'Claude' });+ await expect(createDirect(localDeviceId)).resolves.toEqual({ channel: { id: 'chn_1' } });+ // Its device is chosen in the Channel; nothing is probed before then.expect(findDevice).not.toHaveBeenCalled();+ expect(create).toHaveBeenCalledWith({ agentConfig: {}, agentId: 'agt_new', title: 'Claude' });+ });++ it('opens nothing for a runtime Channels do not support', async () => {+ getAgent.mockResolvedValue({+ agencyConfig: { heterogeneousProvider: { type: 'openclaw' } },+ name: 'Agent',+ });+ await expect(createDirect('desktop')).resolves.toBeUndefined();expect(create).not.toHaveBeenCalled();});@@ -175,6 +183,35 @@ describe('the direct Channel of a new Agent', () => {});});+describe('opening the direct Channel of an existing Agent', () => {+ beforeEach(() => {+ vi.resetAllMocks();+ create.mockResolvedValue({ channel: { id: 'chn_new' } });+ getAgent.mockResolvedValue({ model: 'gpt-5', name: 'Nasa' });+ });+ const openDirect = () => new ChannelService({} as never, 'owner').openDirect('agt_old');++ it('reuses the existing conversation without probing its device again', async () => {+ findDirectAccess.mockResolvedValue({ channel: { id: 'chn_old', isDeleted: null } });+ await expect(openDirect()).resolves.toEqual({ channel: { id: 'chn_old', isDeleted: null } });+ expect(findDirectAccess).toHaveBeenCalledWith('agt_old');+ expect(getAgent).not.toHaveBeenCalled();+ expect(create).not.toHaveBeenCalled();+ });++ it('leaves a conversation the person moved to the trash there', async () => {+ findDirectAccess.mockResolvedValue({ channel: { id: 'chn_old', isDeleted: true } });+ await expect(openDirect()).resolves.toBeUndefined();+ expect(create).not.toHaveBeenCalled();+ });++ it('opens one for an Agent made before direct Channels', async () => {+ findDirectAccess.mockResolvedValue(undefined);+ await expect(openDirect()).resolves.toEqual({ channel: { id: 'chn_new' } });+ expect(create).toHaveBeenCalledWith({ agentConfig: {}, agentId: 'agt_old', title: 'Nasa' });+ });+});+describe('inviting from a direct conversation', () => {beforeEach(() => {vi.resetAllMocks();diff --git a/apps/server/src/services/channel/ChannelService.ts b/apps/server/src/services/channel/ChannelService.tsindex 851cc5c8a0a..906ec49b761 100644--- a/apps/server/src/services/channel/ChannelService.ts+++ b/apps/server/src/services/channel/ChannelService.ts@@ -190,10 +190,10 @@ export class ChannelService {};/**- * The direct conversation a person starts with an Agent they just created, titled with the- * Agent's name. The Agent keeps the device and directory a new Channel would give it, checked- * the same way; an external Agent with no device to run on gets none, as it could not join a- * group either.+ * The direct conversation between a person and an Agent, titled with the Agent's name. The Agent+ * keeps the device and directory a new Channel would give it, checked the same way. An external+ * Agent with no device yet still gets its conversation; it asks for a device in the Channel+ * before it can reply.*/createDirect = async (agentId: string, { localDeviceId }: { localDeviceId?: string } = {}) => {const agent = await this.agentService.getAgentConfigById(agentId);@@ -205,8 +205,10 @@ export class ChannelService {localDeviceId,runtime,});- if (!deviceId && runtime !== 'native') return;- const { config } = await this.resolveAgent({ agentId, deviceId }, agent);+ const { config } =+ deviceId || runtime === 'native'+ ? await this.resolveAgent({ agentId, deviceId }, agent)+ : { config: {} };return this.repository.create({agentConfig: config,agentId,@@ -214,6 +216,17 @@ export class ChannelService {});};+ /**+ * The direct conversation a person opens with an existing Agent, e.g. one created before direct+ * Channels. An existing conversation opens as it is, without probing its device again; one the+ * person moved to the trash stays there, and the Agent opens as before.+ */+ openDirect = async (agentId: string, options: { localDeviceId?: string } = {}) => {+ const existing = await this.repository.findDirectAccess(agentId);+ if (existing) return existing.channel.isDeleted ? undefined : existing;+ return this.createDirect(agentId, options);+ };+/*** The main Agent when it runs natively. An external Agent needs a device and directory that a* member picks when adding it, so the scope's LobeAI answers in the meantime.diff --git a/locales/en-US/channel.json b/locales/en-US/channel.jsonindex 00092639156..09c6f63641b 100644--- a/locales/en-US/channel.json+++ b/locales/en-US/channel.json@@ -21,6 +21,7 @@"autoTitle.separator": ", ","blocked.device_approval_pending": "Waiting for device approval","blocked.device_offline": "Waiting for device to connect",+ "blocked.device_required": "Choose a device for this Agent to run on","blocked.directory_locked": "Waiting for this directory to be released","blocked.member_busy": "Waiting for the previous reply","blocked.unavailable": "Agent unavailable",diff --git a/locales/zh-CN/channel.json b/locales/zh-CN/channel.jsonindex 17223c36f96..8662f99d2fb 100644--- a/locales/zh-CN/channel.json+++ b/locales/zh-CN/channel.json@@ -21,6 +21,7 @@"autoTitle.separator": "、","blocked.device_approval_pending": "等待设备授权","blocked.device_offline": "等待设备上线",+ "blocked.device_required": "请为这个 Agent 选择运行设备","blocked.directory_locked": "等待工作目录释放","blocked.member_busy": "等待上一条回复完成","blocked.unavailable": "Agent 暂不可用",diff --git a/packages/database/src/repositories/channel/__tests__/agentConfig.test.ts b/packages/database/src/repositories/channel/__tests__/agentConfig.test.tsindex bd03eb5d2ff..7c36d087436 100644--- a/packages/database/src/repositories/channel/__tests__/agentConfig.test.ts+++ b/packages/database/src/repositories/channel/__tests__/agentConfig.test.ts@@ -23,7 +23,8 @@ afterEach(fixture.cleanup);describe('Channel Agent configuration', () => {it.each(['codex', 'claude-code'])('preserves the legacy model-only %s runtime', async (model) => {const team = await fixture.createTeamChannel();- const member = await fixture.addAgent(team.channel.id, 'Legacy Agent');+ // An external runtime runs on a device, so the member has one.+ const member = await fixture.addAgent(team.channel.id, 'Legacy Agent', deviceConfig());await db.update(agents).set({ model, agencyConfig: null })diff --git a/packages/database/src/repositories/channel/__tests__/claimGuards.test.ts b/packages/database/src/repositories/channel/__tests__/claimGuards.test.tsindex 745ff66d434..e2ddb77cc91 100644--- a/packages/database/src/repositories/channel/__tests__/claimGuards.test.ts+++ b/packages/database/src/repositories/channel/__tests__/claimGuards.test.ts@@ -48,6 +48,31 @@ const answer = async (channelId: string, jobId: string) => {};describe('claim guards', () => {+ it('asks for a device before an external Agent without one replies', async () => {+ const model = new ChannelRepository(db, fixture.ownerId);+ const { channel } = await model.create({ title: 'Direct to Codex' });+ const agent = await fixture.addAgent(channel.id, 'Codex', {+ model: 'gpt-5',+ provider: 'openai',+ runtime: 'codex',+ });++ const waiting = await request(model, channel.id, agent.id, 'no-device');+ expect(await execution.claim(channel.id, waiting.job.id, lease)).toBeNull();+ expect(await jobById(waiting.job.id)).toMatchObject({+ blockedCode: 'device_required',+ status: 'queued',+ });++ // Choosing a device lets the same queued job start.+ await model.updateAgentEnvironment(channel.id, agent.id, {+ deviceId: 'device-4',+ deviceOwnerId: fixture.ownerId,+ workingDirectory: '/repo',+ });+ expect(await execution.claim(channel.id, waiting.job.id, lease)).not.toBeNull();+ });+it('requires an approved grant that matches the device, directory and owner', async () => {const { asOwner, channel, member } = await fixture.createTeamChannel();// A private device owned by the member, not shared with the workspace.diff --git a/packages/database/src/repositories/channel/__tests__/identity.test.ts b/packages/database/src/repositories/channel/__tests__/identity.test.tsindex 46e0898dc59..2f529d416f0 100644--- a/packages/database/src/repositories/channel/__tests__/identity.test.ts+++ b/packages/database/src/repositories/channel/__tests__/identity.test.ts@@ -40,6 +40,38 @@ const publish = async (channelId: string, messageId: string) => {};describe('direct Channel identity', () => {+ it('finds the caller’s direct conversation with an Agent only in its own scope', async () => {+ const agent = await createAgent();+ const repository = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);+ await expect(repository.findDirectAccess(agent.id)).resolves.toBeUndefined();++ const { channel } = await repository.create({ agentId: agent.id, title: 'Direct' });+ await expect(repository.findDirectAccess(agent.id)).resolves.toMatchObject({+ channel: { id: channel.id },+ member: { actorType: 'user', userId: fixture.ownerId },+ });+ await expect(+ new ChannelRepository(db, fixture.ownerId, null).findDirectAccess(agent.id),+ ).resolves.toBeUndefined();+ });++ it('lists each Channel with its newest main message and unread count', async () => {+ const agent = await createAgent();+ const repository = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);+ const { channel } = await repository.create({ agentId: agent.id, title: 'Direct' });+ expect((await repository.list()).find((item) => item.id === channel.id)).toMatchObject({+ lastMessage: null,+ unreadCount: 0,+ });++ await repository.send(channel.id, { ...sendInput, content: 'First', requestKey: 'first' });+ await repository.send(channel.id, { ...sendInput, content: 'Second', requestKey: 'second' });+ expect((await repository.list()).find((item) => item.id === channel.id)).toMatchObject({+ lastMessage: { content: 'Second' },+ unreadCount: 2,+ });+ });+it.each([null, fixture.workspaceId])('creates a private user/Agent conversation in scope %s',async (workspaceId) => {diff --git a/packages/database/src/repositories/channel/claim.ts b/packages/database/src/repositories/channel/claim.tsindex fb2d5425694..dbf5f0b6092 100644--- a/packages/database/src/repositories/channel/claim.ts+++ b/packages/database/src/repositories/channel/claim.ts@@ -278,6 +278,12 @@ export const claimJob = async (return null;}+ // An external Agent runs on a device; its direct conversation can open before one is chosen.+ if (executionConfig.runtime !== 'native' && !member.config?.deviceId) {+ await block(tx, job, 'device_required', 'Choose a device for this Agent to run on');+ return null;+ }+const blocked = (await deviceBlock(tx, channel, member)) ?? (await directoryBlock(tx, member));if (blocked) {await block(tx, job, blocked.code, blocked.reason);diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.tsindex 9b88f505aad..35d2b6cc953 100644--- a/packages/database/src/repositories/channel/index.ts+++ b/packages/database/src/repositories/channel/index.ts@@ -1,5 +1,5 @@import type { ChannelMemberConfig, ChannelMemberRole, ChannelVisibility } from '@lobechat/types';-import { and, desc, eq, isNull, or } from 'drizzle-orm';+import { and, desc, eq, inArray, isNull, or, sql } from 'drizzle-orm';import { TrashModel } from '../../models/trash';import type { ChannelItem, ChannelJobItem, ChannelMessageItem } from '../../schemas';@@ -63,6 +63,9 @@ const hasRole = (role: ChannelMemberRole | null, minRole: ChannelMemberRole) =>* scope (personal, or the given workspace). Every write runs inside `write`, which holds the* `channels` row lock so mutations of one channel serialize in a transaction.*/+/** Characters of the latest message a Channel list item carries as its preview. */+const LIST_PREVIEW_LENGTH = 200;+export class ChannelRepository {private readonly workspaceId: string | null;@@ -306,15 +309,56 @@ export class ChannelRepository {* Channels the caller belongs to in the current scope, newest first. Archived ones are* included with their `status`, so they stay readable outside the active list.*/- list = async (): Promise<Array<ChannelItem & { canDelete: boolean }>> => {+ list = async (): Promise<+ Array<+ ChannelItem & {+ canDelete: boolean;+ lastMessage: { content: string; createdAt: Date } | null;+ unreadCount: number;+ }+ >+ > => {const rows = await this.db- .select({ channel: channels, role: channelMembers.role })+ .select({+ channel: channels,+ lastReadSequence: channelMembers.lastReadSequence,+ role: channelMembers.role,+ }).from(channels).innerJoin(channelMembers, eq(channelMembers.channelId, channels.id)).where(and(this.membershipWhere(), notTrashed(channels.isDeleted))).orderBy(desc(channels.createdAt));- return rows.map(({ channel, role }) => ({ ...channel, canDelete: hasRole(role, 'admin') }));+ // The newest main-channel message of each, for a conversation-list preview.+ const latest = rows.length+ ? await this.db+ .selectDistinctOn([channelMessages.channelId], {+ channelId: channelMessages.channelId,+ content: sql<string>`left(${channelMessages.content}, ${LIST_PREVIEW_LENGTH})`,+ createdAt: channelMessages.createdAt,+ })+ .from(channelMessages)+ .where(+ and(+ inArray(+ channelMessages.channelId,+ rows.map(({ channel }) => channel.id),+ ),+ isNull(channelMessages.threadId),+ ),+ )+ .orderBy(channelMessages.channelId, desc(channelMessages.sequence))+ : [];+ const lastMessageOf = new Map(+ latest.map(({ channelId, ...message }) => [channelId, message] as const),+ );++ return rows.map(({ channel, lastReadSequence, role }) => ({+ ...channel,+ canDelete: hasRole(role, 'admin'),+ lastMessage: lastMessageOf.get(channel.id) ?? null,+ unreadCount: Math.max(0, channel.sequence - (lastReadSequence ?? 0)),+ }));};/** Read access. Returns undefined when the channel is missing or the caller is no member. */@@ -329,6 +373,10 @@ export class ChannelRepository {return row;};+ /** The caller's direct conversation with an Agent in this scope, trashed or not. */+ findDirectAccess = (agentId: string): Promise<ChannelAccess | undefined> =>+ this.findDirect(this.db, agentId);+/*** Runs `fn` while holding the channel row lock, after checking that the caller is an* active member with at least `minRole` (default `member`).@@ -562,7 +610,7 @@ export class ChannelRepository {};private findDirect = async (- tx: Transaction,+ tx: LobeChatDatabase | Transaction,agentId: string,): Promise<ChannelAccess | undefined> => {const [row] = await txdiff --git a/packages/locales/src/default/channel.ts b/packages/locales/src/default/channel.tsindex 83185b36d02..8428968c7d4 100644--- a/packages/locales/src/default/channel.ts+++ b/packages/locales/src/default/channel.ts@@ -129,6 +129,7 @@ export default {'status.cancelled': 'Stopped','blocked.device_approval_pending': 'Waiting for device approval','blocked.device_offline': 'Waiting for device to connect',+ 'blocked.device_required': 'Choose a device for this Agent to run on','blocked.directory_locked': 'Waiting for this directory to be released','blocked.member_busy': 'Waiting for the previous reply','blocked.unavailable': 'Agent unavailable',diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.tsindex 2f459127ee5..4b6192eccc0 100644--- a/packages/types/src/channel.ts+++ b/packages/types/src/channel.ts@@ -183,6 +183,7 @@ export type ChannelJobStatus = 'cancelled' | 'completed' | 'failed' | 'queued' |export type ChannelJobBlockCode =| 'device_approval_pending'| 'device_offline'+ | 'device_required'| 'directory_locked'| 'member_busy'| 'unavailable'@@ -264,11 +265,17 @@ export interface ChannelListItem {canDelete: boolean;createdAt: Date;id: string;+ /** The newest main-channel message, cut for a preview; set by the Channel list. */+ lastMessage?: { content: string; createdAt: Date } | null;/** The project the channel is grouped under; null for a standalone channel. */projectId: string | null;sequence: number;status: ChannelStatus;title: string;+ /** Main-channel messages the caller has not read; set by the Channel list. */+ unreadCount?: number;+ /** Bumped by every new message, so it orders conversations by latest activity. */+ updatedAt?: Date;workspaceId: string | null;}diff --git a/src/features/Channels/ChannelConversation.tsx b/src/features/Channels/ChannelConversation.tsxindex 975599acf58..4dfd2b30fa8 100644--- a/src/features/Channels/ChannelConversation.tsx+++ b/src/features/Channels/ChannelConversation.tsx@@ -13,7 +13,6 @@ import { createStore, Provider } from '@/features/Conversation/store';import WideScreenContainer from '@/features/WideScreenContainer';import { useActiveLocation } from '@/hooks/useActiveLocation';import { cacheScope } from '@/libs/replica';-import { channelService } from '@/services/channel';import { channelActions, channelSelectors, useChannelStore } from '@/store/channel';import { ArchivedNotice } from './ArchivedNotice';@@ -99,7 +98,7 @@ const Timeline = ({useEffect(() => {if (threadId || sequence === undefined || before !== undefined) return;- void channelService+ void channelActions.markRead(channelId, sequence).catch((error: unknown) => console.error('Failed to mark Channel read', error));}, [channelId, threadId, sequence, before]);diff --git a/src/features/Channels/ChannelList.tsx b/src/features/Channels/ChannelList.tsxindex 0aa0522b362..54d57987dbd 100644--- a/src/features/Channels/ChannelList.tsx+++ b/src/features/Channels/ChannelList.tsx@@ -1,5 +1,4 @@import type { ChannelListItem } from '@lobechat/types';-import { CHANNEL_LIMITS } from '@lobechat/types';import {AccordionHeader,AccordionItem,@@ -8,31 +7,19 @@ import {accordionStyles,AccordionTrigger,ActionIcon,- copyToClipboard,cx,DropdownMenu,Flexbox,Text,- toast,} from '@lobehub/ui';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';-import {- Archive,- ArchiveRestore,- Copy,- Hash,- MoreHorizontal,- PencilLine,- Plus,- Trash,-} from 'lucide-react';+import { Archive, Hash, MoreHorizontal, Plus } from 'lucide-react';import { useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';import AsyncError from '@/components/AsyncError';-import { openRenameModal } from '@/components/RenameModal';import EmptyNavItem from '@/features/NavPanel/components/EmptyNavItem';import NavItem from '@/features/NavPanel/components/NavItem';import SkeletonList from '@/features/NavPanel/components/SkeletonList';@@ -40,16 +27,14 @@ import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwarimport { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';import { useActiveLocation } from '@/hooks/useActiveLocation';import { channelActions, channelSelectors, useChannelStore } from '@/store/channel';-import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';-import { isTrpcErrorCode } from '@/utils/trpcError';import { channelsInScope } from './channelScope';import { openCreateChannel } from './CreateChannel';import { channelPath, matchChannel } from './paths';import { threadTitle } from './threadTitle';-import { useChannelArchive } from './useChannelArchive';import { useChannelEvents } from './useChannelEvents';-import { useRemoveChannel } from './useRemoveChannel';+import { useChannelMenu } from './useChannelMenu';+import { useChannelsEnabled } from './useChannelsEnabled';import { useThreadMenu } from './useThreadMenu';// The connector runs down from the centre of the Channel's 18px icon (4px row padding + half@@ -183,72 +168,12 @@ const EnabledChannelSection = ({ itemKey = 'channels', projectId }: ChannelSecticonst channels = useMemo(() => channelsInScope(allChannels, projectId), [allChannels, projectId]);useChannelEvents();- const remove = useRemoveChannel();- const { archive, unarchive } = useChannelArchive();const [showArchived, setShowArchived] = useState(false);const activeChannelId = matchChannel(pathname);const create = () =>openCreateChannel((id) => navigate(channelPath(id, null, projectId)), projectId);const activeThreadId = new URLSearchParams(search).get('thread');- const rename = (channel: ChannelListItem) =>- openRenameModal({- defaultValue: channel.title,- maxLength: CHANNEL_LIMITS.titleLength,- title: t('rename'),- onSave: async (title) => {- try {- await channelActions.rename(channel.id, title);- } catch (error) {- console.error('Failed to rename Channel', error);- toast.error(t(isTrpcErrorCode(error, 'FORBIDDEN') ? 'renameForbidden' : 'renameFailed'));- throw error; // Keep the dialog open with the typed name.- }- },- });- const menuItems = (channel: ChannelListItem) => [- ...(channel.canDelete && channel.status !== 'archived'- ? [{ icon: PencilLine, key: 'rename', label: t('rename'), onClick: () => rename(channel) }]- : []),- {- icon: Copy,- key: 'copyId',- label: t('copyId'),- onClick: async () => {- try {- await copyToClipboard(channel.id);- toast.success(t('copyIdSuccess'));- } catch (error) {- console.error('Failed to copy Channel id', error);- toast.error(t('actionFailed'));- }- },- },- ...(channel.canDelete- ? [- channel.status === 'archived'- ? {- icon: ArchiveRestore,- key: 'unarchive',- label: t('unarchive'),- onClick: () => void unarchive(channel.id),- }- : {- icon: Archive,- key: 'archive',- label: t('archive'),- onClick: () => archive(channel),- },- { type: 'divider' as const },- {- danger: true,- icon: Trash,- key: 'delete',- label: t('moveToTrash'),- onClick: () => remove(channel),- },- ]- : []),- ];+ const menuItems = useChannelMenu();const renderChannel = (channel: ChannelListItem) => {const path = channelPath(channel.id, null, channel.projectId);@@ -350,10 +275,6 @@ const EnabledChannelSection = ({ itemKey = 'channels', projectId }: ChannelSecti);};-// Before the per-user flags load the store holds defaults; wait instead of guessing.-const useChannelsEnabled = () =>- useServerConfigStore((s) => s.serverConfigInit && serverConfigSelectors.enableChannels(s));-/** One accordion item; place it inside an `AccordionRoot`. */export const ChannelSection = (props: ChannelSectionProps) =>useChannelsEnabled() ? <EnabledChannelSection {...props} /> : null;diff --git a/src/features/Channels/useChannelMenu.ts b/src/features/Channels/useChannelMenu.tsnew file mode 100644index 00000000000..610a5b1226f--- /dev/null+++ b/src/features/Channels/useChannelMenu.ts@@ -0,0 +1,80 @@+import type { ChannelListItem } from '@lobechat/types';+import { CHANNEL_LIMITS } from '@lobechat/types';+import { copyToClipboard, toast } from '@lobehub/ui';+import { Archive, ArchiveRestore, Copy, PencilLine, Trash } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { openRenameModal } from '@/components/RenameModal';+import { channelActions } from '@/store/channel';+import { isTrpcErrorCode } from '@/utils/trpcError';++import { useChannelArchive } from './useChannelArchive';+import { useRemoveChannel } from './useRemoveChannel';++/** A Channel's menu wherever it is listed: rename, copy id, archive, and move to the trash. */+export const useChannelMenu = () => {+ const { t } = useTranslation('channel');+ const remove = useRemoveChannel();+ const { archive, unarchive } = useChannelArchive();++ const rename = (channel: ChannelListItem) =>+ openRenameModal({+ defaultValue: channel.title,+ maxLength: CHANNEL_LIMITS.titleLength,+ title: t('rename'),+ onSave: async (title) => {+ try {+ await channelActions.rename(channel.id, title);+ } catch (error) {+ console.error('Failed to rename Channel', error);+ toast.error(t(isTrpcErrorCode(error, 'FORBIDDEN') ? 'renameForbidden' : 'renameFailed'));+ throw error; // Keep the dialog open with the typed name.+ }+ },+ });++ return (channel: ChannelListItem) => [+ ...(channel.canDelete && channel.status !== 'archived'+ ? [{ icon: PencilLine, key: 'rename', label: t('rename'), onClick: () => rename(channel) }]+ : []),+ {+ icon: Copy,+ key: 'copyId',+ label: t('copyId'),+ onClick: async () => {+ try {+ await copyToClipboard(channel.id);+ toast.success(t('copyIdSuccess'));+ } catch (error) {+ console.error('Failed to copy Channel id', error);+ toast.error(t('actionFailed'));+ }+ },+ },+ ...(channel.canDelete+ ? [+ channel.status === 'archived'+ ? {+ icon: ArchiveRestore,+ key: 'unarchive',+ label: t('unarchive'),+ onClick: () => void unarchive(channel.id),+ }+ : {+ icon: Archive,+ key: 'archive',+ label: t('archive'),+ onClick: () => archive(channel),+ },+ { type: 'divider' as const },+ {+ danger: true,+ icon: Trash,+ key: 'delete',+ label: t('moveToTrash'),+ onClick: () => remove(channel),+ },+ ]+ : []),+ ];+};diff --git a/src/features/Channels/useChannelsEnabled.ts b/src/features/Channels/useChannelsEnabled.tsnew file mode 100644index 00000000000..b7f53d91a57--- /dev/null+++ b/src/features/Channels/useChannelsEnabled.ts@@ -0,0 +1,5 @@+import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';++/** Before the per-user flags load the store holds defaults; wait instead of guessing. */+export const useChannelsEnabled = () =>+ useServerConfigStore((s) => s.serverConfigInit && serverConfigSelectors.enableChannels(s));diff --git a/src/features/MessageList/AgentConversation.test.tsx b/src/features/MessageList/AgentConversation.test.tsxnew file mode 100644index 00000000000..b07a67dffab--- /dev/null+++ b/src/features/MessageList/AgentConversation.test.tsx@@ -0,0 +1,108 @@+/**+ * @vitest-environment happy-dom+ */+import { render, screen } from '@testing-library/react';+import { createElement } from 'react';+import { describe, expect, it, vi } from 'vitest';++import AgentConversation from './AgentConversation';++vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('@/components/AgentAvatar', () => ({+ default: ({ agentId, avatar }: { agentId: string; avatar?: string }) =>+ createElement('span', { 'data-testid': 'agent-avatar' }, `${agentId}:${avatar ?? 'generated'}`),+}));+vi.mock('@/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu', () => ({+ // An Agent's own menu ends with its Delete; the row must not clash with it.+ useAgentDropdownMenu: () => () => [{ key: 'delete', label: 'delete' }],+}));+vi.mock('@/features/Channels/useChannelMenu', () => ({+ useChannelMenu: () => (channel: { status?: string }) => [+ { key: 'copyId', label: 'copyId' },+ channel.status === 'archived'+ ? { key: 'unarchive', label: 'unarchive' }+ : { key: 'archive', label: 'archive' },+ { type: 'divider' },+ { key: 'delete', label: 'moveToTrash' },+ ],+}));+vi.mock('@/features/HomeSidebar/Body/Agent/List/usePreservedAgentUrl', () => ({+ usePreservedAgentUrl: (id: string) => `/agent/${id}`,+}));+vi.mock('@/features/HomeSidebar/Body/Agent/ModalProvider', () => ({+ useAgentModal: () => ({ openCreateGroupModal: () => {} }),+}));+vi.mock('@/hooks/usePrefetchAgent', () => ({ usePrefetchAgent: () => () => {} }));+vi.mock('@/store/chat', () => ({ useChatStore: () => false }));+vi.mock('@/store/chat/selectors', () => ({+ operationSelectors: { isAgentVisiblyRunning: () => () => false },+}));+vi.mock('./useAgentConversationLink', () => ({+ useAgentConversationLink: (_: string, url: string) => ({ url }),+}));+vi.mock('./ConversationRow', () => ({+ default: ({ avatar, contextMenuItems, title }: any) =>+ createElement(+ 'div',+ {},+ title,+ avatar as never,+ createElement(+ 'span',+ { 'data-testid': 'menu' },+ (contextMenuItems?.() ?? []).map((item: any) => item.key ?? item.type).join(','),+ ),+ ),+}));++const conversation = (avatar?: string, channel?: { status?: string }) =>+ ({+ activeAt: new Date('2026-11-03'),+ ...(channel ? { channel: { id: 'cht_cook', title: 'Cook', unreadCount: 0, ...channel } } : {}),+ item: { avatar, id: 'agt_cook', name: 'Cook', title: 'Cook', type: 'agent' },+ }) as never;++describe('AgentConversation avatar', () => {+ // The row drew the legacy robot image while the agent's Channel showed its generated character.+ it('draws the agent avatar seeded by its id when it has no image of its own', () => {+ render(createElement(AgentConversation, { active: false, conversation: conversation() }));++ expect(screen.getByTestId('agent-avatar')).toHaveTextContent('agt_cook:generated');+ });++ it('keeps an agent’s own image or emoji', () => {+ render(createElement(AgentConversation, { active: false, conversation: conversation('🍳') }));++ expect(screen.getByTestId('agent-avatar')).toHaveTextContent('agt_cook:🍳');+ });++ // A row that opens a direct Channel is that conversation, so its archive / trash live here.+ it('offers the direct Channel archive and trash actions beside the Agent menu', () => {+ render(+ createElement(AgentConversation, {+ active: false,+ conversation: conversation(undefined, {}),+ }),+ );++ expect(screen.getByTestId('menu')).toHaveTextContent('delete,divider,channel-archive,channel-delete');+ });++ it('offers unarchive instead for an archived direct Channel', () => {+ render(+ createElement(AgentConversation, {+ active: false,+ conversation: conversation(undefined, { status: 'archived' }),+ }),+ );++ expect(screen.getByTestId('menu')).toHaveTextContent('channel-unarchive');+ });++ it('keeps the Agent menu alone when the row opens no Channel', () => {+ render(createElement(AgentConversation, { active: false, conversation: conversation() }));++ expect(screen.getByTestId('menu')).toHaveTextContent('delete');+ expect(screen.getByTestId('menu')).not.toHaveTextContent('channel-');+ });+});diff --git a/src/features/MessageList/AgentConversation.tsx b/src/features/MessageList/AgentConversation.tsxindex dccfe348184..9653f254a3a 100644--- a/src/features/MessageList/AgentConversation.tsx+++ b/src/features/MessageList/AgentConversation.tsx@@ -1,11 +1,12 @@'use client';-import { DEFAULT_AVATAR } from '@lobechat/const';import { agentDisplayName } from '@lobechat/types';-import { memo, useCallback } from 'react';+import { type DropdownItem } from '@lobehub/ui';+import { memo, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';-import Avatar from '@/components/Avatar';+import AgentAvatar from '@/components/AgentAvatar';+import { useChannelMenu } from '@/features/Channels/useChannelMenu';import { useAgentDropdownMenu } from '@/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu';import { usePreservedAgentUrl } from '@/features/HomeSidebar/Body/Agent/List/usePreservedAgentUrl';import { useAgentModal } from '@/features/HomeSidebar/Body/Agent/ModalProvider';@@ -16,6 +17,24 @@ import { operationSelectors } from '@/store/chat/selectors';import ConversationRow from './ConversationRow';import { type Conversation } from './conversations';import { AVATAR_SIZE } from './style';+import { useAgentConversationLink } from './useAgentConversationLink';++/** The direct Channel's own conversation actions, next to the Agent's own menu. */+const CONVERSATION_ACTION_KEYS = new Set(['archive', 'unarchive', 'delete']);++/**+ * A row that opens a direct Channel *is* that conversation, so the Channel's archive and+ * trash actions belong on the row: without them, archiving or trashing the conversation+ * means opening it first, and the Agent's Delete removes the Agent instead. Keys are+ * prefixed so they cannot collide with the Agent's own `delete`.+ */+const conversationActions = (menu: DropdownItem[]): DropdownItem[] =>+ menu.flatMap((item) => {+ if (!item || !('key' in item)) return [];+ const key = String(item.key);+ if (!CONVERSATION_ACTION_KEYS.has(key)) return [];+ return [{ ...item, key: `channel-${key}` } as DropdownItem];+ });interface AgentConversationProps {active: boolean;@@ -29,7 +48,10 @@ const AgentConversation = memo<AgentConversationProps>(({ active, conversation }const { openCreateGroupModal } = useAgentModal();const prefetchAgent = usePrefetchAgent();const running = useChatStore(operationSelectors.isAgentVisiblyRunning(id));- const url = usePreservedAgentUrl(id);+ const agentUrl = usePreservedAgentUrl(id);+ const { onClick, url } = useAgentConversationLink(id, agentUrl);+ const channelMenu = useChannelMenu();+ const directChannel = conversation.channel;const title = agentDisplayName(item, t('untitledAgent'));const avatarSrc = typeof avatar === 'string' ? avatar : undefined;@@ -54,27 +76,40 @@ const AgentConversation = memo<AgentConversationProps>(({ active, conversation }visibility,});+ const menuItems = useMemo(+ () => () => {+ const agentItems = contextMenuItems();+ if (!directChannel) return agentItems;+ const items = conversationActions(channelMenu(directChannel));+ if (items.length === 0) return agentItems;+ return [...agentItems, { type: 'divider' as const }, ...items];+ },+ [channelMenu, contextMenuItems, directChannel],+ );+return (<ConversationRowactive={active}activeAt={activeAt}- contextMenuItems={contextMenuItems}+ contextMenuItems={menuItems}pinned={!!pinned}preview={preview}running={running}title={title}- unread={item.unreadCount}+ unread={conversation.unread ?? item.unreadCount}url={url}avatar={- <Avatar- emojiScaleWithBackground- avatar={avatarSrc || DEFAULT_AVATAR}+ // Same avatar the agent has everywhere else, including its direct Channel: its own+ // image or emoji, else the character generated from its id.+ <AgentAvatar+ agentId={id}+ avatar={avatarSrc}background={backgroundColor || undefined}name={title}- shape={'square'}size={AVATAR_SIZE}/>}+ onClick={onClick}onMouseEnter={() => prefetchAgent(id)}/>);diff --git a/src/features/MessageList/Body.test.tsx b/src/features/MessageList/Body.test.tsxindex e4015b77a00..ef5715caacb 100644--- a/src/features/MessageList/Body.test.tsx+++ b/src/features/MessageList/Body.test.tsx@@ -1,13 +1,18 @@/*** @vitest-environment happy-dom*/-import { render, screen } from '@testing-library/react';+import { fireEvent, render, screen } from '@testing-library/react';import { createElement } from 'react';import { beforeEach, describe, expect, it, vi } from 'vitest';import Body from './Body';const home = vi.hoisted(() => ({+ channels: [] as Record<string, unknown>[],+ channelsEnabled: true,+ channelsError: undefined as unknown,+ pathname: '/',+ query: '',error: undefined as unknown,isInit: false,items: [] as unknown[],@@ -20,7 +25,28 @@ vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => kvi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({useActiveWorkspaceSlug: () => null,}));-vi.mock('@/hooks/useActiveLocation', () => ({ useActiveLocation: () => ({ pathname: '/' }) }));+vi.mock('@/hooks/useActiveLocation', () => ({+ useActiveLocation: () => ({ pathname: home.pathname }),+}));+vi.mock('@/store/channel', () => ({+ channelActions: {+ refreshList: () => {},+ useFetchList: () => ({ error: home.channelsError }),+ },+ channelSelectors: { list: () => home.channels },+ useChannelStore: (selector: (state: object) => unknown) => selector({}),+}));+vi.mock('@/features/Channels/useChannelsEnabled', () => ({+ useChannelsEnabled: () => home.channelsEnabled,+}));+vi.mock('@/features/Channels/useChannelEvents', () => ({ useChannelEvents: () => {} }));+vi.mock('./SearchContext', () => ({+ useMessageSearch: () => ({ query: home.query, setQuery: () => {} }),+}));+vi.mock('@/features/NavPanel/components/NavItem', () => ({+ default: ({ onClick, title }: { onClick: () => void; title: string }) =>+ createElement('button', { onClick }, title),+}));vi.mock('@/hooks/useFetchAgentList', () => ({useFetchAgentList: () => ({ error: home.error, mutate: home.mutate }),}));@@ -47,8 +73,9 @@ vi.mock('@/store/agent/selectors', () => ({builtinAgentSelectors: { inboxAgentId: () => 'inbox' },}));-vi.mock('@/features/Channels/ChannelList', () => ({- default: () => createElement('div', {}, 'Channels'),+vi.mock('./ChannelConversation', () => ({+ default: ({ active, channel }: { active: boolean; channel: { title: string } }) =>+ createElement('div', { 'aria-current': active ? 'page' : undefined }, `# ${channel.title}`),}));vi.mock('@/features/NavPanel/components/SkeletonList', () => ({default: () => createElement('div', {}, 'Loading agents'),@@ -57,12 +84,32 @@ vi.mock('./InboxConversation', () => ({default: () => createElement('div', {}, 'Lobe AI row'),}));vi.mock('./AgentConversation', () => ({- default: ({ conversation }: { conversation: { item: { title: string } } }) =>- createElement('div', {}, conversation.item.title),+ default: ({+ active,+ conversation,+ }: {+ active: boolean;+ conversation: { item: { title: string } };+ }) =>+ createElement('div', { 'aria-current': active ? 'page' : undefined }, conversation.item.title),}));vi.mock('./GroupConversation', () => ({ default: () => null }));beforeEach(() => {+ home.channels = [+ {+ agentId: null,+ createdAt: new Date('2026-10-01'),+ id: 'chn_team',+ projectId: null,+ status: 'active',+ title: 'Team',+ },+ ];+ home.channelsEnabled = true;+ home.channelsError = undefined;+ home.pathname = '/';+ home.query = '';home.error = undefined;home.isInit = false;home.items = [];@@ -74,7 +121,7 @@ describe('MessageList Body', () => {render(createElement(Body));expect(screen.getByText('Lobe AI row')).toBeInTheDocument();- expect(screen.getByText('Channels')).toBeInTheDocument();+ expect(screen.getByText('# Team')).toBeInTheDocument();expect(screen.getByText('Loading agents')).toBeInTheDocument();});@@ -86,7 +133,7 @@ describe('MessageList Body', () => {expect(screen.getByText('Agents failed')).toBeInTheDocument();expect(screen.queryByText('Loading agents')).not.toBeInTheDocument();expect(screen.getByText('Lobe AI row')).toBeInTheDocument();- expect(screen.getByText('Channels')).toBeInTheDocument();+ expect(screen.getByText('# Team')).toBeInTheDocument();});it('drops the agent skeleton once the list arrives', () => {@@ -99,7 +146,109 @@ describe('MessageList Body', () => {expect(screen.getByText('Agent A')).toBeInTheDocument();expect(screen.queryByText('Loading agents')).not.toBeInTheDocument();- expect(screen.getByText('Channels')).toBeInTheDocument();+ expect(screen.getByText('# Team')).toBeInTheDocument();+ });+});++describe('MessageList Body Channel rows', () => {+ const channel = (patch: Record<string, unknown>) => ({+ agentId: null,+ createdAt: new Date('2026-10-01'),+ projectId: null,+ status: 'active',+ ...patch,+ });++ it('lists group Channels as rows, leaving out direct, project and archived ones', () => {+ home.channels = [+ channel({ id: 'chn_team', title: 'Team' }),+ channel({ agentId: 'agt_nasa', id: 'chn_direct', title: 'Nasa' }),+ channel({ id: 'chn_project', projectId: 'pro_1', title: 'Project' }),+ channel({ id: 'chn_archived', status: 'archived', title: 'Old' }),+ ];++ render(createElement(Body));++ expect(screen.getByText('# Team')).toBeInTheDocument();+ expect(screen.queryByText('# Nasa')).not.toBeInTheDocument();+ expect(screen.queryByText('# Project')).not.toBeInTheDocument();+ expect(screen.queryByText('# Old')).not.toBeInTheDocument();+ });++ it('keeps an archived Channel listed while it is open, and highlights it', () => {+ home.pathname = '/channels/chn_archived';+ home.channels = [channel({ id: 'chn_archived', status: 'archived', title: 'Old' })];++ render(createElement(Body));++ expect(screen.getByText('# Old')).toHaveAttribute('aria-current', 'page');+ });++ // Archiving a group Channel left the IM layout with no way back to it.+ it('lists archived Channels behind the archived group at the end', () => {+ home.channels = [+ channel({ id: 'chn_team', title: 'Team' }),+ channel({ id: 'chn_archived', status: 'archived', title: 'Old' }),+ ];++ render(createElement(Body));+ expect(screen.queryByText('# Old')).not.toBeInTheDocument();++ fireEvent.click(screen.getByText('archivedGroup'));+ expect(screen.getByText('# Old')).toBeInTheDocument();+ });++ it('finds archived Channels by search', () => {+ home.query = 'old';+ home.channels = [channel({ id: 'chn_archived', status: 'archived', title: 'Old' })];++ render(createElement(Body));++ expect(screen.getByText('# Old')).toBeInTheDocument();+ expect(screen.queryByText('archivedGroup')).not.toBeInTheDocument();+ });++ it('shows no Channel rows while Channels are off', () => {+ home.channelsEnabled = false;++ render(createElement(Body));++ expect(screen.queryByText('# Team')).not.toBeInTheDocument();+ });+});++describe('MessageList Body active row', () => {+ const agent = {+ id: 'agt_nasa',+ pinned: false,+ title: 'Nasa',+ type: 'agent',+ updatedAt: new Date(),+ };++ it.each([+ ['its Agent page', '/agent/agt_nasa'],+ ['its direct Channel', '/channels/chn_000000000001'],+ ])('highlights an Agent row while %s is open', (_, pathname) => {+ home.isInit = true;+ home.items = [agent];+ home.pathname = pathname;+ home.channels = [{ agentId: 'agt_nasa', id: 'chn_000000000001' }];++ render(createElement(Body));++ expect(screen.getByText('Nasa')).toHaveAttribute('aria-current', 'page');+ });++ it('leaves Agent rows unhighlighted inside a group Channel', () => {+ home.isInit = true;+ home.items = [agent];+ home.pathname = '/channels/chn_000000000002';+ home.channels = [{ agentId: null, id: 'chn_000000000002' }];++ render(createElement(Body));++ expect(screen.getByText('Nasa')).not.toHaveAttribute('aria-current');});});diff --git a/src/features/MessageList/Body.tsx b/src/features/MessageList/Body.tsxindex 9b7f7bac56c..df8a5bff897 100644--- a/src/features/MessageList/Body.tsx+++ b/src/features/MessageList/Body.tsx@@ -4,27 +4,34 @@ import { agentDisplayName } from '@lobechat/types';import { Flexbox } from '@lobehub/ui';import * as stylex from '@stylexjs/stylex';import isEqual from 'fast-deep-equal';-import { memo, useMemo } from 'react';+import { Archive } from 'lucide-react';+import { memo, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';import AsyncError from '@/components/AsyncError';import { resolveInboxAgentRouteId } from '@/features/AgentRoute/useResolvedAgentRouteId';-import ChannelList from '@/features/Channels/ChannelList';+import { matchChannel } from '@/features/Channels/paths';+import { useChannelEvents } from '@/features/Channels/useChannelEvents';+import { useChannelsEnabled } from '@/features/Channels/useChannelsEnabled';+import NavItem from '@/features/NavPanel/components/NavItem';import SkeletonList from '@/features/NavPanel/components/SkeletonList';import { useActiveLocation } from '@/hooks/useActiveLocation';import { useFetchAgentList } from '@/hooks/useFetchAgentList';import { useAgentStore } from '@/store/agent';import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';+import { channelActions, channelSelectors, useChannelStore } from '@/store/channel';import { useHomeStore } from '@/store/home';import { homeAgentListSelectors, homeRecentSelectors } from '@/store/home/selectors';import { ALL_RECENTS_LIMIT } from '@/store/home/slices/recent/action';import { createConversationRecentQueryKey } from '@/store/home/slices/recent/projection';import AgentConversation from './AgentConversation';+import ChannelConversation from './ChannelConversation';import {buildConversationEntries,buildConversationSections,+ channelActivity,type Conversation,latestActivity,latestTopicOf,@@ -36,10 +43,21 @@ import { styles } from './style';const RECENTS_QUERY_KEY = createConversationRecentQueryKey(ALL_RECENTS_LIMIT);-/** `/agent/:id/...` or `/group/:id/...` → the routed conversation id. */+/**+ * `/agent/:id/...`, `/group/:id/...` or `/channels/:id` → the routed conversation id. A direct+ * Channel stands for its Agent, so opening one highlights that Agent's row.+ */const useActiveRouteId = () => {const { pathname } = useActiveLocation();const slug = useActiveWorkspaceSlug();+ const channelId = matchChannel(pathname);+ const directAgentId = useChannelStore((s) =>+ channelId+ ? channelSelectors.list(s)?.find((channel) => channel.id === channelId)?.agentId+ : undefined,+ );+ if (channelId) return directAgentId ?? channelId;+const segments = pathname.split('/').filter(Boolean);const [root, id] = slug && segments[0] === slug ? segments.slice(1) : segments;@@ -60,8 +78,20 @@ const ConversationItem = memo<{ activeRouteId?: string; conversation: ConversatiConversationItem.displayName = 'ConversationItem';+/** Keeps the Channel list fresh while Channels are on; it has no row of its own. */+const ChannelSync = memo(() => {+ const { error } = channelActions.useFetchList();+ useChannelEvents();++ return error ? (+ <AsyncError error={error} variant="inline" onRetry={() => void channelActions.refreshList()} />+ ) : null;+});++ChannelSync.displayName = 'MessageListChannelSync';+const Body = memo(() => {- const { t } = useTranslation('common');+ const { t } = useTranslation(['common', 'channel']);const { error: agentsError, mutate: retryAgents } = useFetchAgentList();const isInit = useHomeStore(homeAgentListSelectors.isAgentListInit);useHomeStore((s) => s.useFetchConversationRecents)(ALL_RECENTS_LIMIT);@@ -69,8 +99,38 @@ const Body = memo(() => {const items = useHomeStore(homeAgentListSelectors.allAgents, isEqual);const recents = useHomeStore(homeRecentSelectors.conversationRecents(RECENTS_QUERY_KEY));const activeRouteId = useActiveRouteId();-+ const channelsEnabled = useChannelsEnabled();+ const allChannels = useChannelStore(channelSelectors.list);const { query } = useMessageSearch();+ const [showArchived, setShowArchived] = useState(false);+ // Group Channels outside any project; a direct Channel opens from its Agent's row. An archived+ // one leaves the list unless it is open, but search still finds it and the archived group at+ // the end lists it.+ const directChannels = useMemo(+ () =>+ new Map(+ channelsEnabled+ ? (allChannels ?? [])+ .filter((channel) => channel.agentId && !channel.projectId)+ .map((channel) => [channel.agentId!, channel] as const)+ : [],+ ),+ [allChannels, channelsEnabled],+ );+ const { archived, channels } = useMemo(() => {+ const groups = channelsEnabled+ ? (allChannels ?? []).filter((channel) => !channel.projectId && !channel.agentId)+ : [];+ const isHidden = (channel: (typeof groups)[number]) =>+ channel.status === 'archived' && channel.id !== activeRouteId;+ return {+ archived: groups+ .filter(isHidden)+ .sort((a, b) => channelActivity(b).getTime() - channelActivity(a).getTime()),+ channels: query.trim() ? groups : groups.filter((channel) => !isHidden(channel)),+ };+ }, [activeRouteId, allChannels, channelsEnabled, query]);+const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);const inboxUpdatedAt = useAgentStore((s) =>inboxAgentId ? s.agentMap[inboxAgentId]?.updatedAt : undefined,@@ -92,11 +152,12 @@ const Body = memo(() => {const entries = useMemo(() =>buildConversationEntries(- buildConversationSections(items, recents),+ buildConversationSections(items, recents, directChannels),{ activeAt: latestActivity(inboxUpdatedAt, inboxTopic), title: inboxTitle },query,+ channels,),- [items, recents, inboxUpdatedAt, inboxTitle, inboxTopic, query],+ [items, recents, directChannels, inboxUpdatedAt, inboxTitle, inboxTopic, query, channels],);// Only the agent rows wait on the agent list: Lobe AI and Channels load on@@ -108,6 +169,13 @@ const Body = memo(() => {{entries.map((entry) =>entry.type === 'inbox' ? (<InboxConversation activeRouteId={activeRouteId} key={'inbox'} />+ ) : entry.type === 'channel' ? (+ <ChannelConversation+ active={entry.channel.id === activeRouteId}+ activeAt={entry.activeAt}+ channel={entry.channel}+ key={entry.channel.id}+ />) : (<ConversationItemactiveRouteId={activeRouteId}@@ -129,8 +197,26 @@ const Body = memo(() => {</div>))}- {/* Non-project Channels (and their create entry) have no other home in the rail layout. */}- <ChannelList />+ {!query.trim() && archived.length > 0 && (+ <>+ <NavItem+ aria-expanded={showArchived}+ icon={Archive}+ title={t('archivedGroup', { count: archived.length, ns: 'channel' })}+ onClick={() => setShowArchived(!showArchived)}+ />+ {showArchived &&+ archived.map((channel) => (+ <ChannelConversation+ active={false}+ activeAt={channelActivity(channel)}+ channel={channel}+ key={channel.id}+ />+ ))}+ </>+ )}+ {channelsEnabled && <ChannelSync />}</Flexbox>);});diff --git a/src/features/MessageList/ChannelConversation.tsx b/src/features/MessageList/ChannelConversation.tsxnew file mode 100644index 00000000000..4580d00351f--- /dev/null+++ b/src/features/MessageList/ChannelConversation.tsx@@ -0,0 +1,49 @@+'use client';++import type { ChannelListItem } from '@lobechat/types';+import { Avatar, Icon } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import { HashIcon } from 'lucide-react';+import { memo } from 'react';++import { channelPath } from '@/features/Channels/paths';+import { useChannelMenu } from '@/features/Channels/useChannelMenu';++import ConversationRow from './ConversationRow';+import { channelPreview } from './conversations';+import { AVATAR_SIZE } from './style';++interface ChannelConversationProps {+ active: boolean;+ activeAt: Date;+ channel: ChannelListItem;+}++/** A group Channel as one more conversation, ordered with the Agents by its latest message. */+const ChannelConversation = memo<ChannelConversationProps>(({ active, activeAt, channel }) => {+ const menuItems = useChannelMenu();++ return (+ <ConversationRow+ active={active}+ activeAt={activeAt}+ contextMenuItems={menuItems(channel)}+ preview={channelPreview(channel)}+ title={channel.title}+ unread={channel.unreadCount}+ url={channelPath(channel.id)}+ avatar={+ <Avatar+ avatar={<Icon color={cssVar.colorTextSecondary} icon={HashIcon} size={16} />}+ background={cssVar.colorFillSecondary}+ shape={'square'}+ size={AVATAR_SIZE}+ />+ }+ />+ );+});++ChannelConversation.displayName = 'ChannelConversation';++export default ChannelConversation;diff --git a/src/features/MessageList/ConversationRow.tsx b/src/features/MessageList/ConversationRow.tsxindex 484e87b17b4..965978a9706 100644--- a/src/features/MessageList/ConversationRow.tsx+++ b/src/features/MessageList/ConversationRow.tsx@@ -2,7 +2,7 @@import { ContextMenuTrigger, Flexbox, Spin } from '@lobehub/ui';import * as stylex from '@stylexjs/stylex';-import { type ComponentProps, memo, type ReactNode, type Ref } from 'react';+import { type ComponentProps, memo, type MouseEvent, type ReactNode, type Ref } from 'react';import { useTranslation } from 'react-i18next';import WorkspaceLink from '@/features/Workspace/WorkspaceLink';@@ -15,6 +15,7 @@ export interface ConversationRowProps {activeAt?: Date;avatar: ReactNode;contextMenuItems?: ComponentProps<typeof ContextMenuTrigger>['items'];+ onClick?: (event: MouseEvent<HTMLAnchorElement>) => void;onMouseEnter?: () => void;/** Pinned rows keep a tinted background, like WeChat's 置顶. */pinned?: boolean;@@ -33,6 +34,7 @@ const ConversationRow = memo<ConversationRowProps>(activeAt,avatar,contextMenuItems,+ onClick,onMouseEnter,pinned,preview,@@ -51,6 +53,7 @@ const ConversationRow = memo<ConversationRowProps>(ref={ref}{...stylex.props(styles.row, pinned && styles.rowPinned, active && styles.rowActive)}to={url}+ onClick={onClick}onMouseEnter={onMouseEnter}><span {...stylex.props(styles.avatar)}>diff --git a/src/features/MessageList/Header.tsx b/src/features/MessageList/Header.tsxindex dbcbd1fd004..9815daa98ce 100644--- a/src/features/MessageList/Header.tsx+++ b/src/features/MessageList/Header.tsx@@ -1,12 +1,16 @@'use client';-import { ActionIcon, DropdownMenu, Flexbox, SearchBar, Text } from '@lobehub/ui';-import { PlusIcon } from 'lucide-react';+import { ActionIcon, DropdownMenu, Flexbox, Icon, SearchBar, Text } from '@lobehub/ui';+import { HashIcon, PlusIcon } from 'lucide-react';import { memo, type ReactNode, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';+import { openCreateChannel } from '@/features/Channels/CreateChannel';+import { channelPath } from '@/features/Channels/paths';+import { useChannelsEnabled } from '@/features/Channels/useChannelsEnabled';import { useCreateMenuItems } from '@/features/HomeSidebar/hooks';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { useMessageSearch } from './SearchContext';@@ -37,10 +41,28 @@ export const ListHeader = memo<ListHeaderProps>(({ title, actions }) => (ListHeader.displayName = 'ListHeader';const Header = memo(() => {- const { t } = useTranslation('common');+ const { t } = useTranslation(['common', 'channel']);const { query, setQuery } = useMessageSearch();const { createTopLevelMenuItems, isLoading } = useCreateMenuItems();- const createItems = useMemo(() => createTopLevelMenuItems(), [createTopLevelMenuItems]);+ const channelsEnabled = useChannelsEnabled();+ const navigate = useWorkspaceAwareNavigate();+ // Group Channels are rows of this list too, so they are created from the same entry.+ const createItems = useMemo(() => {+ const items = createTopLevelMenuItems();+ if (!channelsEnabled) return items;+ const [agent, group, ...rest] = items;+ return [+ agent,+ group,+ {+ icon: <Icon icon={HashIcon} />,+ key: 'newChannel',+ label: t('create', { ns: 'channel' }),+ onClick: () => openCreateChannel((id) => navigate(channelPath(id))),+ },+ ...rest,+ ];+ }, [channelsEnabled, createTopLevelMenuItems, navigate, t]);// WeChat-style header: a search box that filters the list, and one "+" entry.return (diff --git a/src/features/MessageList/conversations.test.ts b/src/features/MessageList/conversations.test.tsindex e10c7f8165c..2c68c333f65 100644--- a/src/features/MessageList/conversations.test.ts+++ b/src/features/MessageList/conversations.test.ts@@ -1,4 +1,4 @@-import type { RecentItem, SidebarAgentItem } from '@lobechat/types';+import type { ChannelListItem, RecentItem, SidebarAgentItem } from '@lobechat/types';import { describe, expect, it } from 'vitest';import {@@ -87,6 +87,48 @@ describe('buildConversationSections', () => {});});+describe('buildConversationSections with direct Channels', () => {+ // The row opened the direct Channel but still showed the legacy topic's badge, preview and time.+ it('describes an agent row by the direct Channel it opens', () => {+ const direct = {+ agentId: 'a',+ createdAt: new Date('2026-10-01'),+ id: 'chn_a',+ lastMessage: { content: '**Done**, see\n the PR', createdAt: new Date('2026-10-09') },+ unreadCount: 2,+ } as ChannelListItem;+ const { recent } = buildConversationSections(+ [agent('a', '2026-10-01', { unreadCount: 5 }), agent('b', '2026-10-05')],+ [topic({ agentId: 'a', lastAssistantMessage: 'legacy reply', updatedAt: '2026-10-02' })],+ new Map([['a', direct]]),+ );++ expect(recent.map((c) => c.item.id)).toEqual(['a', 'b']);+ expect(recent[0]).toMatchObject({+ activeAt: new Date('2026-10-09'),+ preview: 'Done, see the PR',+ unread: 2,+ });+ });++ it('falls back to the agent description while its direct Channel is empty', () => {+ const direct = {+ agentId: 'a',+ createdAt: new Date('2026-10-01'),+ id: 'chn_a',+ lastMessage: null,+ unreadCount: 0,+ } as ChannelListItem;+ const { recent } = buildConversationSections(+ [agent('a', '2026-10-01', { description: 'Cooks dinner' })],+ [topic({ agentId: 'a', lastAssistantMessage: 'legacy reply', updatedAt: '2026-10-02' })],+ new Map([['a', direct]]),+ );++ expect(recent[0]).toMatchObject({ preview: 'Cooks dinner', unread: 0 });+ });+});+describe('formatConversationTime', () => {const now = new Date(2026, 9, 26, 15, 0);@@ -109,7 +151,16 @@ describe('buildConversationEntries', () => {undefined,);const ids = (entries: ReturnType<typeof buildConversationEntries>) =>- entries.map((e) => (e.type === 'inbox' ? 'inbox' : e.item.id));+ entries.map((e) =>+ e.type === 'inbox' ? 'inbox' : e.type === 'channel' ? e.channel.id : e.item.id,+ );+ const channel = (id: string, title: string, updatedAt: string) =>+ ({+ createdAt: new Date('2026-01-01'),+ id,+ title,+ updatedAt: new Date(updatedAt),+ }) as ChannelListItem;it('places Lobe AI by its own activity instead of pinning it on top', () => {expect(@@ -149,6 +200,24 @@ describe('buildConversationEntries', () => {expect(ids(buildConversationEntries(named, undefined, 'alice'))).toEqual(['n']);expect(ids(buildConversationEntries(named, undefined, 'health'))).toEqual(['n']);});++ it('orders group Channels with the other conversations by their latest message', () => {+ const channels = [+ channel('chn_team', 'Team', '2026-10-03'),+ channel('chn_old', 'Archive talk', '2026-08-01'),+ ];++ expect(ids(buildConversationEntries(sections, undefined, '', channels))).toEqual([+ 'p',+ 'a',+ 'chn_team',+ 'b',+ 'chn_old',+ ]);+ expect(ids(buildConversationEntries(sections, undefined, 'team', channels))).toEqual([+ 'chn_team',+ ]);+ });});describe('latestTopicOf', () => {diff --git a/src/features/MessageList/conversations.ts b/src/features/MessageList/conversations.tsindex 91cf73983ce..6d9fede8455 100644--- a/src/features/MessageList/conversations.ts+++ b/src/features/MessageList/conversations.ts@@ -1,11 +1,17 @@-import type { RecentItem, SidebarAgentItem } from '@lobechat/types';+import type { ChannelListItem, RecentItem, SidebarAgentItem } from '@lobechat/types';++import { markdownToTxt } from '@/utils/markdownToTxt';export interface Conversation {/** Latest activity: the newer of the item itself and its latest topic. */activeAt: Date;+ /** The agent's direct Channel, when the row opens it. Carries its own archive / trash actions. */+ channel?: ChannelListItem;item: SidebarAgentItem;/** One-line preview from the latest topic (assistant reply, else title). */preview?: string;+ /** Unread messages of the agent's direct Channel, when the row opens it. */+ unread?: number;}export interface ConversationSections {@@ -25,6 +31,17 @@ const recentOwnerId = (recent: RecentItem): string | undefined => {const toTime = (value: Date | string) => new Date(value).getTime();+const oneLine = (text: string | null | undefined) =>+ (text ?? '').replaceAll(/\s+/g, ' ').trim() || undefined;++/** A Channel's latest message as one line of plain text. */+export const channelPreview = (channel: Pick<ChannelListItem, 'lastMessage'>) =>+ channel.lastMessage ? oneLine(markdownToTxt(channel.lastMessage.content)) : undefined;++/** When a Channel last had a message, else when it was opened. */+export const channelActivity = (channel: ChannelListItem): Date =>+ new Date(channel.lastMessage?.createdAt ?? channel.updatedAt ?? channel.createdAt);+/** Newest topic per owner (agent id, or the group named by the topic route). */const topicsByOwner = (recents: RecentItem[] | undefined): Map<string, RecentItem> => {const latest = new Map<string, RecentItem>();@@ -65,6 +82,8 @@ export const latestActivity = (export const buildConversationSections = (items: SidebarAgentItem[],recents: RecentItem[] | undefined,+ /** The person's direct Channel per agent id. A row that opens one shows that conversation. */+ directChannels?: Map<string, ChannelListItem>,): ConversationSections => {const latestByOwner = topicsByOwner(recents);@@ -74,8 +93,21 @@ export const buildConversationSections = (if (seen.has(item.id)) continue;seen.add(item.id);- const latest = latestByOwner.get(item.id);const itemTime = toTime(item.updatedAt);+ const direct = directChannels?.get(item.id);+ if (direct) {+ // The row opens the direct Channel, so its legacy topics no longer describe it.+ conversations.push({+ activeAt: new Date(Math.max(itemTime, channelActivity(direct).getTime())),+ channel: direct,+ item,+ preview: channelPreview(direct) ?? oneLine(item.description),+ unread: direct.unreadCount ?? 0,+ });+ continue;+ }++ const latest = latestByOwner.get(item.id);const latestTime = latest ? toTime(latest.updatedAt) : 0;conversations.push({@@ -97,17 +129,20 @@ export const buildConversationSections = (};export type ConversationEntry =- { activeAt: Date; type: 'inbox' } | (Conversation & { type: 'item' });+ | { activeAt: Date; type: 'inbox' }+ | { activeAt: Date; channel: ChannelListItem; type: 'channel' }+ | (Conversation & { type: 'item' });/*** One IM list like WeChat's: pinned rows first, then everything else by latest- * activity. Lobe AI is an ordinary row placed by its own activity, not pinned- * to the top; a name / title filter narrows the whole list.+ * activity. Lobe AI and group Channels are ordinary rows placed by their own+ * activity, not pinned to the top; a name / title filter narrows the whole list.*/export const buildConversationEntries = ({ pinned, recent }: ConversationSections,inbox: { activeAt?: Date; title: string } | undefined,query = '',+ channels: ChannelListItem[] = [],): ConversationEntry[] => {const keyword = query.trim().toLowerCase();const matches = (...names: (string | null | undefined)[]) =>@@ -120,7 +155,16 @@ export const buildConversationEntries = (.filter((c) => matches(c.item.name, c.item.title)).map((c) => ({ ...c, type: 'item' as const }));- const rest = items(recent);+ const rest = [+ ...items(recent),+ ...channels+ .filter((channel) => matches(channel.title))+ .map((channel) => ({+ activeAt: channelActivity(channel),+ channel,+ type: 'channel' as const,+ })),+ ].sort((a, b) => b.activeAt.getTime() - a.activeAt.getTime());if (inbox && matches(inbox.title)) {const activeAt = inbox.activeAt ?? new Date(0);const index = rest.findIndex((entry) => entry.activeAt.getTime() < activeAt.getTime());diff --git a/src/features/MessageList/useAgentConversationLink.test.ts b/src/features/MessageList/useAgentConversationLink.test.tsnew file mode 100644index 00000000000..1eeed1f0698--- /dev/null+++ b/src/features/MessageList/useAgentConversationLink.test.ts@@ -0,0 +1,128 @@+/**+ * @vitest-environment happy-dom+ */+import { act, renderHook } from '@testing-library/react';+import type { MouseEvent } from 'react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useAgentConversationLink } from './useAgentConversationLink';++const state = vi.hoisted(() => ({+ directChannelId: undefined as string | undefined,+ enabled: true,+ navigate: vi.fn(),+ openDirect: vi.fn(),+ pathname: '/',+ scope: 'personal',+ slug: null as string | null,+}));++vi.mock('@/hooks/useActiveLocation', () => ({+ useActiveLocation: () => ({ pathname: state.pathname, search: '' }),+}));+vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({+ useActiveWorkspaceSlug: () => state.slug,+}));+vi.mock('@/libs/replica', () => ({ cacheScope: { get: () => state.scope } }));++vi.mock('@/features/Channels/useChannelsEnabled', () => ({+ useChannelsEnabled: () => state.enabled,+}));+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({+ useWorkspaceAwareNavigate: () => state.navigate,+}));+vi.mock('@/store/channel', () => ({+ channelActions: { openDirect: state.openDirect },+ channelSelectors: {+ directByAgent: () => () => (state.directChannelId ? { id: state.directChannelId } : undefined),+ },+ useChannelStore: (selector: (s: object) => unknown) => selector({}),+}));++const click = (patch: Partial<MouseEvent> = {}) =>+ ({ button: 0, preventDefault: vi.fn(), ...patch }) as unknown as MouseEvent<HTMLAnchorElement>;++const render = () => renderHook(() => useAgentConversationLink('agt_nasa', '/agent/agt_nasa'));++describe('useAgentConversationLink', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.spyOn(console, 'error').mockImplementation(() => {});+ state.directChannelId = undefined;+ state.enabled = true;+ state.pathname = '/';+ state.scope = 'personal';+ state.slug = null;+ });++ it('links an Agent row to its direct Channel', () => {+ state.directChannelId = 'chn_000000000001';+ expect(render().result.current).toEqual({ url: '/channels/chn_000000000001' });+ });++ it('keeps the Agent page while Channels are off', () => {+ state.enabled = false;+ expect(render().result.current).toEqual({ onClick: undefined, url: '/agent/agt_nasa' });+ });++ it('opens a missing direct Channel on click and navigates into it', async () => {+ state.openDirect.mockResolvedValue('chn_000000000002');+ const { result } = render();+ const event = click();++ await act(async () => result.current.onClick?.(event));++ expect(event.preventDefault).toHaveBeenCalled();+ expect(state.openDirect).toHaveBeenCalledExactlyOnceWith('agt_nasa');+ expect(state.navigate).toHaveBeenCalledWith('/channels/chn_000000000002');+ });++ it.each([+ ['cannot answer in a Channel', () => state.openDirect.mockResolvedValue(undefined)],+ ['fails to open one', () => state.openDirect.mockRejectedValue(new Error('offline'))],+ ])('falls back to the Agent page when the Agent %s', async (_, arrange) => {+ arrange();+ const { result } = render();++ await act(async () => result.current.onClick?.(click()));++ expect(state.navigate).toHaveBeenCalledWith('/agent/agt_nasa');+ });++ // A slow open pulled the person away from the conversation they picked meanwhile.+ it.each([+ [+ 'another conversation is opened meanwhile',+ (rerender: () => void) => {+ state.pathname = '/channels/chn_000000000009';+ rerender();+ },+ ],+ [+ 'the workspace changes meanwhile',+ () => {+ state.scope = 'workspace:other';+ },+ ],+ ])('does not navigate when %s', async (_, change) => {+ let resolve!: (id: string) => void;+ state.openDirect.mockReturnValue(new Promise<string>((r) => (resolve = r)));+ const { rerender, result } = render();++ act(() => result.current.onClick?.(click()));+ change(rerender);+ await act(async () => resolve('chn_000000000002'));++ expect(state.navigate).not.toHaveBeenCalled();+ });++ it('leaves a modified click to the browser', () => {+ const { result } = render();+ const event = click({ metaKey: true });++ result.current.onClick?.(event);++ expect(event.preventDefault).not.toHaveBeenCalled();+ expect(state.openDirect).not.toHaveBeenCalled();+ });+});diff --git a/src/features/MessageList/useAgentConversationLink.ts b/src/features/MessageList/useAgentConversationLink.tsnew file mode 100644index 00000000000..41ca7fec618--- /dev/null+++ b/src/features/MessageList/useAgentConversationLink.ts@@ -0,0 +1,66 @@+import { type MouseEvent, useCallback, useEffect, useRef } from 'react';++import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';+import { channelPath } from '@/features/Channels/paths';+import { useChannelsEnabled } from '@/features/Channels/useChannelsEnabled';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { useActiveLocation } from '@/hooks/useActiveLocation';+import { cacheScope } from '@/libs/replica';+import { channelActions, channelSelectors, useChannelStore } from '@/store/channel';++/** A plain left click; modified clicks keep the browser's own handling of the link. */+const isPlainClick = (event: MouseEvent) =>+ event.button === 0 && !event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey;++/**+ * With Channels on, an agent row opens the person's direct Channel with the Agent. An Agent made+ * before direct Channels has none yet, so the first click opens it; an Agent that cannot answer+ * in a Channel (no reachable device) or a failed open falls back to the Agent's own page.+ */+export const useAgentConversationLink = (agentId: string, agentUrl: string) => {+ const enabled = useChannelsEnabled();+ const directChannelId = useChannelStore((s) =>+ enabled ? channelSelectors.directByAgent(agentId)(s)?.id : undefined,+ );+ const navigate = useWorkspaceAwareNavigate();+ const opening = useRef(false);+ const { pathname, search } = useActiveLocation();+ const slug = useActiveWorkspaceSlug();+ // Where the person is now. Opening a missing Channel takes a request, and by the time it+ // answers they may have picked another conversation or workspace.+ const location = `${slug ?? ''}|${pathname}${search}`;+ const here = useRef(location);+ useEffect(() => {+ here.current = location;+ }, [location]);++ const onClick = useCallback(+ (event: MouseEvent<HTMLAnchorElement>) => {+ if (!isPlainClick(event)) return;+ event.preventDefault();+ if (opening.current) return;+ opening.current = true;+ const from = here.current;+ const scope = cacheScope.get();+ // Navigate only if nothing else was selected meanwhile, and never route an id from the+ // previous workspace under a new one.+ const go = (path: string) => {+ if (here.current === from && cacheScope.get() === scope) navigate(path);+ };+ void channelActions+ .openDirect(agentId)+ .then((channelId) => go(channelId ? channelPath(channelId) : agentUrl))+ .catch((error) => {+ console.error('[channel] Failed to open the direct Channel', error);+ go(agentUrl);+ })+ .finally(() => {+ opening.current = false;+ });+ },+ [agentId, agentUrl, navigate],+ );++ if (directChannelId) return { url: channelPath(directChannelId) };+ return { onClick: enabled ? onClick : undefined, url: agentUrl };+};diff --git a/src/services/channel.ts b/src/services/channel.tsindex d9821236c0b..84fac460811 100644--- a/src/services/channel.ts+++ b/src/services/channel.ts@@ -51,6 +51,9 @@ class ChannelService {title: string;userIds: string[];}) => lambdaClient.channel.createGroupFromDirect.mutate(input);+ /** The caller's direct Channel with an Agent, opened if missing; null when it cannot answer there. */+ openDirect = async (input: { agentId: string; localDeviceId?: string }) =>+ (await lambdaClient.channel.openDirect.mutate(input)).data;detail = async (params: ChannelViewParams): Promise<ChannelDetail> =>(await lambdaClient.channel.detail.query(params)).data;list = async (): Promise<ChannelListItem[]> => (await lambdaClient.channel.list.query()).data;diff --git a/src/store/channel/action.openDirect.test.ts b/src/store/channel/action.openDirect.test.tsnew file mode 100644index 00000000000..a4521b442ae--- /dev/null+++ b/src/store/channel/action.openDirect.test.ts@@ -0,0 +1,88 @@+import type { ChannelListItem } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { channelActions } from './action';+import { useChannelStore } from './store';++vi.mock('@/services/channel', () => ({+ channelService: { list: vi.fn(), markRead: vi.fn(), openDirect: vi.fn() },+}));++const { channelService } = await import('@/services/channel');++const direct = (patch: Partial<ChannelListItem>) =>+ ({ agentId: 'agt_nasa', id: 'chn_000000000001', projectId: null, ...patch }) as ChannelListItem;++describe('channelActions.openDirect', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.spyOn(console, 'error').mockImplementation(() => {});+ channelActions.reset();+ vi.mocked(channelService.list).mockResolvedValue([]);+ });++ it('reuses the listed direct Channel without asking the server', async () => {+ useChannelStore.setState({+ listMap: { all: [direct({ agentId: null, id: 'chn_group00000001' }), direct({})] },+ });++ await expect(channelActions.openDirect('agt_nasa')).resolves.toBe('chn_000000000001');+ expect(channelService.openDirect).not.toHaveBeenCalled();+ });++ it('ignores a project Channel bound to the same Agent', async () => {+ useChannelStore.setState({ listMap: { all: [direct({ projectId: 'pro_1' })] } });+ vi.mocked(channelService.openDirect).mockResolvedValue('chn_000000000002');++ await expect(channelActions.openDirect('agt_nasa')).resolves.toBe('chn_000000000002');+ });++ it('opens one for an Agent made before direct Channels, then refreshes the list', async () => {+ vi.mocked(channelService.openDirect).mockResolvedValue('chn_000000000002');++ await expect(channelActions.openDirect('agt_nasa')).resolves.toBe('chn_000000000002');+ expect(channelService.openDirect).toHaveBeenCalledExactlyOnceWith({+ agentId: 'agt_nasa',+ localDeviceId: undefined,+ });+ expect(channelService.list).toHaveBeenCalled();+ });++ it('reports no Channel when the Agent cannot answer in one', async () => {+ vi.mocked(channelService.openDirect).mockResolvedValue(null);++ await expect(channelActions.openDirect('agt_nasa')).resolves.toBeUndefined();+ expect(channelService.list).not.toHaveBeenCalled();+ });+});++describe('channelActions.markRead', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ channelActions.reset();+ });++ // The row kept its badge for up to a minute after the Channel was read.+ it('clears the listed unread count as soon as the Channel is read', async () => {+ useChannelStore.setState({+ listMap: { all: [direct({ sequence: 5, unreadCount: 3 } as Partial<ChannelListItem>)] },+ });+ vi.mocked(channelService.markRead).mockResolvedValue(5 as never);++ await channelActions.markRead('chn_000000000001', 5);++ expect(useChannelStore.getState().listMap.all?.[0].unreadCount).toBe(0);+ expect(channelService.markRead).toHaveBeenCalledExactlyOnceWith('chn_000000000001', 5);+ });++ it('restores the count when the write fails', async () => {+ useChannelStore.setState({+ listMap: { all: [direct({ sequence: 5, unreadCount: 3 } as Partial<ChannelListItem>)] },+ });+ vi.mocked(channelService.markRead).mockRejectedValue(new Error('offline'));++ await expect(channelActions.markRead('chn_000000000001', 5)).rejects.toThrow('offline');++ expect(useChannelStore.getState().listMap.all?.[0].unreadCount).toBe(3);+ });+});diff --git a/src/store/channel/action.ts b/src/store/channel/action.tsindex 7d29da72bcc..3cb4da081e4 100644--- a/src/store/channel/action.ts+++ b/src/store/channel/action.ts@@ -1,3 +1,4 @@+import { isDesktop } from '@lobechat/const';import type { ChannelPublicThread, ChannelStatus, ChannelThreadStatus } from '@lobechat/types';import { cacheScope } from '@/libs/replica';@@ -8,6 +9,7 @@ import {channelService,type ChannelViewParams,} from '@/services/channel';+import { getElectronStoreState } from '@/store/electron';import { ChannelPrivateAction } from './privateAction';import { channelThreadEntityId } from './projection';@@ -63,6 +65,34 @@ class ChannelActionImpl {await this.#refreshAfterWrite(this.refreshList);return result.data.channel.id;};+ /**+ * Marks the main channel read up to `sequence`. The listed unread count drops at once, so a+ * conversation row does not keep its badge until the next list poll; a failed write restores it.+ */+ markRead = (channelId: string, sequence: number) =>+ this.#private.entity.optimistic(+ channelId,+ (channel) => ({+ ...channel,+ unreadCount: Math.min(channel.unreadCount ?? 0, Math.max(0, channel.sequence - sequence)),+ }),+ () => channelService.markRead(channelId, sequence),+ );+ /**+ * The caller's direct Channel with an Agent, opening it for an Agent that predates direct+ * Channels. Undefined when the Agent cannot answer in a Channel.+ */+ openDirect = async (agentId: string) => {+ const existing = channelSelectors.directByAgent(agentId)(useChannelStore.getState());+ if (existing) return existing.id;+ // On desktop, name this machine so a direct Channel to a local Agent can run here.+ const localDeviceId = isDesktop+ ? await getElectronStoreState().resolveGatewayDeviceId()+ : undefined;+ const channelId = await channelService.openDirect({ agentId, localDeviceId });+ if (channelId) await this.#refreshAfterWrite(this.refreshList);+ return channelId ?? undefined;+ };remove = async (channelId: string) => {const scope = cacheScope.get();// Optimistically hide the row; failure restores it. Keep the open conversationdiff --git a/src/store/channel/selectors.ts b/src/store/channel/selectors.tsindex 6fde6c57279..90faa4fb1b5 100644--- a/src/store/channel/selectors.ts+++ b/src/store/channel/selectors.ts@@ -9,6 +9,7 @@ import type { ChannelState } from './store';const EXTERNAL_BLOCKS = new Set<ChannelJobBlockCode>(['device_approval_pending','device_offline',+ 'device_required','unavailable','workspace_changed',]);@@ -36,5 +37,8 @@ export const channelSelectors = {));},+ /** The caller's direct conversation with an Agent; a direct Channel never belongs to a project. */+ directByAgent: (agentId: string) => (state: ChannelState) =>+ state.listMap.all?.find((channel) => channel.agentId === agentId && !channel.projectId),list: (state: ChannelState) => state.listMap.all,};