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(agent-share): show share visitor topics in the Agent sidebar (#23497)

YuTengjingf77357e96ff8
diff --git a/apps/server/src/routers/lambda/channel.ts b/apps/server/src/routers/lambda/channel.ts
index 156ec6e17e6..954494fa1ba 100644
--- a/apps/server/src/routers/lambda/channel.ts
+++ b/apps/server/src/routers/lambda/channel.ts
@@ -254,6 +254,20 @@ export const channelRouter = router({
data: await ctx.channelService.shareVisitors(input.agentId),
success: true,
})),
+ /** A visitor's run topic with its transcript, read-only for the shared Agent's owner. */
+ shareVisitorTopic: channelProcedure
+ .input(z.object({ topicId: z.string().min(1) }))
+ .query(async ({ ctx, input }) => ({
+ data: await ctx.channelService.shareVisitorTopic(input.topicId),
+ success: true,
+ })),
+ /** The run topics of visitors' conversations with the caller's shared Agent, by visitor. */
+ shareVisitorTopics: channelProcedure
+ .input(z.object({ agentId: z.string().min(1) }))
+ .query(async ({ ctx, input }) => ({
+ data: await ctx.channelService.shareVisitorTopics(input.agentId),
+ success: true,
+ })),
/** Messages in a Channel and its Threads containing every word of `query`, newest first. */
searchMessages: channelProcedure
.input(
diff --git a/apps/server/src/services/channel/ChannelService.shareVisitorTopic.test.ts b/apps/server/src/services/channel/ChannelService.shareVisitorTopic.test.ts
new file mode 100644
index 00000000000..807f733d3e0
--- /dev/null
+++ b/apps/server/src/services/channel/ChannelService.shareVisitorTopic.test.ts
@@ -0,0 +1,68 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ChannelError } from '@/database/repositories/channel';
+
+import { ChannelService } from './ChannelService';
+
+const { findTopic, query } = vi.hoisted(() => ({ findTopic: vi.fn(), query: vi.fn() }));
+vi.mock('@/database/repositories/channel/shareVisitors', async (original) => ({
+ ...(await original<object>()),
+ findShareVisitorTopic: findTopic,
+}));
+vi.mock('@/database/models/message', () => ({
+ MessageModel: class {
+ query = query;
+ },
+}));
+vi.mock('@/database/models/project', () => ({ ProjectModel: class {} }));
+vi.mock('@/database/models/device', () => ({ DeviceModel: class {} }));
+vi.mock('@/server/services/agent', () => ({ AgentService: class {} }));
+vi.mock('@/server/services/file', () => ({
+ FileService: class {
+ getFileAccessUrl = vi.fn();
+ },
+}));
+vi.mock('./ChannelCoordinator', () => ({ ChannelCoordinator: class {} }));
+vi.mock('./notify', () => ({ notifyChannel: vi.fn() }));
+vi.mock('./queue', () => ({ wakeChannel: vi.fn() }));
+
+const visitor = { avatar: 'vee.png', id: 'visitor', name: 'Visitor Vee' };
+const service = () => new ChannelService({} as never, 'owner');
+
+describe('reading a share visitor topic', () => {
+ beforeEach(() => {
+ vi.resetAllMocks();
+ });
+
+ it('refuses a topic the caller may not read, without reading its messages', async () => {
+ findTopic.mockResolvedValue(undefined);
+
+ await expect(service().shareVisitorTopic('tpc_1')).rejects.toBeInstanceOf(ChannelError);
+ expect(query).not.toHaveBeenCalled();
+ });
+
+ it('reads the transcript past the visitor guard and credits the visitor with their turns', async () => {
+ findTopic.mockResolvedValue({ agentId: 'agt_1', id: 'tpc_1', visitor });
+ query.mockResolvedValue([
+ { id: 'msg_1', role: 'user', sender: { fullName: 'Owner', id: 'owner' } },
+ { id: 'msg_2', role: 'assistant' },
+ ]);
+
+ const { messages } = await service().shareVisitorTopic('tpc_1');
+
+ expect(query).toHaveBeenCalledWith(
+ // The whole transcript, not the default newest window: the page holds it without paging.
+ { agentId: 'agt_1', pageSize: 100_000, topicId: 'tpc_1' },
+ expect.objectContaining({ allowShareVisitor: true }),
+ );
+ expect(messages).toEqual([
+ {
+ id: 'msg_1',
+ role: 'user',
+ sender: { avatar: 'vee.png', fullName: 'Visitor Vee', id: 'visitor' },
+ },
+ { id: 'msg_2', role: 'assistant' },
+ ]);
+ });
+});
diff --git a/apps/server/src/services/channel/ChannelService.ts b/apps/server/src/services/channel/ChannelService.ts
index e16f2c4410f..e9b9fe28209 100644
--- a/apps/server/src/services/channel/ChannelService.ts
+++ b/apps/server/src/services/channel/ChannelService.ts
@@ -15,6 +15,7 @@ import pMap from 'p-map';
import { AgentShareModel } from '@/database/models/agentShare';
import { ContactModel, parseContactHandle } from '@/database/models/contact';
import { DeviceModel } from '@/database/models/device';
+import { MessageModel } from '@/database/models/message';
import type { ProjectModelOptions } from '@/database/models/project';
import { ProjectModel } from '@/database/models/project';
import type {
@@ -25,7 +26,9 @@ import type {
import { ChannelError, ChannelRepository } from '@/database/repositories/channel';
import { findProjectMainChannelId } from '@/database/repositories/channel/projectMainChannel';
import {
+ findShareVisitorTopic,
listShareVisitorConversations,
+ listShareVisitorTopics,
readShareVisitorChannel,
} from '@/database/repositories/channel/shareVisitors';
import { users } from '@/database/schemas';
@@ -56,6 +59,9 @@ const agentRuntime = (agent: Pick<ChannelAgentConfig, 'agencyConfig' | 'model'>)
agent.agencyConfig?.heterogeneousProvider?.type ??
(isHeterogeneousAgentModelId(agent.model) ? agent.model : 'native');
+/** Scan guard for a visitor topic transcript, which is read whole (see `shareVisitorTopic`). */
+const SHARE_VISITOR_TRANSCRIPT_ROW_CEILING = 100_000;
+
export class ChannelService {
readonly repository: ChannelRepository;
private readonly agentService: AgentService;
@@ -462,6 +468,39 @@ export class ChannelService {
/** Visitor conversations with the caller's shared Agent, when its share lets the caller read them. */
shareVisitors = (agentId: string) => listShareVisitorConversations(this.db, this.userId, agentId);
+ /** The run topics of those conversations, grouped by visitor, for the Agent's sidebar. */
+ shareVisitorTopics = (agentId: string) => listShareVisitorTopics(this.db, this.userId, agentId);
+
+ /**
+ * A visitor's run topic with its full transcript, for the share's owner to read. The owner pays
+ * for and is accountable for these runs, so the transcript keeps model, usage and error details;
+ * only this read opts in to visitor rows, and every write path still refuses them.
+ */
+ shareVisitorTopic = async (topicId: string) => {
+ const topic = await findShareVisitorTopic(this.db, this.userId, topicId);
+ if (!topic) throw new ChannelError('NOT_FOUND', 'Topic not found');
+ const files = new FileService(this.db, this.userId, this.workspaceId);
+ const messages = await new MessageModel(this.db, this.userId, this.workspaceId).query(
+ // The page holds the transcript without paging, so read it whole rather than the default
+ // newest window: the share's per-visitor message cap already bounds a topic.
+ { agentId: topic.agentId, pageSize: SHARE_VISITOR_TRANSCRIPT_ROW_CEILING, topicId },
+ {
+ allowShareVisitor: true,
+ postProcessUrl: (path, file) => files.getFileAccessUrl({ id: file.id, url: path }),
+ },
+ );
+ // Visitor turns persist under the owner, so their joined sender is the owner; the visitor
+ // wrote them.
+ const { visitor } = topic;
+ const sender = { avatar: visitor.avatar, fullName: visitor.name, id: visitor.id };
+ return {
+ messages: messages.map((message) =>
+ message.role === 'user' ? { ...message, sender } : message,
+ ),
+ topic,
+ };
+ };
+
/**
* A Channel the caller is a member of or can read openly; failing that, a visitor's conversation
* with the caller's shared Agent, read-only.
diff --git a/locales/en-US/topic.json b/locales/en-US/topic.json
index eb61dc8ad25..be4c4bc75c3 100644
--- a/locales/en-US/topic.json
+++ b/locales/en-US/topic.json
@@ -300,6 +300,11 @@
"scheduledStatusTip": "Scheduled to run at {{time}}.",
"searchPlaceholder": "Search Topics...",
"searchResultEmpty": "No search results found.",
+ "shareVisitorTopics.readOnly": "Read-only",
+ "shareVisitorTopics.readOnlyHint": "A visitor's conversation through your share link. You can read it, but not reply or change it.",
+ "shareVisitorTopics.title": "Visitors",
+ "shareVisitorTopics.unavailable": "This conversation is no longer available",
+ "shareVisitorTopics.untitled": "Untitled conversation",
"sidebar.collapseAll": "Collapse all groups",
"sidebar.expandAll": "Expand all groups",
"sidebar.title": "Topics",
diff --git a/locales/zh-CN/topic.json b/locales/zh-CN/topic.json
index 9a2a059d355..f6d9157abe9 100644
--- a/locales/zh-CN/topic.json
+++ b/locales/zh-CN/topic.json
@@ -300,6 +300,11 @@
"scheduledStatusTip": "将于 {{time}} 运行",
"searchPlaceholder": "搜索话题…",
"searchResultEmpty": "暂无搜索结果",
+ "shareVisitorTopics.readOnly": "只读",
+ "shareVisitorTopics.readOnlyHint": "访客通过你的分享链接发起的对话,只能查看,不能回复或修改。",
+ "shareVisitorTopics.title": "访客",
+ "shareVisitorTopics.unavailable": "该对话已无法查看",
+ "shareVisitorTopics.untitled": "未命名对话",
"sidebar.collapseAll": "折叠所有分组",
"sidebar.expandAll": "展开所有分组",
"sidebar.title": "话题",
diff --git a/packages/const/src/url.ts b/packages/const/src/url.ts
index ddb04bc1b85..8ad41bcbf09 100644
--- a/packages/const/src/url.ts
+++ b/packages/const/src/url.ts
@@ -78,6 +78,10 @@ export const AGENT_CHAT_TOPIC_PAGE_URL = (agentId: string, topicId: string, mobi
return urlJoin('/agent', agentId, topicId, 'page');
};
+/** A share visitor's run topic, opened read-only by the shared Agent's owner. */
+export const AGENT_SHARE_VISITOR_TOPIC_URL = (agentId: string, topicId: string) =>
+ urlJoin('/agent', agentId, 'visitor', topicId);
+
export const AGENT_PROFILE_URL = (agentId: string) => `/agent/${agentId}/profile`;
export const GROUP_CHAT_URL = (groupId: string) => `/group/${groupId}`;
diff --git a/packages/database/src/repositories/channel/__tests__/shareVisitors.test.ts b/packages/database/src/repositories/channel/__tests__/shareVisitors.test.ts
index 63788160af4..6e0a63a29a6 100644
--- a/packages/database/src/repositories/channel/__tests__/shareVisitors.test.ts
+++ b/packages/database/src/repositories/channel/__tests__/shareVisitors.test.ts
@@ -5,7 +5,12 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
import { agents, agentShares, topics, users } from '../../../schemas';
import { ChannelExecutionRepository, ChannelRepository } from '..';
-import { listShareVisitorConversations, readShareVisitorChannel } from '../shareVisitors';
+import {
+ findShareVisitorTopic,
+ listShareVisitorConversations,
+ listShareVisitorTopics,
+ readShareVisitorChannel,
+} from '../shareVisitors';
import { createChannelFixture, jobsOf, lease } from './testUtils';
const db = await getTestDB();
@@ -134,3 +139,76 @@ describe('share visitor conversations', () => {
expect(await readShareVisitorChannel(db, ownerId, channel.id)).toBeUndefined();
});
});
+
+describe('share visitor topics', () => {
+ it('stay hidden from the creator until the share lets them read them', async () => {
+ const { topicId } = await openConversation(0.5, 1200);
+
+ expect(await listShareVisitorTopics(db, ownerId, agentId)).toEqual([]);
+ expect(await findShareVisitorTopic(db, ownerId, topicId)).toBeUndefined();
+ });
+
+ it('list each visitor with the run topics of their conversation', async () => {
+ await setCreatorView(true);
+ const { topicId } = await openConversation(0.25, 1500);
+
+ expect(await listShareVisitorTopics(db, ownerId, agentId)).toEqual([
+ {
+ topics: [
+ expect.objectContaining({
+ id: topicId,
+ preview: 'Hello helper',
+ totalCost: 0.25,
+ totalTokens: 1500,
+ }),
+ ],
+ visitor: expect.objectContaining({ id: visitorId, name: 'Visitor Vee' }),
+ },
+ ]);
+ expect(await findShareVisitorTopic(db, ownerId, topicId)).toMatchObject({
+ agentId,
+ id: topicId,
+ visitor: { id: visitorId, name: 'Visitor Vee' },
+ });
+ });
+
+ it('are listed and opened only by the Agent owner', async () => {
+ await setCreatorView(true);
+ const { topicId } = await openConversation(0.25, 1500);
+
+ expect(await listShareVisitorTopics(db, visitorId, agentId)).toEqual([]);
+ expect(await findShareVisitorTopic(db, visitorId, topicId)).toBeUndefined();
+ });
+
+ it('drop a topic once it is trashed', async () => {
+ await setCreatorView(true);
+ const { topicId } = await openConversation(0.25, 1500);
+ await db
+ .update(topics)
+ .set({ deletedAt: new Date(), isDeleted: true })
+ .where(eq(topics.id, topicId));
+
+ expect(await listShareVisitorTopics(db, ownerId, agentId)).toEqual([]);
+ expect(await findShareVisitorTopic(db, ownerId, topicId)).toBeUndefined();
+ });
+
+ it('keep a Workspace member’s own run topics private', async () => {
+ await setCreatorView(true);
+ await db
+ .update(agents)
+ .set({ visibility: 'public', workspaceId: fixture.workspaceId })
+ .where(eq(agents.id, agentId));
+ const member = new ChannelRepository(db, visitorId, fixture.workspaceId);
+ const { channel } = await member.create({ agentId, title: 'Helper' });
+ const message = await member.send(channel.id, {
+ content: 'Workspace question',
+ requestKey: 'member',
+ routing: 'fallback',
+ });
+ const [job] = await jobsOf(db, message.id);
+ const claim = (await execution.claim(channel.id, job.id, lease))!;
+
+ expect(await listShareVisitorTopics(db, ownerId, agentId)).toEqual([]);
+ expect(await findShareVisitorTopic(db, ownerId, claim.topic.id)).toBeUndefined();
+ });
+});
diff --git a/packages/database/src/repositories/channel/shareVisitors.ts b/packages/database/src/repositories/channel/shareVisitors.ts
index 8d68c85f417..bbaa486dbe8 100644
--- a/packages/database/src/repositories/channel/shareVisitors.ts
+++ b/packages/database/src/repositories/channel/shareVisitors.ts
@@ -1,4 +1,10 @@
-import type { ShareVisitorConversation } from '@lobechat/types';
+import type {
+ ShareVisitorConversation,
+ ShareVisitorIdentity,
+ ShareVisitorTopic,
+ ShareVisitorTopicGroup,
+} from '@lobechat/types';
+import type { SQL } from 'drizzle-orm';
import { and, desc, eq, inArray, isNotNull, ne, sql } from 'drizzle-orm';
import { agents, agentShares, channelJobs, channels, topics, users } from '../../schemas';
@@ -98,6 +104,121 @@ export const listShareVisitorConversations = async (
}));
};
+/** Characters of the visitor's first message kept to name an untitled run topic. */
+const SHARE_VISITOR_TOPIC_PREVIEW_LENGTH = 100;
+
+/**
+ * Run topics behind the visitor Channels `ownerId` may read (see {@link shareVisitorChannelWhere}).
+ * The topic belongs to the owner and records the visitor as its sender; both are checked so a
+ * topic reached through a Channel job never widens into another user's topics.
+ */
+const shareVisitorTopics = (db: LobeChatDatabase | Transaction, ownerId: string, scope: SQL) =>
+ db
+ .selectDistinct({
+ agentId: channels.agentId,
+ topic: {
+ createdAt: topics.createdAt,
+ id: topics.id,
+ // The Channel message that started the topic's first run: it exists from the claim on,
+ // before the run writes its own copy into the topic.
+ preview: sql<string | null>`(
+ SELECT left(m.content, ${SHARE_VISITOR_TOPIC_PREVIEW_LENGTH})
+ FROM channel_jobs j JOIN channel_messages m ON m.id = j.message_id
+ WHERE j.topic_id = ${topics.id}
+ ORDER BY m.created_at
+ LIMIT 1
+ )`,
+ title: topics.title,
+ totalCost: topics.totalCost,
+ totalTokens: topics.totalTokens,
+ updatedAt: topics.updatedAt,
+ },
+ visitorAvatar: users.avatar,
+ visitorId: channels.userId,
+ visitorName: users.fullName,
+ visitorUsername: users.username,
+ })
+ .from(topics)
+ .innerJoin(channelJobs, eq(channelJobs.topicId, topics.id))
+ .innerJoin(channels, eq(channels.id, channelJobs.channelId))
+ .innerJoin(agents, eq(agents.id, channels.agentId))
+ .innerJoin(agentShares, eq(agentShares.agentId, agents.id))
+ .leftJoin(users, eq(users.id, channels.userId))
+ .where(
+ and(
+ scope,
+ shareVisitorChannelWhere(ownerId),
+ eq(topics.userId, ownerId),
+ eq(topics.senderId, channels.userId),
+ notTrashed(topics.isDeleted),
+ ),
+ );
+
+/**
+ * Topics one sidebar list returns across every visitor of an Agent, newest first. Older topics
+ * beyond it drop out of the sidebar but still open from a link ({@link findShareVisitorTopic}).
+ */
+const SHARE_VISITOR_TOPIC_LIMIT = 500;
+
+/**
+ * The run topics of every visitor conversation with `ownerId`'s Agent the owner may read, grouped
+ * by visitor. Visitors and their topics are both ordered by latest activity.
+ */
+export const listShareVisitorTopics = async (
+ db: LobeChatDatabase,
+ ownerId: string,
+ agentId: string,
+): Promise<ShareVisitorTopicGroup[]> => {
+ const rows = await shareVisitorTopics(db, ownerId, eq(channels.agentId, agentId))
+ .orderBy(desc(topics.updatedAt), desc(topics.id))
+ .limit(SHARE_VISITOR_TOPIC_LIMIT);
+
+ const groups = new Map<string, ShareVisitorTopicGroup>();
+ for (const { topic, visitorAvatar, visitorId, visitorName, visitorUsername } of rows) {
+ if (!visitorId) continue;
+ let group = groups.get(visitorId);
+ if (!group) {
+ group = {
+ topics: [],
+ visitor: { avatar: visitorAvatar, id: visitorId, name: visitorName || visitorUsername },
+ };
+ groups.set(visitorId, group);
+ }
+ group.topics.push({
+ ...topic,
+ totalCost: Number(topic.totalCost ?? 0),
+ totalTokens: topic.totalTokens ?? 0,
+ });
+ }
+ return [...groups.values()];
+};
+
+/**
+ * A visitor's run topic as the share's owner may open it, with the Agent and visitor it belongs to.
+ * Undefined when `viewerId` may not read it.
+ */
+export const findShareVisitorTopic = async (
+ db: LobeChatDatabase,
+ viewerId: string,
+ topicId: string,
+): Promise<
+ (ShareVisitorTopic & { agentId: string; visitor: ShareVisitorIdentity }) | undefined
+> => {
+ const [row] = await shareVisitorTopics(db, viewerId, eq(topics.id, topicId)).limit(1);
+ if (!row?.visitorId || !row.agentId) return;
+ return {
+ ...row.topic,
+ agentId: row.agentId,
+ totalCost: Number(row.topic.totalCost ?? 0),
+ totalTokens: row.topic.totalTokens ?? 0,
+ visitor: {
+ avatar: row.visitorAvatar,
+ id: row.visitorId,
+ name: row.visitorName || row.visitorUsername,
+ },
+ };
+};
+
/**
* A visitor's conversation as the share's owner reads it: the same public view the visitor sees,
* read-only. Run topic links are left out — the owner's topic views exclude visitor topics, so
diff --git a/packages/locales/src/default/topic.ts b/packages/locales/src/default/topic.ts
index 929f683033f..7746f977afc 100644
--- a/packages/locales/src/default/topic.ts
+++ b/packages/locales/src/default/topic.ts
@@ -334,6 +334,12 @@ export default {
'scheduledStatusTip': 'Scheduled to run at {{time}}.',
'searchPlaceholder': 'Search Topics...',
'searchResultEmpty': 'No search results found.',
+ 'shareVisitorTopics.readOnly': 'Read-only',
+ 'shareVisitorTopics.readOnlyHint':
+ "A visitor's conversation through your share link. You can read it, but not reply or change it.",
+ 'shareVisitorTopics.title': 'Visitors',
+ 'shareVisitorTopics.unavailable': 'This conversation is no longer available',
+ 'shareVisitorTopics.untitled': 'Untitled conversation',
'sidebar.collapseAll': 'Collapse all groups',
'sidebar.expandAll': 'Expand all groups',
'sidebar.title': 'Topics',
diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.ts
index fbb283af4ca..15df7bf4be2 100644
--- a/packages/types/src/channel.ts
+++ b/packages/types/src/channel.ts
@@ -972,5 +972,37 @@ export interface ShareVisitorConversation {
totalCost: number;
totalTokens: number;
updatedAt: Date;
- visitor: { avatar: string | null; id: string; name: string | null };
+ visitor: ShareVisitorIdentity;
+}
+
+/** A share visitor as the shared Agent's owner sees them. */
+export interface ShareVisitorIdentity {
+ avatar: string | null;
+ id: string;
+ name: string | null;
+}
+
+/**
+ * One run topic of a visitor's conversation with a shared Agent. A visitor's conversation spans
+ * several: a new one starts after a long pause or when the Agent's configuration changes.
+ */
+export interface ShareVisitorTopic {
+ createdAt: Date;
+ id: string;
+ /**
+ * The start of the visitor's first message. Run topics get no generated title, so this is what
+ * names one when `title` is empty.
+ */
+ preview: string | null;
+ title: string | null;
+ /** USD cost of the topic's runs. */
+ totalCost: number;
+ totalTokens: number;
+ updatedAt: Date;
+}
+
+/** A visitor's run topics with a shared Agent, newest first, for its owner's sidebar. */
+export interface ShareVisitorTopicGroup {
+ topics: ShareVisitorTopic[];
+ visitor: ShareVisitorIdentity;
}
diff --git a/src/components/Skeleton/Conversation/ReadOnly.tsx b/src/components/Skeleton/Conversation/ReadOnly.tsx
new file mode 100644
index 00000000000..e52c902f205
--- /dev/null
+++ b/src/components/Skeleton/Conversation/ReadOnly.tsx
@@ -0,0 +1,19 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+
+import SkeletonBar from '../Bar';
+import ConversationListSkeleton from './List';
+
+/** A read-only transcript page: a header naming the conversation over its messages, no composer. */
+const ReadOnlyConversationSkeleton = () => (
+ <Flexbox aria-busy flex={1} height={'100%'} style={{ minHeight: 0, overflow: 'hidden' }}>
+ <Flexbox horizontal align={'center'} gap={8} height={44} paddingInline={16}>
+ <SkeletonBar height={20} radius={'50%'} width={20} />
+ <SkeletonBar height={14} width={160} />
+ </Flexbox>
+ <ConversationListSkeleton />
+ </Flexbox>
+);
+
+export default ReadOnlyConversationSkeleton;
diff --git a/src/features/AgentSidebar/Body.tsx b/src/features/AgentSidebar/Body.tsx
index 8b1b8b43857..c0c4bed5af5 100644
--- a/src/features/AgentSidebar/Body.tsx
+++ b/src/features/AgentSidebar/Body.tsx
@@ -1,6 +1,7 @@
import { AccordionRoot, Flexbox } from '@lobehub/ui';
import React, { memo, useCallback, useMemo } from 'react';
+import ShareVisitorTopicsSection from '@/features/ShareVisitorTopics/SidebarSection';
import { useAgentStore } from '@/store/agent';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
@@ -8,10 +9,12 @@ import { systemStatusSelectors } from '@/store/global/selectors';
import Topic from './Topic';
export enum ChatSidebarKey {
+ ShareVisitors = 'shareVisitors',
Topic = 'topic',
}
const DEFAULT_EXPANDED: Record<string, boolean> = {
+ [ChatSidebarKey.ShareVisitors]: true,
[ChatSidebarKey.Topic]: true,
};
@@ -33,6 +36,7 @@ const Body = memo(() => {
updateSystemStatus({
expandAgentSidebarSectionsByAgent: {
[agentId]: {
+ [ChatSidebarKey.ShareVisitors]: keys.includes(ChatSidebarKey.ShareVisitors),
[ChatSidebarKey.Topic]: keys.includes(ChatSidebarKey.Topic),
},
},
@@ -53,6 +57,9 @@ const Body = memo(() => {
expanded={expandedKeys.includes(ChatSidebarKey.Topic)}
itemKey={ChatSidebarKey.Topic}
/>
+ {agentId && (
+ <ShareVisitorTopicsSection agentId={agentId} itemKey={ChatSidebarKey.ShareVisitors} />
+ )}
</AccordionRoot>
</Flexbox>
);
diff --git a/src/features/AgentTopicManager/ShareVisitorSection.tsx b/src/features/AgentTopicManager/ShareVisitorSection.tsx
index 27929ddd807..97a168eb970 100644
--- a/src/features/AgentTopicManager/ShareVisitorSection.tsx
+++ b/src/features/AgentTopicManager/ShareVisitorSection.tsx
@@ -1,6 +1,6 @@
'use client';
-import { CHANNEL_URL } from '@lobechat/const';
+import { AGENT_SHARE_VISITOR_TOPIC_URL, CHANNEL_URL } from '@lobechat/const';
import type { ShareVisitorConversation } from '@lobechat/types';
import { formatPrice, formatTokenNumber } from '@lobechat/utils/format';
import { Block, Flexbox, Icon, Text } from '@lobehub/ui';
@@ -10,6 +10,7 @@ import { type KeyboardEvent, memo } from 'react';
import { useTranslation } from 'react-i18next';
import UserAvatar from '@/components/UserAvatar';
+import { useShareVisitorTopics } from '@/features/ShareVisitorTopics/useShareVisitorTopics';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useActivityTime } from '@/hooks/useActivityTime';
@@ -18,11 +19,24 @@ import { channelCardStyles as styles } from './ChannelSection';
/** Counts and amounts are compared across cards, so digits keep the same width. */
const NUMBER_STYLE = { fontVariantNumeric: 'tabular-nums' } as const;
-const ShareVisitorCard = memo<{ conversation: ShareVisitorConversation }>(({ conversation }) => {
+interface ShareVisitorCardProps {
+ agentId: string;
+ conversation: ShareVisitorConversation;
+ /** The visitor's newest run topic, where the full execution can be read. */
+ latestTopicId?: string;
+}
+
+const ShareVisitorCard = memo<ShareVisitorCardProps>(({ agentId, conversation, latestTopicId }) => {
const { t } = useTranslation('topic');
const navigate = useWorkspaceAwareNavigate();
const activity = useActivityTime(conversation.updatedAt ?? conversation.createdAt);
- const open = () => navigate(CHANNEL_URL(conversation.id));
+ // A conversation whose first run has not been claimed yet has no topic; its Channel shows it.
+ const open = () =>
+ navigate(
+ latestTopicId
+ ? AGENT_SHARE_VISITOR_TOPIC_URL(agentId, latestTopicId)
+ : CHANNEL_URL(conversation.id),
+ );
const name = conversation.visitor.name || t('management.shareVisitors.unnamedVisitor');
const preview = conversation.lastMessage?.content?.trim();
const { totalCost, totalTokens } = conversation;
@@ -91,12 +105,16 @@ ShareVisitorCard.displayName = 'AgentTopicManagerShareVisitorCard';
/**
* Visitors' conversations with the Agent through its share link, one card per visitor. Each opens
- * the visitor's Channel read-only; its run topics stay private execution context.
+ * the visitor's newest run topic read-only, beside the visitor's other topics in the sidebar.
*/
-const ShareVisitorSection = memo<{ conversations: ShareVisitorConversation[] }>(
- ({ conversations }) => {
+const ShareVisitorSection = memo<{ agentId: string; conversations: ShareVisitorConversation[] }>(
+ ({ agentId, conversations }) => {
const { t } = useTranslation('topic');
+ const topicGroups = useShareVisitorTopics(agentId);
if (conversations.length === 0) return null;
+ const latestTopicByVisitor = new Map(
+ topicGroups.map((group) => [group.visitor.id, group.topics[0]?.id]),
+ );
return (
<Flexbox gap={12}>
@@ -110,7 +128,12 @@ const ShareVisitorSection = memo<{ conversations: ShareVisitorConversation[] }>(
</Flexbox>
<div {...stylex.props(styles.grid)}>
{conversations.map((conversation) => (
- <ShareVisitorCard conversation={conversation} key={conversation.id} />
+ <ShareVisitorCard
+ agentId={agentId}
+ conversation={conversation}
+ key={conversation.id}
+ latestTopicId={latestTopicByVisitor.get(conversation.visitor.id)}
+ />
))}
</div>
</Flexbox>
diff --git a/src/features/AgentTopicManager/index.tsx b/src/features/AgentTopicManager/index.tsx
index 410bc5b0769..44f8595e6de 100644
--- a/src/features/AgentTopicManager/index.tsx
+++ b/src/features/AgentTopicManager/index.tsx
@@ -359,7 +359,7 @@ const AgentTopicManager = memo(() => {
onRetry={shareVisitors.retry}
/>
) : (
- <ShareVisitorSection conversations={visibleShareVisitors} />
+ <ShareVisitorSection agentId={activeAgentId} conversations={visibleShareVisitors} />
)}
{totalAfterFilter === 0 ? null : viewMode === 'card' ? (
<TopicGrid
diff --git a/src/features/ShareVisitorTopics/SidebarSection.tsx b/src/features/ShareVisitorTopics/SidebarSection.tsx
new file mode 100644
index 00000000000..db81becc20b
--- /dev/null
+++ b/src/features/ShareVisitorTopics/SidebarSection.tsx
@@ -0,0 +1,160 @@
+'use client';
+
+import { AGENT_SHARE_VISITOR_TOPIC_URL } from '@lobechat/const';
+import type { ShareVisitorTopicGroup } from '@lobechat/types';
+import {
+ AccordionHeader,
+ AccordionItem,
+ AccordionPanel,
+ AccordionRoot,
+ AccordionTrigger,
+ Flexbox,
+ Text,
+} from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import { useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useLocation } from 'react-router';
+
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+import UserAvatar from '@/components/UserAvatar';
+import NavItem from '@/features/NavPanel/components/NavItem';
+import SectionTitle, { useSectionTriggerStyle } from '@/features/NavPanel/components/SectionTitle';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
+
+import { useShareVisitorTopics } from './useShareVisitorTopics';
+
+const COUNT_STYLE = { fontVariantNumeric: 'tabular-nums' } as const;
+
+/** Lines topic titles up with the Agent's own topic rows, which lead with a status icon slot. */
+const ICON_PLACEHOLDER = <span aria-hidden style={{ flex: 'none', width: 16 }} />;
+
+const VisitorGroup = ({
+ activeTopicId,
+ agentId,
+ group,
+}: {
+ activeTopicId: string | undefined;
+ agentId: string;
+ group: ShareVisitorTopicGroup;
+}) => {
+ const { t } = useTranslation('topic');
+ const sectionTriggerStyle = useSectionTriggerStyle();
+ const navigate = useWorkspaceAwareNavigate();
+ const workspaceSlug = useActiveWorkspaceSlug();
+ const name = group.visitor.name || t('management.shareVisitors.unnamedVisitor');
+
+ return (
+ <AccordionItem value={group.visitor.id}>
+ <AccordionHeader>
+ <AccordionTrigger style={sectionTriggerStyle}>
+ <Flexbox horizontal align={'center'} gap={6} height={24} style={{ minWidth: 0 }}>
+ <UserAvatar
+ avatar={group.visitor.avatar}
+ name={name}
+ shape={'circle'}
+ size={16}
+ style={{ flex: 'none' }}
+ />
+ <SectionTitle>{name}</SectionTitle>
+ <Text fontSize={11} style={COUNT_STYLE} type={'secondary'}>
+ {group.topics.length}
+ </Text>
+ </Flexbox>
+ </AccordionTrigger>
+ </AccordionHeader>
+ <AccordionPanel contentStyle={{ padding: 0 }}>
+ <Flexbox gap={1} paddingBlock={1}>
+ {group.topics.map((topic) => {
+ const path = AGENT_SHARE_VISITOR_TOPIC_URL(agentId, topic.id);
+ return (
+ <NavItem
+ titleMarquee
+ active={topic.id === activeTopicId}
+ href={buildWorkspaceAwarePath(path, workspaceSlug)}
+ icon={ICON_PLACEHOLDER}
+ key={topic.id}
+ title={topic.title || topic.preview || t('shareVisitorTopics.untitled')}
+ titleColor={cssVar.colorText}
+ onClick={() => navigate(path)}
+ />
+ );
+ })}
+ </Flexbox>
+ </AccordionPanel>
+ </AccordionItem>
+ );
+};
+
+const VISITOR_TOPIC_PATH = /\/visitor\/([^/]+)\/?$/;
+
+interface ShareVisitorTopicsSectionProps {
+ agentId: string;
+ itemKey: string;
+}
+
+/**
+ * Visitors' conversations with the Agent through its share link, as run topics grouped by visitor.
+ * Shown only while the share lets the owner read them; each topic opens read-only.
+ */
+const ShareVisitorTopicsSection = ({ agentId, itemKey }: ShareVisitorTopicsSectionProps) => {
+ const { t } = useTranslation('topic');
+ const sectionTriggerStyle = useSectionTriggerStyle();
+ const groups = useShareVisitorTopics(agentId);
+ const { pathname } = useLocation();
+ const activeTopicId = VISITOR_TOPIC_PATH.exec(pathname)?.[1];
+ const activeVisitorId = useMemo(
+ () =>
+ activeTopicId
+ ? groups.find((group) => group.topics.some((topic) => topic.id === activeTopicId))?.visitor
+ .id
+ : undefined,
+ [activeTopicId, groups],
+ );
+ const [expanded, setExpanded] = useState<string[]>([]);
+ const [revealedVisitorId, setRevealedVisitorId] = useState<string>();
+
+ // Opening a topic from elsewhere (the Topics page) reveals it in its visitor's group, once per
+ // visitor so the group can still be collapsed afterwards.
+ if (activeVisitorId && activeVisitorId !== revealedVisitorId) {
+ setRevealedVisitorId(activeVisitorId);
+ if (!expanded.includes(activeVisitorId)) setExpanded([...expanded, activeVisitorId]);
+ }
+
+ if (groups.length === 0) return null;
+
+ return (
+ <AccordionItem value={itemKey}>
+ <AccordionHeader>
+ <AccordionTrigger style={sectionTriggerStyle}>
+ <Flexbox horizontal align="center" gap={4}>
+ <SectionTitle>{t('shareVisitorTopics.title')}</SectionTitle>
+ <Text fontSize={11} style={COUNT_STYLE} type="secondary">
+ {groups.length}
+ </Text>
+ </Flexbox>
+ </AccordionTrigger>
+ </AccordionHeader>
+ <AccordionPanel contentStyle={{ padding: 0 }}>
+ <AccordionRoot
+ indicatorPlacement="inline"
+ style={{ gap: 2 }}
+ value={expanded}
+ onValueChange={(next) => setExpanded(next as string[])}
+ >
+ {groups.map((group) => (
+ <VisitorGroup
+ activeTopicId={activeTopicId}
+ agentId={agentId}
+ group={group}
+ key={group.visitor.id}
+ />
+ ))}
+ </AccordionRoot>
+ </AccordionPanel>
+ </AccordionItem>
+ );
+};
+
+export default ShareVisitorTopicsSection;
diff --git a/src/features/ShareVisitorTopics/TopicView.tsx b/src/features/ShareVisitorTopics/TopicView.tsx
new file mode 100644
index 00000000000..0bdf7f46437
--- /dev/null
+++ b/src/features/ShareVisitorTopics/TopicView.tsx
@@ -0,0 +1,111 @@
+'use client';
+
+import type { ConversationContext } from '@lobechat/types';
+import { formatPrice, formatTokenNumber } from '@lobechat/utils/format';
+import { Center, Flexbox, Icon, Tag, Text } from '@lobehub/ui';
+import { CircleDollarSign, Zap } from 'lucide-react';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useParams } from 'react-router';
+
+import ReadOnlyConversationSkeleton from '@/components/Skeleton/Conversation/ReadOnly';
+import UserAvatar from '@/components/UserAvatar';
+import { ChatList, ConversationProvider } from '@/features/Conversation';
+import MessageItem from '@/features/Conversation/Messages';
+import NavHeader from '@/features/NavHeader';
+
+import { useShareVisitorTopic } from './useShareVisitorTopics';
+
+/** Counts and amounts are compared across topics, so digits keep the same width. */
+const NUMBER_STYLE = { fontVariantNumeric: 'tabular-nums' } as const;
+
+const renderMessage = (index: number, id: string) => (
+ <MessageItem disableEditing id={id} index={index} key={id} />
+);
+
+/**
+ * A visitor's run topic, opened read-only by the shared Agent's owner. The transcript is someone
+ * else's conversation read through the share's grant: it is held, never synced, and renders the
+ * way a shared topic does, with no composer and no message actions, so nothing the owner does here
+ * writes into the visitor's context.
+ */
+const ShareVisitorTopicView = () => {
+ const { t } = useTranslation('topic');
+ const { aid, topicId } = useParams<{ aid: string; topicId: string }>();
+ const { data, isLoading } = useShareVisitorTopic(topicId);
+ const context = useMemo<ConversationContext>(
+ () => ({
+ agentId: aid ?? '',
+ topicId: `share-visitor:${topicId}`,
+ topicShareId: `share-visitor:${topicId}`,
+ }),
+ [aid, topicId],
+ );
+
+ if (isLoading && !data) return <ReadOnlyConversationSkeleton />;
+ // Not found, or no longer readable: the share stopped allowing it, or the topic was deleted.
+ if (!data) {
+ return (
+ <Center flex={1}>
+ <Text type={'secondary'}>{t('shareVisitorTopics.unavailable')}</Text>
+ </Center>
+ );
+ }
+
+ const { messages, topic } = data;
+ const name = topic.visitor.name || t('management.shareVisitors.unnamedVisitor');
+
+ return (
+ <Flexbox flex={1} height={'100%'} style={{ minHeight: 0, overflow: 'hidden' }}>
+ <NavHeader
+ left={
+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
+ <UserAvatar
+ avatar={topic.visitor.avatar}
+ name={name}
+ shape={'circle'}
+ size={20}
+ style={{ flex: 'none' }}
+ />
+ <Text ellipsis fontSize={14} weight={500}>
+ {name}
+ </Text>
+ <Text ellipsis fontSize={14} type={'secondary'}>
+ {topic.title || topic.preview || t('shareVisitorTopics.untitled')}
+ </Text>
+ </Flexbox>
+ }
+ right={
+ <Flexbox horizontal align={'center'} gap={12} style={NUMBER_STYLE}>
+ {topic.totalTokens > 0 && (
+ <Flexbox horizontal align={'center'} gap={3} title={`${topic.totalTokens} tokens`}>
+ <Icon icon={Zap} size={12} />
+ <Text fontSize={12} type={'secondary'}>
+ {formatTokenNumber(topic.totalTokens)}
+ </Text>
+ </Flexbox>
+ )}
+ {topic.totalCost > 0 && (
+ <Flexbox horizontal align={'center'} gap={3} title={`$${topic.totalCost.toFixed(4)}`}>
+ <Icon icon={CircleDollarSign} size={12} />
+ <Text fontSize={12} type={'secondary'}>
+ {formatPrice(topic.totalCost, 2)}
+ </Text>
+ </Flexbox>
+ )}
+ <Tag title={t('shareVisitorTopics.readOnlyHint')}>
+ {t('shareVisitorTopics.readOnly')}
+ </Tag>
+ </Flexbox>
+ }
+ />
+ <ConversationProvider context={context} messages={messages}>
+ <Flexbox flex={1} style={{ minHeight: 0, overflow: 'hidden' }}>
+ <ChatList disableActionsBar itemContent={renderMessage} />
+ </Flexbox>
+ </ConversationProvider>
+ </Flexbox>
+ );
+};
+
+export default ShareVisitorTopicView;
diff --git a/src/features/ShareVisitorTopics/useShareVisitorTopics.ts b/src/features/ShareVisitorTopics/useShareVisitorTopics.ts
new file mode 100644
index 00000000000..0faef087004
--- /dev/null
+++ b/src/features/ShareVisitorTopics/useShareVisitorTopics.ts
@@ -0,0 +1,33 @@
+import type { ShareVisitorTopicGroup } from '@lobechat/types';
+
+import { useChannelsEnabled } from '@/features/Channels/useChannelsEnabled';
+import { useClientDataSWR } from '@/libs/swr';
+import { channelService } from '@/services/channel';
+import { CHANNEL_IDLE_REFRESH_MS } from '@/store/channel/action';
+
+const EMPTY: ShareVisitorTopicGroup[] = [];
+
+/**
+ * Visitors' run topics with the Agent's share, by visitor. Empty unless the share lets its owner
+ * read visitor conversations. Visitors keep talking without notifying the owner, so the list
+ * refreshes like the idle Channel list.
+ */
+export const useShareVisitorTopics = (agentId: string | undefined) => {
+ const enabled = useChannelsEnabled();
+ const { data } = useClientDataSWR(
+ enabled && agentId ? ['shareVisitorTopics', agentId] : null,
+ () => channelService.shareVisitorTopics(agentId!),
+ // Most Agents are never shared: read once on open, and keep polling only while there are
+ // visitors to follow.
+ { refreshInterval: (latest) => (latest?.length ? CHANNEL_IDLE_REFRESH_MS : 0) },
+ );
+ return data ?? EMPTY;
+};
+
+/** A visitor's run topic with its transcript. A visitor may still be talking, so it refreshes. */
+export const useShareVisitorTopic = (topicId: string | undefined) =>
+ useClientDataSWR(
+ topicId ? ['shareVisitorTopic', topicId] : null,
+ () => channelService.shareVisitorTopic(topicId!),
+ { refreshInterval: CHANNEL_IDLE_REFRESH_MS },
+ );
diff --git a/src/routes/(main)/agent/features/routeMeta.ts b/src/routes/(main)/agent/features/routeMeta.ts
index b2a5c75fb6f..0d006afc726 100644
--- a/src/routes/(main)/agent/features/routeMeta.ts
+++ b/src/routes/(main)/agent/features/routeMeta.ts
@@ -28,6 +28,7 @@ import AgentShareSkeleton from '@/components/Skeleton/AgentShare';
import AgentStatisticsSkeleton from '@/components/Skeleton/AgentStatistics';
import AgentConversationLayoutSkeleton from '@/components/Skeleton/Conversation/AgentLayout';
import ConversationLayoutSkeleton from '@/components/Skeleton/Conversation/Layout';
+import ReadOnlyConversationSkeleton from '@/components/Skeleton/Conversation/ReadOnly';
import ProfileSkeleton from '@/components/Skeleton/Profile';
import { createSurfaceSkeleton } from '@/components/Skeleton/Surface';
import TopicsSkeleton from '@/components/Skeleton/Topics';
@@ -146,6 +147,16 @@ export const agentChatDesktopRouteMeta = routeMeta({
Skeleton: AgentConversationLayoutSkeleton,
});
+/** A share visitor's run topic, read-only beside the Agent sidebar. */
+export const agentShareVisitorTopicRouteMeta = routeMeta({
+ // Titled like the Topics page (`Topics · <agent>`): the visitor transcript is fetched by the
+ // page, and a background tab should not poll it just to name itself.
+ DynamicMeta: TopicsDynamicMeta,
+ icon: MessagesSquareIcon,
+ Skeleton: ReadOnlyConversationSkeleton,
+ titleKey: 'navigation.topics',
+});
+
export const topicsRouteMeta = routeMeta({
DynamicMeta: TopicsDynamicMeta,
icon: MessagesSquareIcon,
diff --git a/src/routes/(main)/agent/visitor/[topicId]/index.tsx b/src/routes/(main)/agent/visitor/[topicId]/index.tsx
new file mode 100644
index 00000000000..fc4a05f81f7
--- /dev/null
+++ b/src/routes/(main)/agent/visitor/[topicId]/index.tsx
@@ -0,0 +1,7 @@
+'use client';
+
+import ShareVisitorTopicView from '@/features/ShareVisitorTopics/TopicView';
+
+const ShareVisitorTopicPage = () => <ShareVisitorTopicView />;
+
+export default ShareVisitorTopicPage;
diff --git a/src/services/channel.ts b/src/services/channel.ts
index 3418305c29e..60b39adea70 100644
--- a/src/services/channel.ts
+++ b/src/services/channel.ts
@@ -4,6 +4,7 @@ import type {
ChannelListItem,
ChannelVisibility,
ShareVisitorConversation,
+ ShareVisitorTopicGroup,
} from '@lobechat/types';
import { lambdaClient } from '@/libs/trpc/client';
@@ -91,6 +92,12 @@ class ChannelService {
/** Visitors' conversations with the caller's shared Agent, when its share lets the owner read them. */
shareVisitors = async (agentId: string): Promise<ShareVisitorConversation[]> =>
(await lambdaClient.channel.shareVisitors.query({ agentId })).data;
+ /** The run topics of those conversations, grouped by visitor. */
+ shareVisitorTopics = async (agentId: string): Promise<ShareVisitorTopicGroup[]> =>
+ (await lambdaClient.channel.shareVisitorTopics.query({ agentId })).data;
+ /** A visitor's run topic with its transcript, read-only for the Agent's owner. */
+ shareVisitorTopic = async (topicId: string) =>
+ (await lambdaClient.channel.shareVisitorTopic.query({ topicId })).data;
detail = async (params: ChannelViewParams): Promise<ChannelDetail> =>
(await lambdaClient.channel.detail.query(params)).data;
list = async (): Promise<ChannelListItem[]> => (await lambdaClient.channel.list.query()).data;
diff --git a/src/spa/router/agentPageRoutes.tsx b/src/spa/router/agentPageRoutes.tsx
index 489f4666215..e0c5b0d1b8d 100644
--- a/src/spa/router/agentPageRoutes.tsx
+++ b/src/spa/router/agentPageRoutes.tsx
@@ -18,6 +18,7 @@ import {
agentProfileRouteMeta,
agentSelfLearningRouteMeta,
agentShareRouteMeta,
+ agentShareVisitorTopicRouteMeta,
agentSkillsRouteMeta,
agentStatisticsRouteMeta,
agentTasksRouteMeta,
@@ -189,6 +190,14 @@ export const agentPageChildren: RouteObject[] = [
loader: agentUsageLoader,
path: 'statistics',
},
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/visitor/[topicId]'),
+ 'Desktop > Chat > Share Visitor Topic',
+ ),
+ handle: { meta: agentShareVisitorTopicRouteMeta },
+ path: 'visitor/:topicId',
+ },
{
element: dynamicElement(() => import('@/routes/(main)/agent/share'), 'Desktop > Chat > Share'),
handle: { meta: agentShareRouteMeta },