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.

✨ feat(channel): show a thread preview card under its root message (#22914)

Arvin Xuc1744e4b71b2
diff --git a/locales/en-US/channel.json b/locales/en-US/channel.json
index 0eac215d58f..7ee413223f6 100644
--- a/locales/en-US/channel.json
+++ b/locales/en-US/channel.json
@@ -246,6 +246,8 @@
"submit": "Create",
"thread": "Thread",
"threadArchivedNotice": "This thread is archived. Its replies stay readable, but it takes no new messages.",
+ "threadCard.messages_one": "{{count}} message",
+ "threadCard.messages_other": "{{count}} messages",
"threadComposer": "Reply in thread",
"threadDivider": "Replies in this thread",
"threadEmpty": "Keep discussing this message here.",
diff --git a/locales/zh-CN/channel.json b/locales/zh-CN/channel.json
index eaa77b90936..73e56fe7c7f 100644
--- a/locales/zh-CN/channel.json
+++ b/locales/zh-CN/channel.json
@@ -246,6 +246,8 @@
"submit": "创建",
"thread": "线程",
"threadArchivedNotice": "此线程已归档。回复仍可查看,但不再接收新消息。",
+ "threadCard.messages_one": "{{count}} 条消息",
+ "threadCard.messages_other": "{{count}} 条消息",
"threadComposer": "在线程中回复",
"threadDivider": "此线程中的回复",
"threadEmpty": "在这里接着讨论这条消息。",
diff --git a/packages/database/src/repositories/channel/__tests__/view.test.ts b/packages/database/src/repositories/channel/__tests__/view.test.ts
index b55582bc5c2..72559544bea 100644
--- a/packages/database/src/repositories/channel/__tests__/view.test.ts
+++ b/packages/database/src/repositories/channel/__tests__/view.test.ts
@@ -117,6 +117,46 @@ describe('Channel public view', () => {
).rejects.toMatchObject({ code: 'BAD_REQUEST' });
});
+ it('summarizes each thread under its root on the main timeline only', async () => {
+ const { asOwner, channel } = await fixture.createTeamChannel();
+ const root = await asOwner.send(channel.id, {
+ content: 'Root',
+ requestKey: 'root',
+ routing: 'fallback',
+ });
+ const quiet = await asOwner.send(channel.id, {
+ content: 'Quiet root',
+ requestKey: 'quiet',
+ routing: 'fallback',
+ });
+ const thread = await asOwner.createThread(channel.id, { rootMessageId: root.id });
+ const empty = await asOwner.createThread(channel.id, { rootMessageId: quiet.id });
+ for (const content of ['First reply', 'Latest reply'])
+ await asOwner.send(channel.id, {
+ content,
+ requestKey: content,
+ routing: 'fallback',
+ threadId: thread.id,
+ });
+
+ const main = await asOwner.detail(channel.id);
+ expect(main.threads.find((entry) => entry.id === thread.id)).toMatchObject({
+ lastReply: { author: { type: 'user' }, content: 'Latest reply' },
+ replyCount: 2,
+ });
+ expect(main.threads.find((entry) => entry.id === empty.id)).toMatchObject({
+ lastReply: null,
+ replyCount: 0,
+ });
+ // A root outside the loaded page and a thread view skip the summary scan.
+ const older = await asOwner.detail(channel.id, { before: quiet.sequence, limit: 1 });
+ expect(older.threads.find((entry) => entry.id === empty.id)).not.toHaveProperty('replyCount');
+ const inThread = await asOwner.detail(channel.id, { threadId: thread.id });
+ expect(inThread.threads.find((entry) => entry.id === thread.id)).not.toHaveProperty(
+ 'replyCount',
+ );
+ });
+
it.each([false, true])(
'includes the reply author so a new thread can answer without a mention (workspace: %s)',
async (workspace) => {
diff --git a/packages/database/src/repositories/channel/view.ts b/packages/database/src/repositories/channel/view.ts
index 196fe5f97c1..12fcebafa41 100644
--- a/packages/database/src/repositories/channel/view.ts
+++ b/packages/database/src/repositories/channel/view.ts
@@ -1,4 +1,4 @@
-import { and, asc, desc, eq, getTableColumns, inArray, isNull, lt, sql } from 'drizzle-orm';
+import { and, asc, count, desc, eq, getTableColumns, inArray, isNull, lt, sql } from 'drizzle-orm';
import {
agentOperations,
@@ -92,6 +92,49 @@ const sourceTopicsByMessage = async (
return new Map(rows.map((row) => [row.messageId!, { id: row.topicId, title: row.title }]));
};
+const THREAD_PREVIEW_LENGTH = 240;
+
+type ThreadSummary = {
+ lastReply: Pick<ReturnType<typeof publicMessage>, 'author' | 'content' | 'createdAt' | 'id'>;
+ replyCount: number;
+};
+
+/** Reply count and newest reply per thread, so a root can show what it branched into. */
+const threadSummaries = async (tx: Transaction, channelId: string, threadIds: string[]) => {
+ if (!threadIds.length) return new Map<string, ThreadSummary>();
+ const scope = and(
+ eq(channelMessages.channelId, channelId),
+ inArray(channelMessages.threadId, threadIds),
+ );
+ const [counts, latest] = await Promise.all([
+ tx
+ .select({ replyCount: count(), threadId: channelMessages.threadId })
+ .from(channelMessages)
+ .where(scope)
+ .groupBy(channelMessages.threadId),
+ tx
+ .selectDistinctOn([channelMessages.threadId], publicMessageColumns)
+ .from(channelMessages)
+ .leftJoin(users, eq(users.id, channelMessages.userId))
+ .leftJoin(agents, eq(agents.id, channelMessages.agentId))
+ .where(scope)
+ .orderBy(asc(channelMessages.threadId), desc(channelMessages.sequence)),
+ ]);
+ const replyCounts = new Map(counts.map((row) => [row.threadId, row.replyCount]));
+ return new Map<string, ThreadSummary>(
+ latest.map((row) => {
+ const { author, content, createdAt, id } = publicMessage(row, []);
+ return [
+ row.threadId!,
+ {
+ lastReply: { author, content: content.slice(0, THREAD_PREVIEW_LENGTH), createdAt, id },
+ replyCount: replyCounts.get(row.threadId) ?? 0,
+ },
+ ];
+ }),
+ );
+};
+
export const readChannelView = async (
tx: Transaction,
channelId: string,
@@ -194,6 +237,12 @@ export const readChannelView = async (
)
: [];
const page = reversed.slice(0, limit).reverse();
+ // Only main-timeline roots on this page show a thread card; other views skip the scan.
+ const pageIds = new Set(page.map((message) => message.id));
+ const summarized = options.threadId
+ ? []
+ : threads.filter((entry) => pageIds.has(entry.rootMessageId)).map((entry) => entry.id);
+ const summaries = await threadSummaries(tx, channelId, summarized);
const quoteIds = [
...new Set(
[...page, ...(rootMessage ? [rootMessage] : [])].flatMap((message) =>
@@ -244,9 +293,16 @@ export const readChannelView = async (
hasMore: reversed.length > limit,
jobs,
members,
- threads: threads.map((thread) => {
- const title = thread.metadata?.title;
- return typeof title === 'string' && title ? { ...thread, title } : thread;
+ threads: threads.map((entry) => {
+ const title = entry.metadata?.title;
+ const named = typeof title === 'string' && title ? { ...entry, title } : entry;
+ return summarized.includes(entry.id)
+ ? {
+ ...named,
+ lastReply: summaries.get(entry.id)?.lastReply ?? null,
+ replyCount: summaries.get(entry.id)?.replyCount ?? 0,
+ }
+ : named;
}),
rootMessage: rootMessage
? {
diff --git a/packages/locales/src/default/channel.ts b/packages/locales/src/default/channel.ts
index d52391c1657..5dce3f38482 100644
--- a/packages/locales/src/default/channel.ts
+++ b/packages/locales/src/default/channel.ts
@@ -126,6 +126,8 @@ export default {
'startThread': 'Start thread',
'openThread': 'Open thread',
'openThreadPage': 'Open as page',
+ 'threadCard.messages_one': '{{count}} message',
+ 'threadCard.messages_other': '{{count}} messages',
'closeThread': 'Close thread',
'thread': 'Thread',
'threadDivider': 'Replies in this thread',
diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.ts
index 3c7bf36c158..25db199e71c 100644
--- a/packages/types/src/channel.ts
+++ b/packages/types/src/channel.ts
@@ -445,6 +445,13 @@ export type ChannelReplyJob = Pick<
export interface ChannelPublicThread {
followerMemberIds: string[];
id: string;
+ /**
+ * The newest reply, for threads whose root is on the loaded main-timeline page. Absent in
+ * thread views and in views cached before summaries existed.
+ */
+ lastReply?: Pick<ChannelPublicMessage, 'author' | 'content' | 'createdAt' | 'id'> | null;
+ /** Replies in the thread, under the same conditions as `lastReply`. */
+ replyCount?: number;
rootMessageId: string;
rootSequence: number;
status: ChannelThreadStatus;
diff --git a/src/features/Channels/ChannelMessage.test.tsx b/src/features/Channels/ChannelMessage.test.tsx
index 27d1de1606c..dd01fa58b64 100644
--- a/src/features/Channels/ChannelMessage.test.tsx
+++ b/src/features/Channels/ChannelMessage.test.tsx
@@ -239,3 +239,87 @@ describe('ChannelMessage works', () => {
expect(screen.queryByText('Show works in channels')).toBeNull();
});
});
+
+describe('ChannelMessage thread card', () => {
+ const root = { ...message({ avatar: null, id: 'user-other', name: 'Ann', type: 'user' }) };
+ const withThread = (thread: Record<string, unknown>) =>
+ ({
+ ...detail,
+ threads: [{ followerMemberIds: [], id: 'cht_1', rootMessageId: root.id, ...thread }],
+ }) as unknown as ChannelDetail;
+
+ it('shows the thread title, reply count and latest reply, and opens the thread', () => {
+ const onOpenThread = vi.fn();
+ render(
+ <ChannelMessage
+ message={{ ...root, content: 'Topic header is unclickable\nmore detail' }}
+ detail={withThread({
+ lastReply: {
+ author: { avatar: null, id: 'agt_1', name: 'Nasa', type: 'agent' },
+ content: 'PR is up\nsecond line',
+ createdAt: new Date(),
+ id: 'msg_2',
+ },
+ replyCount: 5,
+ })}
+ onOpenThread={onOpenThread}
+ />,
+ );
+
+ expect(screen.getByText('Topic header is unclickable')).toBeTruthy();
+ expect(screen.getByText('threadCard.messages')).toBeTruthy();
+ // The sidebar's thread glyph, not a branch, leads the title row only.
+ const card = screen.getByRole('button', { name: /Topic header is unclickable/ });
+ const [titleRow, replyRow] = card.children;
+ expect(titleRow.firstElementChild?.querySelector('.lucide-corner-down-right')).not.toBeNull();
+ expect(replyRow.querySelector('.lucide-corner-down-right')).toBeNull();
+ expect(card.querySelector('.lucide-git-branch')).toBeNull();
+ expect(screen.getByText('Nasa')).toBeTruthy();
+ expect(screen.getByText('PR is up')).toBeTruthy();
+
+ fireEvent.click(screen.getByRole('button', { name: /Topic header is unclickable/ }));
+ expect(onOpenThread).toHaveBeenCalledWith('cht_1');
+ });
+
+ it('shows the viewer’s own latest reply with their live avatar', () => {
+ render(
+ <ChannelMessage
+ message={root}
+ detail={withThread({
+ lastReply: {
+ author: { avatar: null, id: 'user-self', name: 'Me', type: 'user' },
+ content: 'On it',
+ createdAt: new Date(),
+ id: 'msg_3',
+ },
+ replyCount: 1,
+ })}
+ />,
+ );
+
+ expect(screen.getByText('me')).toBeTruthy();
+ });
+
+ it('names the card after the title an Agent gave the thread', () => {
+ render(
+ <ChannelMessage
+ detail={withThread({ replyCount: 1, title: 'Header click fix' })}
+ message={{ ...root, content: 'Topic header is unclickable' }}
+ />,
+ );
+
+ expect(screen.getByText('Header click fix')).toBeTruthy();
+ });
+
+ it('still offers the thread when a cached view has no summary', () => {
+ render(<ChannelMessage detail={withThread({})} message={root} />);
+
+ expect(screen.getByText('thread')).toBeTruthy();
+ expect(screen.getByText('openThread')).toBeTruthy();
+ // A cached view without a reply row still shows the glyph in front of the title.
+ expect(
+ screen.getByRole('button', { name: /openThread/ }).querySelector('.lucide-corner-down-right'),
+ ).not.toBeNull();
+ expect(screen.queryByText('threadCard.messages')).toBeNull();
+ });
+});
diff --git a/src/features/Channels/ChannelMessage.tsx b/src/features/Channels/ChannelMessage.tsx
index 4f11bdd89de..ecc575460be 100644
--- a/src/features/Channels/ChannelMessage.tsx
+++ b/src/features/Channels/ChannelMessage.tsx
@@ -44,6 +44,7 @@ import type { ReplyTopic } from './ReplyTopicPanel';
import { ReplyWorks } from './ReplyWorks';
import { styles } from './styles';
import type { ChannelThreadDraft } from './threadDraft';
+import { ThreadPreviewCard } from './ThreadPreviewCard';
import type { ChannelReplyTarget } from './useReplyTarget';
const MentionChip = ({ children }: { children?: ReactNode }) => (
@@ -224,18 +225,6 @@ export const ChannelMessage = ({
placement="left"
showHeader={!compact}
style={{ paddingInlineStart: 48 }}
- actionAddon={
- thread ? (
- <Button
- icon={GitBranch}
- size="small"
- type="text"
- onClick={() => onOpenThread?.(thread.id)}
- >
- {t('openThread')}
- </Button>
- ) : undefined
- }
avatar={{
avatar: authorAvatar(message.author),
title: message.author.name || t('deletedMember'),
@@ -316,6 +305,13 @@ export const ChannelMessage = ({
<MessageText content={message.content} names={mentionNames} />
))}
{!!message.works?.length && <ReplyWorks works={message.works} />}
+ {thread && (
+ <ThreadPreviewCard
+ root={message}
+ thread={thread}
+ onOpen={() => onOpenThread?.(thread.id)}
+ />
+ )}
</Flexbox>
}
titleAddon={
diff --git a/src/features/Channels/ThreadPreviewCard.tsx b/src/features/Channels/ThreadPreviewCard.tsx
new file mode 100644
index 00000000000..84cbd5f1339
--- /dev/null
+++ b/src/features/Channels/ThreadPreviewCard.tsx
@@ -0,0 +1,167 @@
+import type { ChannelPublicMessage, ChannelPublicThread } from '@lobechat/types';
+import { Avatar, Icon } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import dayjs from 'dayjs';
+import relativeTime from 'dayjs/plugin/relativeTime';
+import { ChevronRight, CornerDownRight } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import UserAvatar from '@/features/User/UserAvatar';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
+import { authorAvatar, isCurrentUserAuthor } from './memberName';
+import { threadTitle } from './threadTitle';
+
+dayjs.extend(relativeTime);
+
+const styles = stylex.create({
+ card: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 4,
+ alignSelf: 'flex-start',
+ width: '100%',
+ maxWidth: 520,
+ // Sit close to the message it continues: the body's 8px gap plus the paragraph's trailing
+ // margin left the card looking detached.
+ marginBlockStart: -6,
+ marginBlockEnd: 0,
+ marginInline: 0,
+ paddingBlock: 6,
+ paddingInline: 10,
+ // A quiet fill instead of a bordered box: the card follows the message, it is not a new one.
+ borderWidth: 0,
+ borderStyle: 'none',
+ borderRadius: cssVar.borderRadius,
+ font: 'inherit',
+ textAlign: 'start',
+ backgroundColor: {
+ 'default': cssVar.colorFillQuaternary,
+ ':hover': cssVar.colorFillTertiary,
+ },
+ cursor: 'pointer',
+ },
+ row: {
+ display: 'flex',
+ gap: 6,
+ alignItems: 'center',
+ minWidth: 0,
+ },
+ // Indented past the glyph column (16px glyph + 6px gap) so the avatar lines up with the title.
+ replyRow: {
+ paddingInlineStart: 22,
+ },
+ threadIcon: {
+ display: 'inline-flex',
+ flexShrink: 0,
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: 16,
+ color: cssVar.colorTextSecondary,
+ },
+ title: {
+ overflow: 'hidden',
+ minWidth: 0,
+ fontSize: 13,
+ fontWeight: 500,
+ color: cssVar.colorText,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ count: {
+ display: 'inline-flex',
+ flexShrink: 0,
+ alignItems: 'center',
+ fontSize: 12,
+ color: cssVar.colorTextSecondary,
+ },
+ author: {
+ flexShrink: 0,
+ maxWidth: 160,
+ overflow: 'hidden',
+ fontSize: 12,
+ fontWeight: 500,
+ color: cssVar.colorTextSecondary,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ preview: {
+ overflow: 'hidden',
+ flex: '1',
+ minWidth: 0,
+ fontSize: 12,
+ color: cssVar.colorTextSecondary,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ time: {
+ flexShrink: 0,
+ fontSize: 12,
+ color: cssVar.colorTextTertiary,
+ whiteSpace: 'nowrap',
+ // ChatItem hides every `time` inside a message until hover; this one is content, not a stamp.
+ opacity: 1,
+ },
+});
+
+/** A message's thread as a card under it: what it is about, how much was said, and the latest word. */
+export const ThreadPreviewCard = ({
+ onOpen,
+ root,
+ thread,
+}: {
+ onOpen?: () => void;
+ root: ChannelPublicMessage;
+ thread: ChannelPublicThread;
+}) => {
+ const { t } = useTranslation('channel');
+ const { lastReply, replyCount } = thread;
+ // Same rule as the message header: the viewer's own replies use their live avatar.
+ const isOwnReply = useUserStore(
+ (s) => !!lastReply && isCurrentUserAuthor(lastReply.author, userProfileSelectors.userId(s)),
+ );
+ return (
+ <button type="button" {...stylex.props(styles.card)} onClick={onOpen}>
+ <span {...stylex.props(styles.row)}>
+ {/* The sidebar's thread glyph, not a branch. */}
+ <span {...stylex.props(styles.threadIcon)}>
+ <Icon icon={CornerDownRight} size={14} />
+ </span>
+ <span {...stylex.props(styles.title)}>{threadTitle(root, thread) ?? t('thread')}</span>
+ <span {...stylex.props(styles.count)}>
+ {/* Views cached before thread summaries existed only know that the thread exists. */}
+ {replyCount ? t('threadCard.messages', { count: replyCount }) : t('openThread')}
+ <Icon icon={ChevronRight} size={12} />
+ </span>
+ </span>
+ {lastReply && (
+ <span {...stylex.props(styles.row, styles.replyRow)}>
+ {isOwnReply ? (
+ <UserAvatar shape="circle" size={16} />
+ ) : (
+ <Avatar
+ avatar={authorAvatar(lastReply.author)}
+ shape="circle"
+ size={16}
+ title={lastReply.author.name ?? undefined}
+ />
+ )}
+ <span {...stylex.props(styles.author)}>
+ {lastReply.author.name || t('deletedMember')}
+ </span>
+ <span {...stylex.props(styles.preview)}>
+ {lastReply.content.split('\n')[0] || t('reply.attachment')}
+ </span>
+ <time
+ dateTime={new Date(lastReply.createdAt).toISOString()}
+ {...stylex.props(styles.time)}
+ >
+ {dayjs(lastReply.createdAt).fromNow()}
+ </time>
+ </span>
+ )}
+ </button>
+ );
+};