🤯 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): improve conversation reading rhythm (#22026)
AmAzing-550054d175fb
diff --git a/src/features/Channels/ChannelConversation.tsx b/src/features/Channels/ChannelConversation.tsxindex f452073b20d..c2098a137ec 100644--- a/src/features/Channels/ChannelConversation.tsx+++ b/src/features/Channels/ChannelConversation.tsx@@ -2,7 +2,7 @@ import type { ChannelPublicMessage } from '@lobechat/types';import { Button, Empty, Flexbox } from '@lobehub/ui';import * as stylex from '@stylexjs/stylex';import { MessageSquare } from 'lucide-react';-import { useEffect, useRef, useState } from 'react';+import { Fragment, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import AsyncBoundary from '@/components/AsyncBoundary';@@ -20,6 +20,7 @@ import { ChannelMessage, ThreadRootMessage } from './ChannelMessage';import { Composer } from './Composer';import { JoinEventLine } from './JoinEventLine';import { channelJoinEvents, channelTimeline } from './joinEvents';+import { channelTimeFormatters, presentChannelTimeline } from './messagePresentation';import { ReplyActivity } from './ReplyActivity';import { styles } from './styles';import type { ChannelThreadDraft } from './threadDraft';@@ -43,7 +44,8 @@ const Timeline = ({onOpenThread,onStartThread,}: ChannelConversationProps) => {- const { t } = useTranslation('channel');+ const { t, i18n } = useTranslation('channel');+ const timeFormats = useMemo(() => channelTimeFormatters(i18n.language), [i18n.language]);const [before, setBefore] = useState<number>();const reply = useReplyTarget(channelDraftKey(channelId, threadId));const [jumpTarget, setJumpTarget] = useState<ChannelReplyTarget | null>(null);@@ -187,25 +189,38 @@ const Timeline = ({) : (<Empty icon={MessageSquare} title={t('conversationEmpty')} />))}- {timeline.map((item) =>- item.kind === 'event' ? (- <JoinEventLine event={item.event} key={item.event.id} />- ) : (- <ChannelMessage- detail={detail}- highlighted={highlighted === item.message.id}- key={item.message.id}- message={item.message}- threadId={threadId}- onJumpToMessage={jumpToMessage}- onOpenThread={onOpenThread}- onStartThread={channelArchived ? undefined : onStartThread}- onReply={- channelArchived || thread?.status === 'archived' ? undefined : selectReply- }- />- ),- )}+ {presentChannelTimeline(timeline).map(({ item, date, startsDay, continuation }) => (+ <Fragment key={item.kind === 'event' ? item.event.id : item.message.id}>+ {startsDay && (+ <div+ aria-label={timeFormats.date.format(date)}+ role="separator"+ {...stylex.props(styles.dateDivider)}+ >+ <span {...stylex.props(styles.dateLine)} />+ <time dateTime={date.toISOString()}>{timeFormats.date.format(date)}</time>+ <span {...stylex.props(styles.dateLine)} />+ </div>+ )}+ {item.kind === 'event' ? (+ <JoinEventLine event={item.event} />+ ) : (+ <ChannelMessage+ continuation={continuation}+ detail={detail}+ highlighted={highlighted === item.message.id}+ message={item.message}+ threadId={threadId}+ onJumpToMessage={jumpToMessage}+ onOpenThread={onOpenThread}+ onStartThread={channelArchived ? undefined : onStartThread}+ onReply={+ channelArchived || thread?.status === 'archived' ? undefined : selectReply+ }+ />+ )}+ </Fragment>+ ))}</WideScreenContainer></Flexbox>{channelArchived || thread?.status === 'archived' ? (diff --git a/src/features/Channels/ChannelMessage.tsx b/src/features/Channels/ChannelMessage.tsxindex 3c5c050b42c..51dd68fa1fb 100644--- a/src/features/Channels/ChannelMessage.tsx+++ b/src/features/Channels/ChannelMessage.tsx@@ -1,5 +1,5 @@import type { ChannelDetail, ChannelPublicMessage } from '@lobechat/types';-import { Button, Divider, Flexbox, Icon, Text } from '@lobehub/ui';+import { ActionIcon, Button, Divider, Flexbox, Icon, Text } from '@lobehub/ui';import * as stylex from '@stylexjs/stylex';import { GitBranch, Reply } from 'lucide-react';import type { ReactNode } from 'react';@@ -16,6 +16,7 @@ import { userProfileSelectors } from '@/store/user/selectors';import { authorAvatar, isCurrentUserAuthor, memberName } from './memberName';import { CHANNEL_MENTION_TAG, remarkChannelMentions } from './mentionMarkdown';import { MessageAttachments } from './MessageAttachments';+import { channelTimeFormatters } from './messagePresentation';import { MessageFailureMark, MessageRoutingStatus } from './MessageReceipts';import { showsReplyQuote } from './replyQuote';import { styles } from './styles';@@ -42,6 +43,7 @@ const MessageText = ({ content, names }: { content: string; names: string[] }) =export const ChannelMessage = ({detail,+ continuation = false,message,isRoot,highlighted,@@ -51,6 +53,7 @@ export const ChannelMessage = ({onReply,onJumpToMessage,}: {+ continuation?: boolean;detail: ChannelDetail;isRoot?: boolean;highlighted?: boolean;@@ -61,7 +64,24 @@ export const ChannelMessage = ({onJumpToMessage?: (message: ChannelReplyTarget) => void;threadId?: string | null;}) => {- const { t } = useTranslation('channel');+ const { t, i18n } = useTranslation('channel');+ const timeFormats = useMemo(() => channelTimeFormatters(i18n.language), [i18n.language]);+ const date = new Date(message.createdAt);+ // Failed/unassigned requests keep their identity row and recovery affordance.+ const compact =+ continuation &&+ !isRoot &&+ message.routingStatus !== 'unassigned' &&+ !detail.jobs.some((job) => job.messageId === message.id && job.status === 'failed');+ const timestamp = (+ <time+ dateTime={date.toISOString()}+ title={timeFormats.full.format(date)}+ {...stylex.props(styles.messageTime)}+ >+ {timeFormats.time.format(date)}+ </time>+ );const isOwnMessage = useUserStore((s) =>isCurrentUserAuthor(message.author, userProfileSelectors.userId(s)),);@@ -69,6 +89,11 @@ export const ChannelMessage = ({const thread =!threadId && !isRoot && detail.threads.find((entry) => entry.rootMessageId === message.id);const canBranch = !threadId && !isRoot && !thread && !!onStartThread;+ const startThread = () =>+ onStartThread?.({+ root: message,+ attachments: detail.attachments.filter((file) => message.fileIds.includes(file.id)),+ });const isRequest = message.author.type === 'user' && !isRoot;const mentionNames = detail.members.filter((member) => message.mentions.includes(member.id))@@ -76,13 +101,18 @@ export const ChannelMessage = ({.filter(Boolean);return (<div+ aria-label={message.author.name || t('deletedMember')}+ data-continuation={compact || undefined}data-message-id={message.id}+ role="article"{...stylex.props(styles.messageRow,+ compact && (onReply || canBranch) && styles.continuationWithAction,highlighted && styles.highlightedMessage,stylex.defaultMarker(),)}>+ {compact && <span {...stylex.props(styles.continuationTime)}>{timestamp}</span>}<ChatItemshowAvatarshowTitle@@ -91,10 +121,10 @@ export const ChannelMessage = ({belowMessage={isRequest ? <MessageRoutingStatus message={message} /> : undefined}gap={4}id={message.id}- paddingBlock={12}+ paddingBlock={compact ? 2 : 8}placement="left"+ showHeader={!compact}style={{ paddingInlineStart: 48 }}- time={new Date(message.createdAt).getTime()}actionAddon={thread ? (<Button@@ -117,65 +147,76 @@ export const ChannelMessage = ({</Flexbox>)}message={- <CollapsibleContent key={message.id}>- <Flexbox gap={8}>- {!isRoot &&- showsReplyQuote(message) &&- (message.replyTo ? (- <Button- aria-label={t('reply.viewOriginal')}- icon={Reply}- size="small"- style={{ alignSelf: 'flex-start', maxWidth: '100%', minWidth: 0 }}- type="text"- onClick={() => onJumpToMessage?.(message.replyTo!)}- >- <Text ellipsis as="span" fontSize={12} type="secondary">- {message.replyTo.author.name || t('deletedMember')}- {': '}- {message.replyTo.content || t('reply.attachment')}- </Text>- </Button>- ) : (- <Text fontSize={12} type="secondary">- {t('reply.unavailable')}+ <Flexbox gap={8}>+ {!isRoot &&+ showsReplyQuote(message) &&+ (message.replyTo ? (+ <Button+ aria-label={t('reply.viewOriginal')}+ icon={Reply}+ size="small"+ style={{ alignSelf: 'flex-start', maxWidth: '100%', minWidth: 0 }}+ type="text"+ onClick={() => onJumpToMessage?.(message.replyTo!)}+ >+ <Text ellipsis as="span" fontSize={12} type="secondary">+ {message.replyTo.author.name || t('deletedMember')}+ {': '}+ {message.replyTo.content || t('reply.attachment')}</Text>- ))}- {message.fileIds.length > 0 && (- <MessageAttachments attachments={detail.attachments} fileIds={message.fileIds} />- )}- {message.content && <MessageText content={message.content} names={mentionNames} />}- </Flexbox>- </CollapsibleContent>+ </Button>+ ) : (+ <Text fontSize={12} type="secondary">+ {t('reply.unavailable')}+ </Text>+ ))}+ {message.fileIds.length > 0 && (+ <MessageAttachments attachments={detail.attachments} fileIds={message.fileIds} />+ )}+ {message.content && (+ <CollapsibleContent key={message.id} maxHeight={160}>+ <MessageText content={message.content} names={mentionNames} />+ </CollapsibleContent>+ )}+ </Flexbox>}titleAddon={- isRequest ? <MessageFailureMark detail={detail} message={message} /> : undefined+ <>+ {timestamp}+ {isRequest && <MessageFailureMark detail={detail} message={message} />}+ </>}/>{(onReply || canBranch) && (<div {...stylex.props(styles.messageToolbar)}>- {onReply && (- <Button icon={Reply} size="small" type="text" onClick={() => onReply(message)}>- {t('reply.action')}- </Button>- )}- {canBranch && (- <Button- icon={GitBranch}- size="small"- type="text"- onClick={() =>- onStartThread?.({- root: message,- attachments: detail.attachments.filter((file) =>- message.fileIds.includes(file.id),- ),- })- }- >- {t('startThread')}- </Button>- )}+ {onReply &&+ (compact ? (+ <ActionIcon+ aria-label={t('reply.action')}+ icon={Reply}+ size="small"+ title={t('reply.action')}+ onClick={() => onReply(message)}+ />+ ) : (+ <Button icon={Reply} size="small" type="text" onClick={() => onReply(message)}>+ {t('reply.action')}+ </Button>+ ))}+ {canBranch &&+ (compact ? (+ <ActionIcon+ aria-label={t('startThread')}+ icon={GitBranch}+ size="small"+ title={t('startThread')}+ onClick={startThread}+ />+ ) : (+ <Button icon={GitBranch} size="small" type="text" onClick={startThread}>+ {t('startThread')}+ </Button>+ ))}</div>)}</div>diff --git a/src/features/Channels/messagePresentation.test.ts b/src/features/Channels/messagePresentation.test.tsnew file mode 100644index 00000000000..b44d59db149--- /dev/null+++ b/src/features/Channels/messagePresentation.test.ts@@ -0,0 +1,76 @@+import type { ChannelPublicMessage } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import type { TimelineItem } from './joinEvents';+import { channelTimeFormatters, presentChannelTimeline } from './messagePresentation';++const message = (at: Date, patch: Partial<ChannelPublicMessage> = {}): TimelineItem => ({+ kind: 'message',+ message: {+ author: { avatar: null, id: 'alice', name: 'Alice', type: 'user' },+ createdAt: at,+ replyToId: null,+ threadId: null,+ ...patch,+ } as ChannelPublicMessage,+});++describe('channel reading groups', () => {+ const at = new Date(2026, 9, 31, 12);+ const later = (minutes: number) => new Date(at.getTime() + minutes * 60_000);++ it('keeps consecutive speech together but starts a fresh group after a pause', () => {+ const rows = presentChannelTimeline([message(at), message(later(1)), message(later(7))]);+ expect(rows.map((row) => row.continuation)).toEqual([false, true, false]);+ expect(rows.map((row) => row.startsDay)).toEqual([true, false, false]);+ });++ it('does not merge different identities, deleted authors, or distinct replies', () => {+ const variations: Partial<ChannelPublicMessage>[] = [+ { author: { avatar: null, id: 'bob', name: 'Alice', type: 'user' } },+ { author: { avatar: null, id: 'alice', name: 'Alice', type: 'agent' } },+ { author: { avatar: null, id: null, name: 'Deleted', type: 'user' } },+ { replyToId: 'another-request' },+ { threadId: 'another-thread' },+ ];+ for (const patch of variations) {+ expect(presentChannelTimeline([message(at), message(later(1), patch)])[1].continuation).toBe(+ false,+ );+ }+ });++ it('breaks a group around join events and at local midnight', () => {+ const event: TimelineItem = {+ event: { at: later(1).getTime(), id: 'join:bob', members: [] },+ kind: 'event',+ };+ expect(presentChannelTimeline([message(at), event, message(later(2))])[2].continuation).toBe(+ false,+ );+ const midnight = presentChannelTimeline([+ message(new Date(2026, 9, 31, 23, 59)),+ message(new Date(2026, 10, 1, 0, 1)),+ ]);+ expect(midnight[1]).toMatchObject({ continuation: false, startsDay: true });+ });++ it('does not group out-of-order messages or a first message on an older page', () => {+ expect(presentChannelTimeline([message(later(1)), message(at)])[1].continuation).toBe(false);+ expect(presentChannelTimeline([message(at)])[0].continuation).toBe(false);+ });+});++describe('channel timestamps', () => {+ const date = new Date(2026, 9, 31, 15, 4);++ it('uses the requested language for calendar labels and stable clock times', () => {+ const zh = channelTimeFormatters('zh-CN');+ const en = channelTimeFormatters('en-US');+ expect(zh.date.format(date)).toBe('2026年10月31日');+ expect(zh.time.format(date)).toBe('15:04');+ expect(en.date.format(date)).toBe('October 31, 2026');+ expect(en.time.format(date)).toMatch(/03:04\sPM/);+ expect(zh.full.format(date)).toContain('2026年10月31日');+ });+});diff --git a/src/features/Channels/messagePresentation.ts b/src/features/Channels/messagePresentation.tsnew file mode 100644index 00000000000..b499a411af1--- /dev/null+++ b/src/features/Channels/messagePresentation.ts@@ -0,0 +1,39 @@+import type { ChannelPublicMessage } from '@lobechat/types';++import type { TimelineItem } from './joinEvents';++const GROUP_WINDOW_MS = 5 * 60 * 1000;++const itemDate = (item: TimelineItem) =>+ new Date(item.kind === 'event' ? item.event.at : item.message.createdAt);++const sameAuthor = (a: ChannelPublicMessage, b: ChannelPublicMessage) =>+ !!a.author.id && a.author.id === b.author.id && a.author.type === b.author.type;++/** Group only adjacent speech; system events, dates and reply contexts break a group. */+export const presentChannelTimeline = (items: TimelineItem[]) =>+ items.map((item, index) => {+ const previous = items[index - 1];+ const date = itemDate(item);+ const previousDate = previous && itemDate(previous);+ const startsDay = !previousDate || date.toDateString() !== previousDate.toDateString();+ const elapsed = previousDate ? date.getTime() - previousDate.getTime() : Infinity;+ const continuation =+ !startsDay &&+ elapsed >= 0 &&+ elapsed <= GROUP_WINDOW_MS &&+ item.kind === 'message' &&+ previous?.kind === 'message' &&+ sameAuthor(item.message, previous.message) &&+ item.message.threadId === previous.message.threadId &&+ item.message.replyToId === previous.message.replyToId;++ return { continuation, date, item, startsDay };+ });++/** Stable clock labels keep the feed scannable and do not depend on dayjs's global locale. */+export const channelTimeFormatters = (locale: string) => ({+ date: new Intl.DateTimeFormat(locale, { dateStyle: 'long' }),+ full: new Intl.DateTimeFormat(locale, { dateStyle: 'full', timeStyle: 'medium' }),+ time: new Intl.DateTimeFormat(locale, { hour: '2-digit', minute: '2-digit' }),+});diff --git a/src/features/Channels/styles.ts b/src/features/Channels/styles.tsindex 7c4e5421f85..8b962217f72 100644--- a/src/features/Channels/styles.ts+++ b/src/features/Channels/styles.ts@@ -66,9 +66,49 @@ export const styles = stylex.create({highlightedMessage: { backgroundColor: cssVar.colorInfoBg },messageAvatar: {position: 'absolute',- insetBlockStart: 12,+ insetBlockStart: 8,insetInlineStart: 0,},+ // A continuation has no header for its toolbar; reserve room for both actions.+ continuationWithAction: {+ paddingInlineEnd: 84,+ },+ messageTime: {+ flexShrink: 0,+ fontSize: cssVar.fontSizeSM,+ fontVariantNumeric: 'tabular-nums',+ color: cssVar.colorTextSecondary,+ whiteSpace: 'nowrap',+ opacity: 1,+ },+ continuationTime: {+ position: 'absolute',+ insetBlockStart: 4,+ insetInlineStart: 0,+ width: 54,+ textAlign: 'center',+ opacity: {+ default: 1,+ [HOVER]: {+ default: 0,+ [stylex.when.ancestor(':hover')]: 1,+ [stylex.when.ancestor(':focus-within')]: 1,+ },+ },+ },+ dateDivider: {+ display: 'flex',+ alignItems: 'center',+ gap: 12,+ paddingBlock: 12,+ fontSize: cssVar.fontSizeSM,+ color: cssVar.colorTextSecondary,+ },+ dateLine: {+ flex: '1',+ height: 1,+ backgroundColor: cssVar.colorBorderSecondary,+ },/** Floats over the row's top-right corner while the row is hovered or focused. */messageToolbar: {position: 'absolute',diff --git a/src/features/Conversation/ChatItem/ChatItem.tsx b/src/features/Conversation/ChatItem/ChatItem.tsxindex a4519ae9d9b..2dac677bba7 100644--- a/src/features/Conversation/ChatItem/ChatItem.tsx+++ b/src/features/Conversation/ChatItem/ChatItem.tsx@@ -41,6 +41,7 @@ const ChatItem = memo<ChatItemProps>(belowMessage,headerAddon,showAvatar = true,+ showHeader = true,titleAddon,disabled = false,id,@@ -80,23 +81,25 @@ const ChatItem = memo<ChatItemProps>(}}{...rest}>- <Flexbox- align={'center'}- className={'message-header'}- direction={isUser ? 'horizontal-reverse' : 'horizontal'}- gap={8}- // The row wraps nothing, so without a cap it is sized by its content and- // simply overflows its lane — on a narrow viewport that is a header- // wider than the conversation pane (the source-topic link, a long agent- // name). Capped, the shrinkable addons yield to the space actually- // available and truncate instead.- style={{ maxInlineSize: '100%', minInlineSize: 0 }}- >- {showAvatar &&- (customAvatarRender ? customAvatarRender(avatar, avatarContent) : avatarContent)}- {headerAddon}- <Title avatar={avatar} showTitle={showTitle} time={time} titleAddon={titleAddon} />- </Flexbox>+ {showHeader && (+ <Flexbox+ align={'center'}+ className={'message-header'}+ direction={isUser ? 'horizontal-reverse' : 'horizontal'}+ gap={8}+ // The row wraps nothing, so without a cap it is sized by its content and+ // simply overflows its lane — on a narrow viewport that is a header+ // wider than the conversation pane (the source-topic link, a long agent+ // name). Capped, the shrinkable addons yield to the space actually+ // available and truncate instead.+ style={{ maxInlineSize: '100%', minInlineSize: 0 }}+ >+ {showAvatar &&+ (customAvatarRender ? customAvatarRender(avatar, avatarContent) : avatarContent)}+ {headerAddon}+ <Title avatar={avatar} showTitle={showTitle} time={time} titleAddon={titleAddon} />+ </Flexbox>+ )}<FlexboxclassName={'message-body'}gap={8}diff --git a/src/features/Conversation/ChatItem/type.ts b/src/features/Conversation/ChatItem/type.tsindex aa142346f7d..29038a17c93 100644--- a/src/features/Conversation/ChatItem/type.ts+++ b/src/features/Conversation/ChatItem/type.ts@@ -71,6 +71,8 @@ export interface ChatItemProps extends Omit<FlexboxProps, 'children' | 'onChange* @default false*/showAvatar?: boolean;+ /** Omit the identity row for a continuation in a grouped message feed. */+ showHeader?: boolean;/*** @description Whether to show the title of the chat item*/diff --git a/src/store/page/action.test.ts b/src/store/page/action.test.tsindex 7bb23d4745c..a3e8595245b 100644--- a/src/store/page/action.test.ts+++ b/src/store/page/action.test.ts@@ -1,5 +1,5 @@import type { DocumentItem } from '@lobechat/database/schemas';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { DocumentSourceType, type LobeDocument } from '@/types/document';@@ -21,6 +21,12 @@ vi.mock('@/services/document', () => ({},}));+vi.mock('@/store/home', () => ({+ useHomeStore: {+ getState: () => ({ refreshDocsHome: vi.fn().mockResolvedValue(undefined) }),+ },+}));+const { documentService } = await import('@/services/document');/** A `documents` row as the server returns it. */@@ -87,6 +93,11 @@ beforeEach(() => {pageActions.reset();});+afterEach(async () => {+ // Page mutations refresh Docs home through a fire-and-forget dynamic import.+ await vi.dynamicImportSettled();+});+describe('pageActions — createNewPage', () => {it('shows an optimistic row, then swaps in the server row and navigates to it', async () => {const navigate = vi.fn();