Skip to content

🤯 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.

🐛 fix(channel): dispatch @mentions in human quotes, show member avatars for group channels (#22927)

Arvin Xu8725de327d4c
diff --git a/apps/server/src/services/channel/ChannelService.ts b/apps/server/src/services/channel/ChannelService.ts
index ccbfd4b743d..85345abff1c 100644
--- a/apps/server/src/services/channel/ChannelService.ts
+++ b/apps/server/src/services/channel/ChannelService.ts
@@ -338,7 +338,7 @@ export class ChannelService {
routing: config ? 'decision' : 'fallback',
});
notifyChannelMentions(this.db, { userId: this.userId, workspaceId: this.workspaceId }, message);
- // Human quotes only update the public feed; they never schedule Agent work.
+ // A human quote without mentions only updates the public feed; it schedules no Agent work.
if (message.replyToId && message.routingStatus === 'skipped') await this.changed(channelId);
else await Promise.all([wakeChannel(channelId), this.changed(channelId)]);
return message;
diff --git a/packages/database/src/repositories/channel/__tests__/listAvatars.test.ts b/packages/database/src/repositories/channel/__tests__/listAvatars.test.ts
new file mode 100644
index 00000000000..92d5d0cb55d
--- /dev/null
+++ b/packages/database/src/repositories/channel/__tests__/listAvatars.test.ts
@@ -0,0 +1,48 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { channelMembers } from '../../../schemas';
+import { createChannelFixture } from './testUtils';
+
+const db = await getTestDB();
+const fixture = createChannelFixture(db, 'channel-list-avatars');
+beforeEach(fixture.setup);
+afterEach(fixture.cleanup);
+
+describe('Channel list avatars', () => {
+ it('pictures the earliest other active members, capped, for each caller', async () => {
+ const { asMember, asOwner, channel } = await fixture.createTeamChannel();
+ const first = await fixture.addAgent(channel.id, 'First');
+ const removed = await fixture.addAgent(channel.id, 'Removed');
+ const second = await fixture.addAgent(channel.id, 'Second');
+ await fixture.addAgent(channel.id, 'Third');
+ await db
+ .update(channelMembers)
+ .set({ status: 'removed' })
+ .where(eq(channelMembers.id, removed.id));
+
+ const [ownerRow] = await asOwner.list();
+ expect(ownerRow.memberAvatars).toMatchObject([
+ { actorType: 'user', id: fixture.memberId },
+ { actorType: 'agent', id: first.agentId, name: 'First' },
+ { actorType: 'agent', id: second.agentId, name: 'Second' },
+ ]);
+
+ const [memberRow] = await asMember.list();
+ expect(memberRow.memberAvatars).toMatchObject([
+ { actorType: 'user', id: fixture.ownerId },
+ { actorType: 'agent', id: first.agentId },
+ { actorType: 'agent', id: second.agentId },
+ ]);
+ });
+
+ it('pictures no one in a Channel the caller is alone in', async () => {
+ const { asOwner, channel } = await fixture.createTeamChannel();
+ await db.delete(channelMembers).where(eq(channelMembers.userId, fixture.memberId));
+
+ const rows = await asOwner.list();
+ expect(rows.find((row) => row.id === channel.id)?.memberAvatars).toEqual([]);
+ });
+});
diff --git a/packages/database/src/repositories/channel/__tests__/reply.test.ts b/packages/database/src/repositories/channel/__tests__/reply.test.ts
index c8f78e85ea5..1dd33ec93a7 100644
--- a/packages/database/src/repositories/channel/__tests__/reply.test.ts
+++ b/packages/database/src/repositories/channel/__tests__/reply.test.ts
@@ -47,15 +47,10 @@ const threads = (channelId: string) =>
describe('Channel replies', () => {
it.each(['decision', 'fallback'] as const)(
- 'quotes a human without dispatch even when @mentioning an Agent (%s)',
+ 'quotes a human without dispatch when mentioning no one (%s)',
async (routing) => {
- const { asOwner, author, channel, input, root } = await setup();
- const message = await asOwner.send(channel.id, {
- ...input,
- mentions: [author.id],
- replyToId: root.id,
- routing,
- });
+ const { asOwner, channel, input, root } = await setup();
+ const message = await asOwner.send(channel.id, { ...input, replyToId: root.id, routing });
expect(message).toMatchObject({
replyToId: root.id,
threadId: null,
@@ -73,10 +68,32 @@ describe('Channel replies', () => {
},
);
+ it.each(['decision', 'fallback'] as const)(
+ 'dispatches the Agents @mentioned in a human quote, in the same feed (%s)',
+ async (routing) => {
+ const { asOwner, author, channel, input, root } = await setup();
+ const message = await asOwner.send(channel.id, {
+ ...input,
+ mentions: [author.id],
+ replyToId: root.id,
+ routing,
+ });
+ expect(message).toMatchObject({
+ replyToId: root.id,
+ threadId: null,
+ routingStatus: 'directed',
+ routingReason: 'Mentioned',
+ recipientMemberIds: [author.id],
+ });
+ expect(await jobsOf(db, message.id)).toMatchObject([{ memberId: author.id }]);
+ expect(await threads(channel.id)).toEqual([]);
+ },
+ );
+
it('does not invoke the paired Agent when replying to a human', async () => {
const repo = new ChannelRepository(db, fixture.ownerId);
const { channel } = await repo.create({ title: 'Pair' });
- const author = await fixture.addAgent(channel.id, 'Only Agent');
+ await fixture.addAgent(channel.id, 'Only Agent');
const root = await repo.send(channel.id, {
content: 'Hi',
requestKey: 'root',
@@ -87,7 +104,6 @@ describe('Channel replies', () => {
requestKey: 'correction',
routing: 'fallback',
replyToId: root.id,
- mentions: [author.id],
});
expect(message.routingStatus).toBe('skipped');
expect(await jobsOf(db, message.id)).toEqual([]);
@@ -148,8 +164,12 @@ describe('Channel replies', () => {
replyToId: next.id,
threadId: thread.id,
});
+ // Quoting a person stays in the thread; only the mentioned Agent is asked.
expect(humanQuote.threadId).toBe(thread.id);
- expect(await jobsOf(db, humanQuote.id)).toEqual([]);
+ expect(humanQuote.recipientMemberIds).toEqual([other.id]);
+ expect(await jobsOf(db, humanQuote.id)).toMatchObject([
+ { memberId: other.id, threadId: thread.id },
+ ]);
expect(await threads(channel.id)).toHaveLength(1);
});
diff --git a/packages/database/src/repositories/channel/avatars.ts b/packages/database/src/repositories/channel/avatars.ts
new file mode 100644
index 00000000000..dbb673d9a1d
--- /dev/null
+++ b/packages/database/src/repositories/channel/avatars.ts
@@ -0,0 +1,66 @@
+import type { ChannelAvatarMember } from '@lobechat/types';
+import { and, asc, eq, inArray, isNull, lte, ne, or, sql } from 'drizzle-orm';
+
+import { agents, channelMembers, users } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+
+/** A list avatar pictures the caller plus this many other members. */
+export const CHANNEL_AVATAR_MEMBERS = 3;
+
+/**
+ * The earliest active members of each Channel besides `userId`, for the list avatar. One
+ * query for all Channels, capped per Channel, so a large Channel does not load every member.
+ */
+export const channelAvatarMembers = async (
+ db: LobeChatDatabase,
+ channelIds: string[],
+ userId: string,
+): Promise<Map<string, ChannelAvatarMember[]>> => {
+ const result = new Map<string, ChannelAvatarMember[]>();
+ if (!channelIds.length) return result;
+
+ const ranked = db
+ .select({
+ actorType: channelMembers.actorType,
+ avatar: sql<string | null>`coalesce(${agents.avatar}, ${users.avatar})`.as('avatar'),
+ backgroundColor: sql<string | null>`${agents.backgroundColor}`.as('background_color'),
+ channelId: channelMembers.channelId,
+ id: sql<string>`coalesce(${channelMembers.agentId}, ${channelMembers.userId})`.as(
+ 'member_id',
+ ),
+ name: sql<string | null>`coalesce(
+ nullif(${channelMembers.name}, ''),
+ nullif(${agents.title}, ''),
+ nullif(${users.fullName}, ''),
+ ${users.username}
+ )`.as('name'),
+ rank: sql<number>`row_number() over (
+ partition by ${channelMembers.channelId}
+ order by ${channelMembers.createdAt}, ${channelMembers.id}
+ )`.as('rank'),
+ })
+ .from(channelMembers)
+ .leftJoin(agents, eq(agents.id, channelMembers.agentId))
+ .leftJoin(users, eq(users.id, channelMembers.userId))
+ .where(
+ and(
+ inArray(channelMembers.channelId, channelIds),
+ eq(channelMembers.status, 'active'),
+ or(isNull(channelMembers.userId), ne(channelMembers.userId, userId)),
+ ),
+ )
+ .as('ranked');
+
+ const rows = await db
+ .select()
+ .from(ranked)
+ .where(lte(ranked.rank, CHANNEL_AVATAR_MEMBERS))
+ .orderBy(asc(ranked.channelId), asc(ranked.rank));
+
+ for (const { channelId, rank: _rank, ...member } of rows) {
+ const members = result.get(channelId) ?? [];
+ members.push(member);
+ result.set(channelId, members);
+ }
+ return result;
+};
diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.ts
index bf9130de0d7..a0e308da9f5 100644
--- a/packages/database/src/repositories/channel/index.ts
+++ b/packages/database/src/repositories/channel/index.ts
@@ -1,4 +1,5 @@
import type {
+ ChannelAvatarMember,
ChannelMemberConfig,
ChannelMemberRole,
ChannelReplyJob,
@@ -26,6 +27,7 @@ import {
requireAgentMember,
requireChannelAgent,
} from './agent';
+import { channelAvatarMembers } from './avatars';
import { findThread } from './delivery';
import { ChannelError } from './error';
import { addChannelUser, channelUserCandidates, newChannelUserCandidates } from './people';
@@ -421,6 +423,7 @@ export class ChannelRepository {
ChannelItem & {
canDelete: boolean;
lastMessage: { content: string; createdAt: Date } | null;
+ memberAvatars: ChannelAvatarMember[];
mentionCount: number;
replyJobs: ChannelReplyJob[];
unreadCount: number;
@@ -527,10 +530,18 @@ export class ChannelRepository {
: [];
const mentionCountOf = new Map(mentioned.map(({ channelId, count }) => [channelId, count]));
+ // A group Channel's list avatar pictures its first members; a direct one shows its Agent.
+ const avatarsOf = await channelAvatarMembers(
+ this.db,
+ rows.filter(({ channel }) => !channel.agentId).map(({ channel }) => channel.id),
+ this.userId,
+ );
+
return rows.map(({ channel, lastReadSequence, role }) => ({
...channel,
canDelete: hasRole(role, 'admin'),
lastMessage: lastMessageOf.get(channel.id) ?? null,
+ memberAvatars: avatarsOf.get(channel.id) ?? [],
mentionCount: mentionCountOf.get(channel.id) ?? 0,
replyJobs: replyJobsOf.get(channel.id) ?? [],
unreadCount: Math.max(0, channel.sequence - (lastReadSequence ?? 0)),
diff --git a/packages/database/src/repositories/channel/send.ts b/packages/database/src/repositories/channel/send.ts
index 4efb724d36f..595335e23db 100644
--- a/packages/database/src/repositories/channel/send.ts
+++ b/packages/database/src/repositories/channel/send.ts
@@ -25,9 +25,9 @@ import { createChannelThread } from './view';
export interface ChannelSendInput {
content: string;
fileIds?: string[];
- /** Member ids. Human quotes retain mentions without dispatching them. */
+ /** Member ids. A human quote dispatches only its mentioned Agents. */
mentions?: string[];
- /** Quote a person without dispatch, or continue an Agent answer in its thread. */
+ /** Quote a person (only mentions dispatch), or continue an Agent answer in its thread. */
replyToId?: string;
/** Client retry key; a retry with the same key returns the original message. */
requestKey: string;
@@ -65,8 +65,9 @@ export const validateSendInput = (input: ChannelSendInput) => {
/**
* Posts a human message. The caller holds the channel lock and is `access.member`.
*
- * - Human quotes stay in their feed without jobs; Agent replies continue in a thread.
- * - Outside human quotes, @mentioned Agents get jobs in this transaction (`directed`, source `explicit`).
+ * - Human quotes stay in their feed; without mentions they get no jobs. Agent replies continue
+ * in a thread.
+ * - @mentioned Agents get jobs in this transaction (`directed`, source `explicit`), quoted or not.
* - @mentioning only people wakes no Agent.
* - Without mentions, `decision` leaves the message `pending` for the routing task, and
* `fallback` hands it to every candidate Agent at once.
@@ -96,9 +97,11 @@ export const sendMessage = async (
replyTo.id !== sourceThread?.rootMessageId
)
throw new ChannelError('BAD_REQUEST', 'Reply message belongs to another conversation');
- const quoteOnly = !!replyTo && replyTo.routingStatus !== 'reply';
+ const humanQuote = !!replyTo && replyTo.routingStatus !== 'reply';
+ // An explicit @mention still dispatches; the quote only adds context.
+ const quoteOnly = humanQuote && !mentions.length;
const [replyAgent] =
- replyTo && !quoteOnly
+ replyTo && !humanQuote
? await tx
.select()
.from(channelMembers)
@@ -111,7 +114,7 @@ export const sendMessage = async (
),
)
: [];
- if (replyTo && !quoteOnly && !replyAgent)
+ if (replyTo && !humanQuote && !replyAgent)
throw new ChannelError('BAD_REQUEST', 'The replying Agent is no longer available');
// A click is local. Create the Agent's thread atomically with the first sent reply.
const thread = assertThreadOpen(
diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.ts
index 25db199e71c..629368f6ea2 100644
--- a/packages/types/src/channel.ts
+++ b/packages/types/src/channel.ts
@@ -340,6 +340,16 @@ export interface ChannelInputManifest {
/** Flat audit payload: routing decisions, claims, stops, isolation reasons. */
export type ChannelAuditDetails = Record<string, boolean | number | string | string[] | null>;
+/** A member pictured in a Channel's list avatar. */
+export interface ChannelAvatarMember {
+ actorType: ChannelMemberActorType;
+ avatar: string | null;
+ backgroundColor: string | null;
+ /** The Agent id or user id; seeds a generated avatar when there is no image. */
+ id: string;
+ name: string | null;
+}
+
/** Public client projection. No execution configuration, private topic or draft fields. */
export interface ChannelListItem {
/** The bound Agent of a direct conversation; null for a group. */
@@ -350,6 +360,11 @@ export interface ChannelListItem {
id: string;
/** The newest main-channel message, cut for a preview; set by the Channel list. */
lastMessage?: { content: string; createdAt: Date } | null;
+ /**
+ * The first members besides the caller, oldest first, for a group Channel's list avatar;
+ * set by the Channel list.
+ */
+ memberAvatars?: ChannelAvatarMember[];
/** Unread messages, Threads included, that @mention the caller; set by the Channel list. */
mentionCount?: number;
/** The project the channel is grouped under; null for a standalone channel. */
diff --git a/src/features/MessageList/ChannelConversation.test.tsx b/src/features/MessageList/ChannelConversation.test.tsx
new file mode 100644
index 00000000000..6c29e594065
--- /dev/null
+++ b/src/features/MessageList/ChannelConversation.test.tsx
@@ -0,0 +1,71 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import type { ChannelListItem } from '@lobechat/types';
+import { render, screen } from '@testing-library/react';
+import { createElement } from 'react';
+import { describe, expect, it, vi } from 'vitest';
+
+import ChannelConversation from './ChannelConversation';
+
+const store = vi.hoisted(() => ({
+ project: undefined as { id: string; name: string } | undefined,
+}));
+
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('@/features/Channels/useChannelMenu', () => ({ useChannelMenu: () => () => [] }));
+vi.mock('@/store/project', () => ({
+ projectListItemSelector: () => () => store.project,
+ useProjectStore: (selector: () => unknown) => selector(),
+}));
+vi.mock('@/features/Projects/ProjectAvatar', () => ({
+ default: () => createElement('span', { 'data-testid': 'project-avatar' }),
+}));
+vi.mock('@/features/GroupAvatar', () => ({
+ default: ({ avatars }: { avatars: { seed: string }[] }) =>
+ createElement('span', {
+ 'data-members': avatars.map((avatar) => avatar.seed).join(','),
+ 'data-testid': 'group-avatar',
+ }),
+}));
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => () => {},
+}));
+vi.mock('@/features/Workspace/WorkspaceLink', () => ({
+ default: ({ to: _to, ...rest }: { to: string }) => createElement('a', rest),
+}));
+
+const channel = (patch: Partial<ChannelListItem>) =>
+ ({ id: 'chn_1', projectId: null, title: 'Marketing', ...patch }) as ChannelListItem;
+const renderRow = (item: ChannelListItem) =>
+ render(
+ createElement(ChannelConversation, { active: false, activeAt: new Date(), channel: item }),
+ );
+const member = (id: string) => ({
+ actorType: 'agent' as const,
+ avatar: null,
+ backgroundColor: null,
+ id,
+ name: id,
+});
+
+describe('ChannelConversation avatar', () => {
+ it('pictures the members of a standalone Channel', () => {
+ store.project = undefined;
+ renderRow(channel({ memberAvatars: [member('agt_a'), member('agt_b')] }));
+ expect(screen.getByTestId('group-avatar').dataset.members).toBe('agt_a,agt_b');
+ });
+
+ it('keeps "#" while no one else has joined', () => {
+ store.project = undefined;
+ renderRow(channel({ memberAvatars: [] }));
+ expect(screen.queryByTestId('group-avatar')).toBeNull();
+ });
+
+ it('keeps the project logo for a project Channel', () => {
+ store.project = { id: 'prj_1', name: 'Project' };
+ renderRow(channel({ memberAvatars: [member('agt_a')], projectId: 'prj_1' }));
+ expect(screen.getByTestId('project-avatar')).toBeTruthy();
+ expect(screen.queryByTestId('group-avatar')).toBeNull();
+ });
+});
diff --git a/src/features/MessageList/ChannelConversation.tsx b/src/features/MessageList/ChannelConversation.tsx
index bf076ea41bb..ebb400a2c26 100644
--- a/src/features/MessageList/ChannelConversation.tsx
+++ b/src/features/MessageList/ChannelConversation.tsx
@@ -9,6 +9,7 @@ import { HashIcon } from 'lucide-react';
import { memo } from 'react';
import { useChannelMenu } from '@/features/Channels/useChannelMenu';
+import GroupAvatar from '@/features/GroupAvatar';
import ProjectAvatar from '@/features/Projects/ProjectAvatar';
import { projectListItemSelector, useProjectStore } from '@/store/project';
@@ -25,8 +26,15 @@ interface ChannelConversationProps {
/** 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();
- // A Channel grouped under a project wears that project's logo; a standalone one keeps "#".
+ // A Channel grouped under a project wears that project's logo; a standalone one pictures
+ // its members like a group chat, and keeps "#" until someone else joins.
const project = useProjectStore(projectListItemSelector(channel.projectId));
+ const members = channel.memberAvatars ?? [];
+ const channelMark = (
+ <span {...stylex.props(styles.channelMark)}>
+ <Icon color={cssVar.colorTextSecondary} icon={HashIcon} size={9} />
+ </span>
+ );
return (
<ConversationRow
@@ -48,9 +56,20 @@ const ChannelConversation = memo<ChannelConversationProps>(({ active, activeAt,
name={project.name}
size={AVATAR_SIZE}
/>
- <span {...stylex.props(styles.channelMark)}>
- <Icon color={cssVar.colorTextSecondary} icon={HashIcon} size={9} />
- </span>
+ {channelMark}
+ </>
+ ) : members.length ? (
+ <>
+ <GroupAvatar
+ size={AVATAR_SIZE}
+ avatars={members.map((member) => ({
+ avatar: member.avatar || (member.actorType === 'user' ? member.name : null),
+ background: member.backgroundColor ?? undefined,
+ seed: member.id,
+ title: member.name ?? undefined,
+ }))}
+ />
+ {channelMark}
</>
) : (
<Avatar