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(topic): show bot conversation initiator avatars (#20943)

Rdmclin21cc1ee039111
diff --git a/packages/database/src/models/__tests__/topicCreator.test.ts b/packages/database/src/models/__tests__/topicCreator.test.ts
new file mode 100644
index 00000000000..18fcdb1465e
--- /dev/null
+++ b/packages/database/src/models/__tests__/topicCreator.test.ts
@@ -0,0 +1,77 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { messages, topics, users } from '../../schemas';
+import { TopicModel } from '../topic';
+
+const db = await getTestDB();
+const owner = 'topic-creator-owner';
+const model = new TopicModel(db, owner);
+const creator = {
+ avatar: 'https://example.com/bot.png',
+ fullName: 'LobehubBot',
+ id: '123',
+ platform: 'discord',
+};
+const bot = {
+ applicationId: 'app',
+ isOwner: false,
+ platform: 'discord',
+ platformThreadId: 'thread',
+ senderExternalUserId: '456',
+};
+
+beforeEach(async () => {
+ await db.insert(users).values([{ id: owner }, { id: 'other-owner' }]);
+ await db.insert(topics).values([
+ { id: 'bot-topic', userId: owner, metadata: { bot } },
+ { id: 'empty-topic', userId: owner, metadata: { bot } },
+ { id: 'personal-topic', userId: owner },
+ { id: 'foreign-topic', userId: 'other-owner', metadata: { bot } },
+ ]);
+ await db.insert(messages).values([
+ {
+ id: 'first',
+ topicId: 'bot-topic',
+ role: 'user',
+ userId: owner,
+ createdAt: new Date('2026-10-01'),
+ metadata: { botSender: creator },
+ },
+ {
+ id: 'second',
+ topicId: 'bot-topic',
+ role: 'user',
+ userId: owner,
+ createdAt: new Date('2026-10-02'),
+ metadata: { botSender: { ...creator, id: '456', fullName: 'Later participant' } },
+ },
+ {
+ id: 'foreign',
+ topicId: 'foreign-topic',
+ role: 'user',
+ userId: 'other-owner',
+ metadata: { botSender: creator },
+ },
+ ]);
+});
+afterEach(async () => {
+ await db.delete(users);
+});
+
+describe('topic creator list projection', () => {
+ it.each(['sidebar', 'feed', 'feed-preview'] as const)(
+ 'returns the original sender in %s without leaking another owner',
+ async (mode) => {
+ const rows =
+ mode === 'sidebar'
+ ? (await model.query()).items
+ : await model.queryTopics({ withLastMessage: mode === 'feed-preview' });
+ expect(rows.find((row) => row.id === 'bot-topic')?.metadata?.botCreator).toEqual(creator);
+ expect(rows.find((row) => row.id === 'empty-topic')?.metadata?.botCreator).toBeNull();
+ expect(rows.find((row) => row.id === 'personal-topic')?.metadata?.botCreator).toBeUndefined();
+ expect(rows.some((row) => row.id === 'foreign-topic')).toBe(false);
+ },
+ );
+});
diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.ts
index ae96979f00b..95d9236e53c 100644
--- a/packages/database/src/models/topic.ts
+++ b/packages/database/src/models/topic.ts
@@ -67,6 +67,7 @@ import {
trashStamp,
} from '../utils/softDelete';
import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
+import { topicMetadataWithCreator } from './topicCreator';
import { recomputeTopicUsage } from './topicUsage';
type OnboardingSessionMetadataPatch = Partial<NonNullable<ChatTopicMetadata['onboardingSession']>>;
@@ -538,7 +539,6 @@ export class TopicModel {
* it β€” and use {@link mine} (which skips this helper).
*/
private notShareVisitor = () => (this.includeShareVisitor ? undefined : notShareVisitorTopic());
- // **************** Query *************** //
query = async ({
agentId,
@@ -613,7 +613,6 @@ export class TopicModel {
// abandoned `running` row from a crashed earlier run sorts below the live
// one. Not scoped by `ownership()` β€” in a workspace the run may have been
// started by another member, and the topic join is already ownership-gated.
- // Same shape as the `queryTopics` feed's column of the same name.
const runStartedAtSubquery = this.db
.select({ value: agentOperations.startedAt })
.from(agentOperations)
@@ -675,7 +674,6 @@ export class TopicModel {
editingGroupId ? sql`${topics.metadata}->>'editingGroupId' = ${editingGroupId}` : undefined,
);
- // If groupId is provided, query topics by groupId directly
if (groupId) {
const whereCondition = and(
this.ownership(),
@@ -703,7 +701,7 @@ export class TopicModel {
favorite: topics.favorite,
historySummary: topics.historySummary,
id: topics.id,
- metadata: topics.metadata,
+ metadata: topicMetadataWithCreator(this.db, this.messageOwnership()),
projectId: topics.projectId,
projectWorkingDirectoryId: topics.projectWorkingDirectoryId,
model: topics.model,
@@ -784,7 +782,7 @@ export class TopicModel {
favorite: topics.favorite,
historySummary: topics.historySummary,
id: topics.id,
- metadata: topics.metadata,
+ metadata: topicMetadataWithCreator(this.db, this.messageOwnership()),
projectId: topics.projectId,
projectWorkingDirectoryId: topics.projectWorkingDirectoryId,
model: topics.model,
@@ -859,7 +857,7 @@ export class TopicModel {
favorite: topics.favorite,
historySummary: topics.historySummary,
id: topics.id,
- metadata: topics.metadata,
+ metadata: topicMetadataWithCreator(this.db, this.messageOwnership()),
projectId: topics.projectId,
projectWorkingDirectoryId: topics.projectWorkingDirectoryId,
model: topics.model,
@@ -1116,6 +1114,7 @@ export class TopicModel {
return this.db
.select({
...getTableColumns(topics),
+ metadata: topicMetadataWithCreator(this.db, this.messageOwnership()),
parentVisibility: parentVisibilityColumn,
runStartedAt: runStartedAtColumn,
})
@@ -1154,6 +1153,7 @@ export class TopicModel {
const rows = await this.db
.select({
...getTableColumns(topics),
+ metadata: topicMetadataWithCreator(this.db, this.messageOwnership()),
lastAssistantMessage: sql<string | null>`(${lastAssistantMessageSubquery})`.as(
'last_assistant_message',
),
diff --git a/packages/database/src/models/topicCreator.ts b/packages/database/src/models/topicCreator.ts
new file mode 100644
index 00000000000..a5a82677234
--- /dev/null
+++ b/packages/database/src/models/topicCreator.ts
@@ -0,0 +1,21 @@
+import type { ChatTopicMetadata } from '@lobechat/types';
+import { and, asc, eq, type SQL, sql } from 'drizzle-orm';
+
+import { messages, topics } from '../schemas';
+import type { LobeChatDatabase } from '../type';
+
+/** Resolve the initiator, never the latest participant or the bot owner. */
+export const topicMetadataWithCreator = (db: LobeChatDatabase, ownership?: SQL) => {
+ const firstSender = db
+ .select({ value: sql`${messages.metadata}->'botSender'` })
+ .from(messages)
+ .where(and(eq(messages.topicId, topics.id), eq(messages.role, 'user'), ownership))
+ .orderBy(asc(messages.createdAt), asc(messages.id))
+ .limit(1);
+
+ return sql<ChatTopicMetadata | null>`CASE
+ WHEN jsonb_exists(${topics.metadata}, 'bot')
+ THEN ${topics.metadata} || jsonb_build_object('botCreator', (${firstSender}))
+ ELSE ${topics.metadata}
+ END`;
+};
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.ts
index 59bb8662ad3..926c6dc38c7 100644
--- a/packages/types/src/topic/topic.ts
+++ b/packages/types/src/topic/topic.ts
@@ -6,13 +6,12 @@ import type { HeterogeneousReasoningEffort } from '../agent/heteroSelectorCapabi
import type { SerializedAgentHook } from '../agentHook';
import type { WorkingDirConfig } from '../device';
import { workingDirConfigSchema } from '../device';
+import type { BotSenderMetadata } from '../message';
import type { BaseDataModel } from '../meta';
import type { OnboardingUnderstandingSession } from '../understanding';
import type { OnboardingTaskRecommendationSession } from '../user/onboardingTasks';
-// Type definitions
export type ShareVisibility = 'private' | 'link';
-
export type TimeGroupId =
'today' | 'yesterday' | 'week' | 'month' | `${number}-${string}` | `${number}`;
@@ -122,6 +121,7 @@ export interface ChatTopicMetadata {
};
bot?: ChatTopicBotContext;
+ botCreator?: BotSenderMetadata | null;
boundDeviceId?: string;
cronJobId?: string;
/**
diff --git a/src/features/AgentSidebar/Topic/List/Item/index.tsx b/src/features/AgentSidebar/Topic/List/Item/index.tsx
index 49e4d0948fb..0130911ecb4 100644
--- a/src/features/AgentSidebar/Topic/List/Item/index.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/index.tsx
@@ -281,7 +281,10 @@ const TopicItemRow = memo<TopicItemRowProps>(
const activeWorkspaceSlug = useActiveWorkspaceSlug();
// Creator of the topic β€” resolves only inside an active workspace; drives
// the identity-first icon layout below.
- const author = useTopicCreator(isSharedAgent ? userId : undefined);
+ const author = useTopicCreator(
+ isSharedAgent && !metadata?.bot ? userId : undefined,
+ metadata?.botCreator,
+ );
const loadingRingColor = isDarkMode
? cssVar.colorWarningBorder
@@ -572,7 +575,11 @@ const TopicItemRow = memo<TopicItemRowProps>(
}
/>
) : author ? (
- <TopicCreatorAvatar corner={ownIconNode} userId={userId} />
+ <TopicCreatorAvatar
+ botCreator={metadata?.botCreator}
+ corner={ownIconNode}
+ userId={userId}
+ />
) : (
(ownIconNode ?? idleIconPlaceholder)
);
diff --git a/src/features/TopicCreatorAvatar/index.test.tsx b/src/features/TopicCreatorAvatar/index.test.tsx
index a48037c3fe1..9f73d2b5a46 100644
--- a/src/features/TopicCreatorAvatar/index.test.tsx
+++ b/src/features/TopicCreatorAvatar/index.test.tsx
@@ -37,6 +37,35 @@ vi.mock('@/components/Avatar', () => ({
}));
describe('TopicCreatorAvatar', () => {
+ it('shows the bot conversation initiator instead of the workspace bot owner', () => {
+ useAuthorInfoMock.mockReturnValue({ avatar: 'owner.png', fullName: 'Bot owner' });
+ const { getByTestId } = render(
+ <TopicCreatorAvatar
+ userId="owner"
+ botCreator={{
+ id: '123',
+ platform: 'discord',
+ avatar: 'sender.png',
+ fullName: 'LobehubBot',
+ }}
+ />,
+ );
+ expect(getByTestId('avatar').getAttribute('data-avatar')).toBe('sender.png');
+ expect(getByTestId('avatar').getAttribute('data-title')).toBe('LobehubBot');
+ });
+
+ it('uses sender initials without borrowing the owner avatar', () => {
+ useAuthorInfoMock.mockReturnValue({ avatar: 'owner.png', fullName: 'Bot owner' });
+ const { getByTestId } = render(
+ <TopicCreatorAvatar
+ botCreator={{ id: '123', platform: 'discord', username: 'LobehubBot' }}
+ userId="owner"
+ />,
+ );
+ expect(getByTestId('avatar').getAttribute('data-avatar')).toBe('');
+ expect(getByTestId('avatar').getAttribute('data-name')).toBe('LobehubBot');
+ });
+
it("renders a workspace member's round avatar (any member, including self)", () => {
useAuthorInfoMock.mockReturnValue({ avatar: 'https://x/y.png', fullName: 'Alice' });
diff --git a/src/features/TopicCreatorAvatar/index.tsx b/src/features/TopicCreatorAvatar/index.tsx
index 3ef2f3478db..e3470e964fb 100644
--- a/src/features/TopicCreatorAvatar/index.tsx
+++ b/src/features/TopicCreatorAvatar/index.tsx
@@ -1,5 +1,6 @@
'use client';
+import type { BotSenderMetadata } from '@lobechat/types';
import { Tooltip } from '@lobehub/ui';
import { cssVar } from 'antd-style';
import { memo, type ReactNode } from 'react';
@@ -8,14 +9,22 @@ import { useAuthorInfo } from '@/business/client/hooks/useAuthorInfo';
import Avatar from '@/components/Avatar';
/**
- * Resolves a topic creator's profile from the *active workspace* members.
- * `useAuthorInfo` is a business slot: cloud resolves the member profile, the
- * open-source build is a no-op β€” and it returns `undefined` without an active
- * workspace, so all creator-avatar UI disappears in personal mode.
+ * Prefer the bot-channel initiator over the account that owns the bot.
+ * Ordinary topics resolve their creator from active workspace members; the
+ * open-source business slot returns undefined for those member profiles.
*/
-export const useTopicCreator = (userId?: string) => useAuthorInfo(userId);
+export const useTopicCreator = (userId?: string, botCreator?: BotSenderMetadata | null) => {
+ const author = useAuthorInfo(userId);
+ return botCreator
+ ? {
+ avatar: botCreator.avatar,
+ fullName: botCreator.fullName || botCreator.username || botCreator.id,
+ }
+ : author;
+};
interface TopicCreatorAvatarProps {
+ botCreator?: BotSenderMetadata | null;
/**
* Optional mini node (execution status, bot platform icon, PR marker, …)
* overlaid at the avatar's bottom-right corner. The creator stays the
@@ -29,68 +38,68 @@ interface TopicCreatorAvatarProps {
}
/**
- * Round creator avatar for a workspace topic row's leading icon slot β€” it
- * replaces the default `#` placeholder so the shared list reads like a
- * conversation list. Renders nothing when the creator doesn't resolve
- * (personal mode / unknown member).
+ * Round creator avatar for a topic row, with an optional status/platform badge.
+ * Renders nothing when neither a bot initiator nor a workspace member resolves.
*/
-const TopicCreatorAvatar = memo<TopicCreatorAvatarProps>(({ userId, size = 20, corner }) => {
- const author = useTopicCreator(userId);
+const TopicCreatorAvatar = memo<TopicCreatorAvatarProps>(
+ ({ userId, size = 20, corner, botCreator }) => {
+ const author = useTopicCreator(userId, botCreator);
- if (!author) return null;
+ if (!author) return null;
- const avatar = (
- <Tooltip title={author.fullName}>
- <Avatar
- avatar={author.avatar ?? undefined}
- name={author.fullName ?? undefined}
- shape={'circle'}
- size={size}
- style={{ flex: 'none' }}
- title={author.fullName ?? undefined}
- />
- </Tooltip>
- );
+ const avatar = (
+ <Tooltip title={author.fullName}>
+ <Avatar
+ avatar={author.avatar ?? undefined}
+ name={author.fullName ?? undefined}
+ shape={'circle'}
+ size={size}
+ style={{ flex: 'none' }}
+ title={author.fullName ?? undefined}
+ />
+ </Tooltip>
+ );
- if (!corner) return avatar;
+ if (!corner) return avatar;
- return (
- <span style={{ display: 'inline-flex', lineHeight: 0, position: 'relative' }}>
- {avatar}
- <span
- style={{
- alignItems: 'center',
- // Solid panel background so the badge glyph reads cleanly instead of
- // colliding with the avatar underneath; the ring blends it into the
- // sidebar like a Slack/Discord presence badge.
- background: cssVar.colorBgLayout,
- borderRadius: '50%',
- bottom: -4,
- boxShadow: `0 0 0 1.5px ${cssVar.colorBgLayout}`,
- display: 'inline-flex',
- height: 13,
- justifyContent: 'center',
- lineHeight: 0,
- position: 'absolute',
- right: -4,
- width: 13,
- }}
- >
+ return (
+ <span style={{ display: 'inline-flex', lineHeight: 0, position: 'relative' }}>
+ {avatar}
<span
style={{
alignItems: 'center',
+ // Solid panel background so the badge glyph reads cleanly instead of
+ // colliding with the avatar underneath; the ring blends it into the
+ // sidebar like a Slack/Discord presence badge.
+ background: cssVar.colorBgLayout,
+ borderRadius: '50%',
+ bottom: -4,
+ boxShadow: `0 0 0 1.5px ${cssVar.colorBgLayout}`,
display: 'inline-flex',
+ height: 13,
justifyContent: 'center',
- transform: 'scale(0.75)',
- transformOrigin: 'center',
+ lineHeight: 0,
+ position: 'absolute',
+ right: -4,
+ width: 13,
}}
>
- {corner}
+ <span
+ style={{
+ alignItems: 'center',
+ display: 'inline-flex',
+ justifyContent: 'center',
+ transform: 'scale(0.75)',
+ transformOrigin: 'center',
+ }}
+ >
+ {corner}
+ </span>
</span>
</span>
- </span>
- );
-});
+ );
+ },
+);
TopicCreatorAvatar.displayName = 'TopicCreatorAvatar';