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): direct-chat typing in header, icon message toolbar, open reply topic (#22559)

Arvin Xub4a9ea8cbc7c
diff --git a/locales/en-US/channel.json b/locales/en-US/channel.json
index 5345df83fc1..791957df298 100644
--- a/locales/en-US/channel.json
+++ b/locales/en-US/channel.json
@@ -3,6 +3,7 @@
"activity.many": "{{count}} members are replying…",
"activity.one": "{{name}} · {{status}}",
"activity.two": "{{names}} are replying…",
+ "activity.typing": "typing…",
"agents": "Agents",
"archive": "Archive channel",
"archiveConfirm": "Archive “{{title}}”? Replies in progress will stop and the channel will take no new messages. Members can still read its history, and an owner or administrator can unarchive it at any time.",
@@ -117,6 +118,8 @@
"mentionInvite.failed": "Couldn't add {{name}} to the channel. Try again.",
"mentionInvite.failedReason": "Couldn't add {{name}} to the channel: {{reason}}",
"mentionInvite.section": "Not in this channel · mention to add",
+ "message.copied": "Copied",
+ "message.copy": "Copy text",
"moveToTrash": "Move channel to trash",
"moveToTrashConfirm": "Move “{{title}}” to trash? Replies will stop. You can restore the channel and its history from Trash. Agents and files will be kept.",
"moveToTrashSuccess": "Channel moved to trash",
@@ -181,6 +184,11 @@
"threadDivider": "Replies in this thread",
"threadEmpty": "Keep discussing this message here.",
"title": "Channels",
+ "topic.close": "Close topic",
+ "topic.open": "Open topic",
+ "topic.openPage": "Open full topic",
+ "topic.title": "Topic",
+ "topic.titleNamed": "{{name}}'s topic",
"unarchive": "Unarchive channel",
"unarchiveSuccess": "Channel unarchived",
"unarchiveThread": "Unarchive thread",
diff --git a/locales/zh-CN/channel.json b/locales/zh-CN/channel.json
index a2196b0b992..244a95071fd 100644
--- a/locales/zh-CN/channel.json
+++ b/locales/zh-CN/channel.json
@@ -3,6 +3,7 @@
"activity.many": "{{count}} 位成员正在回复…",
"activity.one": "{{name}} · {{status}}",
"activity.two": "{{names}} 正在回复…",
+ "activity.typing": "正在输入中…",
"agents": "Agent",
"archive": "归档频道",
"archiveConfirm": "归档「{{title}}」?进行中的回复会停止,频道不再接收新消息。成员仍可查看历史消息,所有者或管理员可以随时取消归档。",
@@ -117,6 +118,8 @@
"mentionInvite.failed": "未能将 {{name}} 加入频道,请重试。",
"mentionInvite.failedReason": "未能将 {{name}} 加入频道:{{reason}}",
"mentionInvite.section": "不在频道中 · @ 后将加入",
+ "message.copied": "已复制",
+ "message.copy": "复制文本",
"moveToTrash": "移至回收站",
"moveToTrashConfirm": "将「{{title}}」移至回收站?进行中的回复会停止,你可以在回收站恢复频道和历史消息。Agent 和文件将保留。",
"moveToTrashSuccess": "频道已移至回收站",
@@ -181,6 +184,11 @@
"threadDivider": "此线程中的回复",
"threadEmpty": "在这里接着讨论这条消息。",
"title": "频道",
+ "topic.close": "关闭话题",
+ "topic.open": "打开话题",
+ "topic.openPage": "打开完整话题",
+ "topic.title": "话题",
+ "topic.titleNamed": "{{name}} 的话题",
"unarchive": "取消归档",
"unarchiveSuccess": "频道已取消归档",
"unarchiveThread": "取消归档线程",
diff --git a/packages/database/src/repositories/channel/__tests__/sourceTopic.test.ts b/packages/database/src/repositories/channel/__tests__/sourceTopic.test.ts
new file mode 100644
index 00000000000..455172589b6
--- /dev/null
+++ b/packages/database/src/repositories/channel/__tests__/sourceTopic.test.ts
@@ -0,0 +1,65 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { topics } from '../../../schemas';
+import { ChannelExecutionRepository } from '..';
+import { createChannelFixture, jobsOf, lease } from './testUtils';
+
+const db = await getTestDB();
+const fixture = createChannelFixture(db, 'channel-source-topic');
+const execution = new ChannelExecutionRepository(db);
+beforeEach(fixture.setup);
+afterEach(fixture.cleanup);
+
+/** A member asks the Agent and its reply is published from the member's own topic. */
+const publishedReply = async () => {
+ const team = await fixture.createTeamChannel();
+ const agent = await fixture.addAgent(team.channel.id, 'Agent');
+ const request = await team.asMember.send(team.channel.id, {
+ content: 'Question',
+ mentions: [agent.id],
+ requestKey: 'question',
+ routing: 'fallback',
+ });
+ const [job] = await jobsOf(db, request.id);
+ const claimed = (await execution.claim(team.channel.id, job.id, lease))!;
+ await execution.accepted(team.channel.id, job.id);
+ await execution.saveDraft(team.channel.id, job.id, 'Answer');
+ await execution.publish(team.channel.id, job.id);
+ await execution.releaseWriter(team.channel.id, job.id);
+ const reply = async (repo: typeof team.asOwner) =>
+ (await repo.detail(team.channel.id)).messages.find(
+ (message) => message.routingStatus === 'reply',
+ )!;
+ return { ...team, reply, request, topicId: claimed.topic.id };
+};
+
+describe('Channel reply source topic', () => {
+ it('links a reply to the topic of the member who ran it', async () => {
+ const state = await publishedReply();
+
+ expect((await state.reply(state.asMember)).sourceTopicId).toBe(state.topicId);
+ });
+
+ it('hides the topic from other members and on requests', async () => {
+ const state = await publishedReply();
+
+ expect((await state.reply(state.asOwner)).sourceTopicId).toBeNull();
+ const request = (await state.asMember.detail(state.channel.id)).messages.find(
+ (message) => message.id === state.request.id,
+ )!;
+ expect(request.sourceTopicId).toBeNull();
+ });
+
+ it('drops the link once the topic is trashed', async () => {
+ const state = await publishedReply();
+ await db
+ .update(topics)
+ .set({ deletedAt: new Date(), isDeleted: true })
+ .where(eq(topics.id, state.topicId));
+
+ expect((await state.reply(state.asMember)).sourceTopicId).toBeNull();
+ });
+});
diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.ts
index 35d2b6cc953..588d909cadc 100644
--- a/packages/database/src/repositories/channel/index.ts
+++ b/packages/database/src/repositories/channel/index.ts
@@ -271,7 +271,7 @@ export class ChannelRepository {
async (tx, access) => {
if (access.channel.isDeleted) throw new ChannelError('NOT_FOUND', 'Channel not found');
const admin = hasRole(access.member.role, 'admin');
- const view = await readChannelView(tx, channelId, options);
+ const view = await readChannelView(tx, channelId, options, this.userId);
return {
channel: { ...access.channel, canDelete: admin },
...view,
diff --git a/packages/database/src/repositories/channel/view.ts b/packages/database/src/repositories/channel/view.ts
index af2ac09a583..d306e08512d 100644
--- a/packages/database/src/repositories/channel/view.ts
+++ b/packages/database/src/repositories/channel/view.ts
@@ -8,6 +8,7 @@ import {
channelMessages,
channelThreads,
files as fileTable,
+ topics,
users,
} from '../../schemas';
import type { Transaction } from '../../type';
@@ -59,10 +60,37 @@ const publicMessage = (row: MessageRow, fileIds: string[]) => {
};
/** Public projection only. Execution settings, drafts and internal messages never leave this boundary. */
+/**
+ * The Agent topic behind each published reply, for replies the viewer ran: the topic belongs to
+ * the requester, so other members never learn its id.
+ */
+const sourceTopicsByMessage = async (
+ tx: Transaction,
+ channelId: string,
+ messageIds: string[],
+ viewerUserId: string | undefined,
+) => {
+ if (!viewerUserId || !messageIds.length) return new Map<string, string>();
+ const rows = await tx
+ .select({ messageId: channelJobs.publishedMessageId, topicId: topics.id })
+ .from(channelJobs)
+ .innerJoin(topics, eq(topics.id, channelJobs.topicId))
+ .where(
+ and(
+ eq(channelJobs.channelId, channelId),
+ inArray(channelJobs.publishedMessageId, messageIds),
+ eq(topics.userId, viewerUserId),
+ notTrashed(topics.isDeleted),
+ ),
+ );
+ return new Map(rows.map((row) => [row.messageId!, row.topicId]));
+};
+
export const readChannelView = async (
tx: Transaction,
channelId: string,
options: { before?: number; limit?: number; threadId?: string | null } = {},
+ viewerUserId?: string,
) => {
const limit = Math.max(1, Math.min(options.limit ?? 100, 100));
const [members, reversed, threads, jobs] = await Promise.all([
@@ -181,6 +209,14 @@ export const readChannelView = async (
...page.map((message) => message.id),
...(rootMessage ? [rootMessage.id] : []),
]);
+ const sourceTopics = await sourceTopicsByMessage(
+ tx,
+ channelId,
+ [...page, ...(rootMessage ? [rootMessage] : [])].flatMap((message) =>
+ message.routingStatus === 'reply' ? [message.id] : [],
+ ),
+ viewerUserId,
+ );
const ids = [...new Set([...files.values()].flat())];
const attachments = ids.length
? await tx
@@ -203,11 +239,13 @@ export const readChannelView = async (
rootMessage: rootMessage
? {
...publicMessage(rootMessage, files.get(rootMessage.id) ?? []),
+ sourceTopicId: sourceTopics.get(rootMessage.id) ?? null,
replyTo: rootMessage.replyToId ? (quotes.get(rootMessage.replyToId) ?? null) : null,
}
: null,
messages: page.map((message) => ({
...publicMessage(message, files.get(message.id) ?? []),
+ sourceTopicId: sourceTopics.get(message.id) ?? null,
replyTo: message.replyToId ? (quotes.get(message.replyToId) ?? null) : null,
})),
};
diff --git a/packages/locales/src/default/channel.ts b/packages/locales/src/default/channel.ts
index ae7739d36b0..1d6507c8210 100644
--- a/packages/locales/src/default/channel.ts
+++ b/packages/locales/src/default/channel.ts
@@ -153,6 +153,14 @@ export default {
'activity.many': '{{count}} members are replying…',
'activity.one': '{{name}} · {{status}}',
'activity.two': '{{names}} are replying…',
+ 'activity.typing': 'typing…',
+ 'message.copy': 'Copy text',
+ 'message.copied': 'Copied',
+ 'topic.open': 'Open topic',
+ 'topic.title': 'Topic',
+ 'topic.titleNamed': "{{name}}'s topic",
+ 'topic.openPage': 'Open full topic',
+ 'topic.close': 'Close topic',
'autoTitle.empty': 'My Channel',
'autoTitle.more': '{{names}} and {{count}} more',
'autoTitle.separator': ', ',
diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.ts
index c336f846305..ff524144dda 100644
--- a/packages/types/src/channel.ts
+++ b/packages/types/src/channel.ts
@@ -349,6 +349,8 @@ export interface ChannelPublicMessage {
replyToId: string | null;
routingStatus: ChannelMessageRoutingStatus;
sequence: number;
+ /** The Agent topic behind a reply, only when the viewer ran it (owns that topic). */
+ sourceTopicId?: string | null;
threadId: string | null;
userId: string | null;
}
diff --git a/src/features/Channels/ChannelConversation.tsx b/src/features/Channels/ChannelConversation.tsx
index fc8858d1a82..d252f3e0132 100644
--- a/src/features/Channels/ChannelConversation.tsx
+++ b/src/features/Channels/ChannelConversation.tsx
@@ -31,6 +31,7 @@ import {
import { presentOutgoingMessage, timelineTail } from './outgoing';
import { OutgoingStatus } from './OutgoingStatus';
import { ReplyActivity } from './ReplyActivity';
+import type { ReplyTopic } from './ReplyTopicPanel';
import { styles } from './styles';
import type { ChannelThreadDraft } from './threadDraft';
import { useChannelEvents } from './useChannelEvents';
@@ -43,6 +44,7 @@ interface ChannelConversationProps {
/** Mounted beside a thread panel that covers it, so keep it out of the tab order. */
inert?: boolean;
onOpenThread?: (threadId: string, toggle?: boolean) => void;
+ onOpenTopic?: (topic: ReplyTopic) => void;
onStartThread?: (draft: ChannelThreadDraft) => void;
threadId?: string | null;
}
@@ -52,6 +54,7 @@ const Timeline = ({
inert,
threadId = null,
onOpenThread,
+ onOpenTopic,
onStartThread,
}: ChannelConversationProps) => {
const { t, i18n } = useTranslation('channel');
@@ -253,6 +256,7 @@ const Timeline = ({
threadId={threadId}
onJumpToMessage={jumpToMessage}
onOpenThread={onOpenThread}
+ onOpenTopic={onOpenTopic}
onStartThread={channelArchived ? undefined : onStartThread}
onReply={
channelArchived || thread?.status === 'archived' ? undefined : selectReply
@@ -267,12 +271,15 @@ const Timeline = ({
<ArchivedNotice channel={detail.channel} threadId={threadId} />
) : (
<Composer
- activity={<ReplyActivity detail={detail} threadId={threadId} />}
channel={detail.channel}
draftKey={channelDraftKey(channelId, threadId)}
key={channelDraftKey(channelId, threadId)}
members={activeMembers}
replyTarget={reply.target}
+ activity={
+ // A direct conversation shows its Agent's state beside the name in the header.
+ direct && !threadId ? null : <ReplyActivity detail={detail} threadId={threadId} />
+ }
placeholder={
threadId
? t('threadComposer')
diff --git a/src/features/Channels/ChannelMessage.test.tsx b/src/features/Channels/ChannelMessage.test.tsx
index 00f5eee4450..6e1b1028367 100644
--- a/src/features/Channels/ChannelMessage.test.tsx
+++ b/src/features/Channels/ChannelMessage.test.tsx
@@ -58,6 +58,7 @@ vi.mock('./MessageReceipts', () => ({
const detail = {
attachments: [],
+ channel: { agentId: null, id: 'chn_1' },
jobs: [],
members: [{ agentId: 'agt_1', description: 'Architect', id: 'mem_1' }],
threads: [],
diff --git a/src/features/Channels/ChannelMessage.tsx b/src/features/Channels/ChannelMessage.tsx
index 2693cd09a66..69713b00d8a 100644
--- a/src/features/Channels/ChannelMessage.tsx
+++ b/src/features/Channels/ChannelMessage.tsx
@@ -1,7 +1,17 @@
import type { ChannelDetail, ChannelPublicMessage } from '@lobechat/types';
-import { ActionIcon, Button, Divider, Flexbox, Icon, Text } from '@lobehub/ui';
+import {
+ ActionIcon,
+ Button,
+ copyToClipboard,
+ Divider,
+ DropdownMenu,
+ Flexbox,
+ Icon,
+ Text,
+ toast,
+} from '@lobehub/ui';
import * as stylex from '@stylexjs/stylex';
-import { GitBranch, Reply } from 'lucide-react';
+import { Copy, GitBranch, MessagesSquare, MoreHorizontal, Reply } from 'lucide-react';
import type { ReactNode } from 'react';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -20,6 +30,7 @@ import { MessageAttachments } from './MessageAttachments';
import { channelTimeFormatters } from './messagePresentation';
import { MessageFailureMark, MessageRoutingStatus } from './MessageReceipts';
import { showsReplyQuote } from './replyQuote';
+import type { ReplyTopic } from './ReplyTopicPanel';
import { styles } from './styles';
import type { ChannelThreadDraft } from './threadDraft';
import type { ChannelReplyTarget } from './useReplyTarget';
@@ -54,6 +65,7 @@ export const ChannelMessage = ({
onStartThread,
onReply,
onJumpToMessage,
+ onOpenTopic,
pending = false,
}: {
continuation?: boolean;
@@ -67,6 +79,8 @@ export const ChannelMessage = ({
onStartThread?: (draft: ChannelThreadDraft) => void;
onReply?: (message: ChannelPublicMessage) => void;
onJumpToMessage?: (message: ChannelReplyTarget) => void;
+ /** Opens the Agent topic a reply came from; offered only when the server shares it. */
+ onOpenTopic?: (topic: ReplyTopic) => void;
/** Sent from this tab and not yet confirmed by the server. */
pending?: boolean;
threadId?: string | null;
@@ -106,6 +120,41 @@ export const ChannelMessage = ({
const agentMember = agentAuthorId
? detail.members.find((member) => member.agentId === agentAuthorId)
: undefined;
+ const sourceTopicId = message.sourceTopicId;
+ const moreItems = [
+ ...(agentAuthorId && sourceTopicId && onOpenTopic
+ ? [
+ {
+ icon: MessagesSquare,
+ key: 'openTopic',
+ label: t('topic.open'),
+ onClick: () =>
+ onOpenTopic({
+ agentId: agentAuthorId,
+ avatar: message.author.avatar,
+ name: message.author.name || t('unnamedAgent'),
+ topicId: sourceTopicId,
+ }),
+ },
+ ]
+ : []),
+ ...(message.content
+ ? [
+ {
+ icon: Copy,
+ key: 'copy',
+ label: t('message.copy'),
+ onClick: async () => {
+ await copyToClipboard(message.content);
+ toast.success(t('message.copied'));
+ },
+ },
+ ]
+ : []),
+ ];
+ const hasToolbar = !!onReply || canBranch || moreItems.length > 0;
+ // A direct conversation is a chat with one Agent; folding its answers only adds a click.
+ const collapsible = !detail.channel.agentId;
const mentionNames = detail.members
.filter((member) => message.mentions.includes(member.id))
.map((member) => memberName(member, ''))
@@ -119,7 +168,7 @@ export const ChannelMessage = ({
role="article"
{...stylex.props(
styles.messageRow,
- compact && (onReply || canBranch) && styles.continuationWithAction,
+ compact && hasToolbar && styles.continuationWithAction,
highlighted && styles.highlightedMessage,
pending && styles.pendingMessage,
stylex.defaultMarker(),
@@ -205,11 +254,14 @@ export const ChannelMessage = ({
{message.fileIds.length > 0 && (
<MessageAttachments attachments={detail.attachments} fileIds={message.fileIds} />
)}
- {message.content && (
- <CollapsibleContent key={message.id} maxHeight={160}>
+ {message.content &&
+ (collapsible ? (
+ <CollapsibleContent key={message.id} maxHeight={160}>
+ <MessageText content={message.content} names={mentionNames} />
+ </CollapsibleContent>
+ ) : (
<MessageText content={message.content} names={mentionNames} />
- </CollapsibleContent>
- )}
+ ))}
</Flexbox>
}
titleAddon={
@@ -219,36 +271,37 @@ export const ChannelMessage = ({
</>
}
/>
- {(onReply || canBranch) && (
+ {hasToolbar && (
+ // Icon-only, like a chat app's hover toolbar; rarer actions sit behind "more".
<div {...stylex.props(styles.messageToolbar)}>
- {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 ? (
+ {onReply && (
+ <ActionIcon
+ aria-label={t('reply.action')}
+ icon={Reply}
+ size="small"
+ title={t('reply.action')}
+ onClick={() => onReply(message)}
+ />
+ )}
+ {canBranch && (
+ <ActionIcon
+ aria-label={t('startThread')}
+ icon={GitBranch}
+ size="small"
+ title={t('startThread')}
+ onClick={startThread}
+ />
+ )}
+ {moreItems.length > 0 && (
+ <DropdownMenu items={moreItems}>
<ActionIcon
- aria-label={t('startThread')}
- icon={GitBranch}
+ aria-label={t('more', { ns: 'common' })}
+ icon={MoreHorizontal}
size="small"
- title={t('startThread')}
- onClick={startThread}
+ title={t('more', { ns: 'common' })}
/>
- ) : (
- <Button icon={GitBranch} size="small" type="text" onClick={startThread}>
- {t('startThread')}
- </Button>
- ))}
+ </DropdownMenu>
+ )}
</div>
)}
</div>
diff --git a/src/features/Channels/Composer.tsx b/src/features/Channels/Composer.tsx
index 0c11acf5495..3005f98daf6 100644
--- a/src/features/Channels/Composer.tsx
+++ b/src/features/Channels/Composer.tsx
@@ -91,7 +91,7 @@ export function Composer({
replyTarget,
onCancelReply,
}: {
- /** Who is replying right now; shown on the line above the input. */
+ /** Who is replying right now; shown on the line above the input. Omit to drop that line. */
activity?: ReactNode;
/** Lets an @mention invite people and Agents from outside the Channel. */
channel?: ChannelListItem;
@@ -229,11 +229,14 @@ export function Composer({
return (
<WideScreenContainer fullWidth paddingInline={16}>
<Flexbox {...stylex.props(styles.composer)} gap={4} {...getContainerProps()}>
- <div {...stylex.props(styles.composerStatus)}>
- <Flexbox horizontal align="center" style={{ minWidth: 0 }}>
- {activity}
- </Flexbox>
- </div>
+ {/* Without an activity line the input meets the feed directly, with no empty strip. */}
+ {activity != null && (
+ <div {...stylex.props(styles.composerStatus)}>
+ <Flexbox horizontal align="center" style={{ minWidth: 0 }}>
+ {activity}
+ </Flexbox>
+ </div>
+ )}
<ChatInput
maxHeight={480}
minHeight={0}
diff --git a/src/features/Channels/MemberStatus.tsx b/src/features/Channels/MemberStatus.tsx
index a8bd20a4d67..c45d053fd81 100644
--- a/src/features/Channels/MemberStatus.tsx
+++ b/src/features/Channels/MemberStatus.tsx
@@ -47,7 +47,6 @@ export function MemberStatus({
const overflow = entries.length - MAX_VISIBLE;
const title = t('membersCount', { count: entries.length });
const direct = !!channel.agentId;
- const inviteSize = direct ? undefined : 'small';
// A direct conversation is a chat with one Agent: no roster to show, only its actions, like an
// IM header. Its title is the Agent's name, so it cannot be renamed here.
const directMenu = () => [
@@ -90,6 +89,7 @@ export function MemberStatus({
aria-expanded={memberPanel.open}
aria-label={t(memberPanel.open ? 'members.hide' : 'members.show')}
icon={Users}
+ size="small"
title={t(memberPanel.open ? 'members.hide' : 'members.show')}
onClick={memberPanel.onToggle}
/>
@@ -126,7 +126,7 @@ export function MemberStatus({
<ActionIcon
aria-label={t('invite.title')}
icon={UserPlus}
- size={inviteSize}
+ size="small"
title={t('invite.title')}
onClick={() =>
openInviteMembers(
@@ -149,6 +149,7 @@ export function MemberStatus({
<ActionIcon
aria-label={t('more', { ns: 'common' })}
icon={MoreHorizontal}
+ size="small"
title={t('more', { ns: 'common' })}
/>
</DropdownMenu>
diff --git a/src/features/Channels/ReplyActivity.tsx b/src/features/Channels/ReplyActivity.tsx
index 4c46e966993..71ad7cb0e41 100644
--- a/src/features/Channels/ReplyActivity.tsx
+++ b/src/features/Channels/ReplyActivity.tsx
@@ -6,13 +6,18 @@ import { useTranslation } from 'react-i18next';
import AgentAvatar from '@/components/AgentAvatar';
import { activityLabel } from './activityLabel';
-import { channelJobStatus, memberCurrentJob, replyActivityJobs } from './jobStatus';
+import {
+ channelJobStatus,
+ conversationReplies,
+ directReplyStatus,
+ memberCurrentJob,
+} from './jobStatus';
import { replyEntries, ReplyList } from './MessageReceipts';
import { activityStyles, styles } from './styles';
const MAX_AVATARS = 3;
-const TypingDots = () => (
+export const TypingDots = () => (
<span aria-hidden {...stylex.props(activityStyles.dots)}>
{[0, 1, 2].map((index) => (
<span key={index} {...stylex.props(activityStyles.typingDot, activityStyles.delay(index))} />
@@ -32,9 +37,7 @@ export function ReplyActivity({
threadId: string | null;
}) {
const { t, i18n } = useTranslation('channel');
- const { jobs: allJobs = [], messages = [] } = detail;
- const jobs = replyActivityJobs(allJobs.filter((job) => (job.threadId ?? null) === threadId));
- const receiving = messages.some((message) => message.routingStatus === 'pending');
+ const { jobs, receiving } = conversationReplies(detail, threadId);
if (!jobs.length)
return receiving ? (
<span role="status" {...stylex.props(activityStyles.line, styles.muted)}>
@@ -92,3 +95,40 @@ export function ReplyActivity({
</Popover>
);
}
+
+/**
+ * A direct conversation has one Agent to wait on, so its state sits beside the Agent's name in
+ * the header like an IM's "typing…". Anything other than plain work says what it waits on.
+ */
+export function DirectReplyStatus({ detail }: { detail: ChannelDetail }) {
+ const { t } = useTranslation('channel');
+ const reply = directReplyStatus(detail);
+ if (!reply) return null;
+
+ const { jobs, waiting } = reply;
+ const label = activityLabel(waiting ? t(channelJobStatus(waiting)) : t('activity.typing'));
+ const status = (
+ <span role="status" {...stylex.props(activityStyles.line, activityStyles.header)}>
+ <span {...stylex.props(activityStyles.label)}>{label}</span>
+ {!waiting && <TypingDots />}
+ </span>
+ );
+ if (!jobs.length) return status;
+
+ return (
+ <Popover
+ placement="bottomLeft"
+ trigger="click"
+ content={
+ <ReplyList
+ channelId={detail.channel.id}
+ entries={replyEntries(detail, jobs, t('unnamedAgent'))}
+ />
+ }
+ >
+ <Button size="small" type="text" {...stylex.props(activityStyles.headerButton)}>
+ {status}
+ </Button>
+ </Popover>
+ );
+}
diff --git a/src/features/Channels/ReplyTopicPanel.tsx b/src/features/Channels/ReplyTopicPanel.tsx
new file mode 100644
index 00000000000..3d25f9f3166
--- /dev/null
+++ b/src/features/Channels/ReplyTopicPanel.tsx
@@ -0,0 +1,159 @@
+import { AGENT_CHAT_TOPIC_URL } from '@lobechat/const';
+import type { ConversationContext } from '@lobechat/types';
+import { ActionIcon, Flexbox, Text } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
+import { ExternalLink, X } from 'lucide-react';
+import { Activity, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AgentAvatar from '@/components/AgentAvatar';
+import ChatList from '@/features/Conversation/ChatList';
+import { ConversationProvider } from '@/features/Conversation/ConversationProvider';
+import MessageItem from '@/features/Conversation/Messages';
+import NavHeader from '@/features/NavHeader';
+import RightPanel from '@/features/RightPanel';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useOperationState } from '@/hooks/useOperationState';
+import { useAgentStore } from '@/store/agent';
+import { useUserStore } from '@/store/user';
+import { authSelectors } from '@/store/user/selectors';
+
+import { styles } from './styles';
+import { THREAD_FLOAT_BREAKPOINT } from './ThreadPanel';
+
+/** The Agent topic a channel reply was produced in. */
+export interface ReplyTopic {
+ agentId: string;
+ avatar: string | null;
+ name: string;
+ topicId: string;
+}
+
+const renderMessage = (index: number, id: string) => (
+ <MessageItem disableEditing id={id} index={index} key={id} />
+);
+
+/**
+ * The topic's messages, read-only. Writing here would add turns the Channel never saw, so
+ * follow-ups go through the Channel or the full topic page.
+ */
+const TopicConversation = ({ agentId, topicId }: { agentId: string; topicId: string }) => {
+ const isLogin = useUserStore(authSelectors.isLogin);
+ const useHydrateAgentConfig = useAgentStore((s) => s.useHydrateAgentConfig);
+ useHydrateAgentConfig(isLogin, agentId);
+ const context = useMemo<ConversationContext>(
+ () => ({ agentId, isolatedTopic: true, scope: 'main', topicId }),
+ [agentId, topicId],
+ );
+ const operationState = useOperationState(context);
+ return (
+ <ConversationProvider context={context} operationState={operationState}>
+ <Flexbox flex={1} style={{ minHeight: 0, overflow: 'hidden' }}>
+ <ChatList disableActionsBar itemContent={renderMessage} />
+ </Flexbox>
+ </ConversationProvider>
+ );
+};
+
+/** The Agent topic behind a reply, beside the Channel like a thread. */
+export function ReplyTopicPanel({
+ availableWidth = 1000,
+ topic,
+ onClose,
+}: {
+ availableWidth?: number;
+ onClose: () => void;
+ topic: ReplyTopic | null;
+}) {
+ const { t } = useTranslation('channel');
+ const navigate = useWorkspaceAwareNavigate();
+ // Keep the last topic mounted while the panel animates closed.
+ const [lastTopic, setLastTopic] = useState(topic);
+ const [preferredWidth, setPreferredWidth] = useState(520);
+ if (topic && topic !== lastTopic) setLastTopic(topic);
+ const narrow = availableWidth < THREAD_FLOAT_BREAKPOINT;
+ const maxWidth = narrow ? availableWidth : availableWidth - 360;
+ const width = Math.min(preferredWidth, maxWidth);
+
+ return (
+ <RightPanel
+ className={stylex.props(styles.threadPanel).className}
+ classNames={{ content: stylex.props(styles.threadContent).className }}
+ expand={!!topic}
+ maxWidth={maxWidth}
+ minWidth={Math.min(360, maxWidth)}
+ mode={narrow ? 'float' : 'fixed'}
+ showHandleWhenCollapsed={false}
+ showHandleWideArea={false}
+ width={narrow ? availableWidth : width}
+ onExpandChange={(expand) => {
+ if (!expand) onClose();
+ }}
+ onSizeChange={(size) => {
+ const next = Number.parseFloat(String(size?.width));
+ if (Number.isFinite(next)) setPreferredWidth(next);
+ }}
+ >
+ <Activity mode={topic ? 'visible' : 'hidden'}>
+ <Flexbox aria-label={t('topic.title')} role="region" {...stylex.props(styles.body)}>
+ <NavHeader
+ paddingBlock={6}
+ paddingInline={8}
+ showTogglePanelButton={false}
+ left={
+ lastTopic && (
+ <Flexbox
+ horizontal
+ align="center"
+ gap={8}
+ style={{ marginInlineStart: 4, minWidth: 0 }}
+ >
+ <AgentAvatar
+ agentId={lastTopic.agentId}
+ avatar={lastTopic.avatar}
+ name={lastTopic.name}
+ shape={'circle'}
+ size={20}
+ />
+ <Text ellipsis fontSize={14}>
+ {t('topic.titleNamed', { name: lastTopic.name })}
+ </Text>
+ </Flexbox>
+ )
+ }
+ right={
+ <Flexbox horizontal align="center" gap={4}>
+ {lastTopic && (
+ <ActionIcon
+ aria-label={t('topic.openPage')}
+ icon={ExternalLink}
+ size="small"
+ title={t('topic.openPage')}
+ onClick={() =>
+ navigate(AGENT_CHAT_TOPIC_URL(lastTopic.agentId, lastTopic.topicId))
+ }
+ />
+ )}
+ <ActionIcon
+ aria-label={t('topic.close')}
+ icon={X}
+ size="small"
+ title={t('topic.close')}
+ onClick={onClose}
+ />
+ </Flexbox>
+ }
+ {...stylex.props(styles.threadHeader)}
+ />
+ {lastTopic && (
+ <TopicConversation
+ agentId={lastTopic.agentId}
+ key={lastTopic.topicId}
+ topicId={lastTopic.topicId}
+ />
+ )}
+ </Flexbox>
+ </Activity>
+ </RightPanel>
+ );
+}
diff --git a/src/features/Channels/index.tsx b/src/features/Channels/index.tsx
index 1ca5ff30cb3..ef4ccca2a2f 100644
--- a/src/features/Channels/index.tsx
+++ b/src/features/Channels/index.tsx
@@ -14,9 +14,10 @@ import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfi
import { visibleChannelDetail } from './channelAccess';
import { ChannelConversation } from './ChannelConversation';
-import { MemberAvatar } from './MemberAvatar';
import { MEMBER_FLOAT_BREAKPOINT, MemberPanel } from './MemberPanel';
import { MemberStatus } from './MemberStatus';
+import { DirectReplyStatus } from './ReplyActivity';
+import { type ReplyTopic, ReplyTopicPanel } from './ReplyTopicPanel';
import { styles } from './styles';
import { THREAD_FLOAT_BREAKPOINT, ThreadPanel } from './ThreadPanel';
import { useThreadPanel } from './useThreadPanel';
@@ -34,27 +35,36 @@ function EnabledChannelPage() {
const view = { channelId: channelId ?? '', threadId: null };
const sync = channelActions.useFetchDetail(channelId ? view : null);
const detail = visibleChannelDetail(useChannelStore(channelSelectors.detail(view)), sync.error);
- // A direct conversation is titled by its Agent, so it shows the Agent rather than a `#`.
const directAgent = detail?.channel.agentId
? detail.members.find((member) => member.agentId === detail.channel.agentId)
: undefined;
+ const [topic, setTopic] = useState<(ReplyTopic & { channelId: string }) | null>(null);
const membersOpen =
!!detail?.channel.workspaceId &&
membersChannelId === channelId &&
!panel.threadId &&
!panel.draft;
+ // One side panel at a time: a thread or the member list replaces the topic.
+ const openTopic =
+ topic?.channelId === channelId && !panel.threadId && !panel.draft && !membersOpen
+ ? topic
+ : null;
if (!channelId) return null;
return (
<Flexbox {...stylex.props(styles.layout)}>
<NavHeader
+ // A rule separates the header from the feed scrolling under it.
+ {...stylex.props(styles.threadHeader)}
left={
<Flexbox horizontal align="center" gap={8}>
- {directAgent ? <MemberAvatar member={directAgent} size={24} /> : <Hash size={18} />}
+ {/* A direct conversation is titled by its Agent's name alone, like an IM chat. */}
+ {!directAgent && <Hash size={18} />}
<Text ellipsis weight={500}>
{detail?.channel.title || t('title')}
</Text>
{detail?.channel.status === 'archived' && <Tag size="small">{t('archived')}</Tag>}
+ {directAgent && <DirectReplyStatus detail={detail!} />}
</Flexbox>
}
right={
@@ -67,7 +77,10 @@ function EnabledChannelPage() {
id: memberPanelId,
open: membersOpen,
onToggle: () => {
- if (!membersOpen) panel.close();
+ if (!membersOpen) {
+ panel.close();
+ setTopic(null);
+ }
setMembersChannelId(membersOpen ? null : channelId);
},
}
@@ -84,10 +97,22 @@ function EnabledChannelPage() {
inert={
(!!(panel.threadId || panel.draft) &&
(conversationWidth ?? 1000) < THREAD_FLOAT_BREAKPOINT) ||
- (membersOpen && (conversationWidth ?? 1000) < MEMBER_FLOAT_BREAKPOINT)
+ (membersOpen && (conversationWidth ?? 1000) < MEMBER_FLOAT_BREAKPOINT) ||
+ (!!openTopic && (conversationWidth ?? 1000) < THREAD_FLOAT_BREAKPOINT)
}
- onOpenThread={panel.openThread}
- onStartThread={panel.openDraft}
+ onOpenThread={(threadId, toggle) => {
+ setTopic(null);
+ panel.openThread(threadId, toggle);
+ }}
+ onOpenTopic={(next) => {
+ panel.close();
+ setMembersChannelId(null);
+ setTopic({ ...next, channelId });
+ }}
+ onStartThread={(draft) => {
+ setTopic(null);
+ panel.openDraft(draft);
+ }}
/>
{detail && membersOpen && (
<MemberPanel
@@ -97,6 +122,11 @@ function EnabledChannelPage() {
onClose={() => setMembersChannelId(null)}
/>
)}
+ <ReplyTopicPanel
+ availableWidth={conversationWidth}
+ topic={openTopic}
+ onClose={() => setTopic(null)}
+ />
{detail && (
<ThreadPanel
availableWidth={conversationWidth}
diff --git a/src/features/Channels/jobStatus.test.ts b/src/features/Channels/jobStatus.test.ts
index 071bc4e4dbc..df920bd3f4d 100644
--- a/src/features/Channels/jobStatus.test.ts
+++ b/src/features/Channels/jobStatus.test.ts
@@ -4,6 +4,7 @@ import { describe, expect, it } from 'vitest';
import {
channelJobStatus,
channelJobTone,
+ directReplyStatus,
memberCurrentJob,
replyActivityJobs,
unresolvedFailures,
@@ -137,3 +138,39 @@ describe('Channel task tone', () => {
expect(unresolvedFailures(jobs).map((entry) => entry.id)).toEqual(['b-failed']);
});
});
+
+describe('directReplyStatus', () => {
+ const job = (patch: Partial<ChannelPublicJob> = {}) =>
+ ({
+ id: 'job_1',
+ memberId: 'mem_cook',
+ publicationRevoked: false,
+ status: 'running',
+ threadId: null,
+ writerHeld: false,
+ ...patch,
+ }) as ChannelPublicJob;
+ const detail = (jobs: ChannelPublicJob[], messages: unknown[] = []) =>
+ ({ channel: { agentId: 'agt_cook', id: 'chn_cook' }, jobs, members: [], messages }) as never;
+
+ it('is typing while the Agent replies or prepares', () => {
+ expect(directReplyStatus(detail([job()]))?.waiting).toBeUndefined();
+ expect(
+ directReplyStatus(detail([job({ blockedCode: undefined, status: 'queued' })]))?.waiting,
+ ).toBeUndefined();
+ });
+
+ it('is typing while a sent message is still being routed', () => {
+ expect(directReplyStatus(detail([], [{ routingStatus: 'pending' }]))).toEqual({ jobs: [] });
+ });
+
+ it('names what a blocked reply waits on instead of typing', () => {
+ const blocked = job({ blockedCode: 'device_offline', status: 'queued' });
+ expect(directReplyStatus(detail([blocked]))?.waiting).toBe(blocked);
+ });
+
+ it('ignores thread replies and settled conversations', () => {
+ expect(directReplyStatus(detail([job({ threadId: 'thr_1' })]))).toBeNull();
+ expect(directReplyStatus(detail([job({ status: 'completed' })]))).toBeNull();
+ });
+});
diff --git a/src/features/Channels/jobStatus.ts b/src/features/Channels/jobStatus.ts
index 08b7f5c35ec..7ff872eb6b3 100644
--- a/src/features/Channels/jobStatus.ts
+++ b/src/features/Channels/jobStatus.ts
@@ -1,4 +1,4 @@
-import type { ChannelPublicJob } from '@lobechat/types';
+import type { ChannelDetail, ChannelPublicJob } from '@lobechat/types';
export const channelJobStatus = (job: ChannelPublicJob) =>
job.publicationRevoked && job.writerHeld
@@ -52,3 +52,23 @@ export const memberCurrentJob = (jobs: ChannelPublicJob[], memberId: string) =>
unresolvedFailures(own)[0]
);
};
+
+/** Replies a conversation still waits on, and whether a sent message awaits routing. */
+export const conversationReplies = (detail: ChannelDetail, threadId: string | null) => {
+ const { jobs = [], messages = [] } = detail;
+ return {
+ jobs: replyActivityJobs(jobs.filter((job) => (job.threadId ?? null) === threadId)),
+ receiving: messages.some((message) => message.routingStatus === 'pending'),
+ };
+};
+
+/**
+ * What a direct conversation's header says about its one Agent: "typing" while it works, or the
+ * reply it is `waiting` on when blocked or stopping. Null when nothing is pending.
+ */
+export const directReplyStatus = (detail: ChannelDetail) => {
+ const { jobs, receiving } = conversationReplies(detail, null);
+ const job = jobs[0] && memberCurrentJob(jobs, jobs[0].memberId);
+ if (!job) return receiving ? { jobs } : null;
+ return channelJobTone(job) === 'working' ? { jobs } : { jobs, waiting: job };
+};
diff --git a/src/features/Channels/styles.ts b/src/features/Channels/styles.ts
index 45842b0cdab..a28f6d2a631 100644
--- a/src/features/Channels/styles.ts
+++ b/src/features/Channels/styles.ts
@@ -334,6 +334,14 @@ export const activityStyles = stylex.create({
paddingInline: 4,
color: cssVar.colorTextSecondary,
},
+ /** Beside the Agent's name in a direct conversation's header. */
+ header: {
+ color: cssVar.colorTextDescription,
+ },
+ headerButton: {
+ height: 22,
+ paddingInline: 4,
+ },
avatars: {
display: 'inline-flex',
flex: 'none',