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): let creators read visitor conversations (#23472)

YuTengjing90f44fac5b8b
diff --git a/apps/server/src/routers/lambda/channel.ts b/apps/server/src/routers/lambda/channel.ts
index a565c88c839..bd524ce87f3 100644
--- a/apps/server/src/routers/lambda/channel.ts
+++ b/apps/server/src/routers/lambda/channel.ts
@@ -244,6 +244,16 @@ export const channelRouter = router({
data: await ctx.channelService.detail(input.channelId, input),
success: true,
})),
+ /**
+ * Visitors' conversations with the caller's shared Agent, for its owner to read; empty unless
+ * the share lets the owner read visitor conversations.
+ */
+ shareVisitors: channelProcedure
+ .input(z.object({ agentId: z.string().min(1) }))
+ .query(async ({ ctx, input }) => ({
+ data: await ctx.channelService.shareVisitors(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.shareVisitor.test.ts b/apps/server/src/services/channel/ChannelService.shareVisitor.test.ts
new file mode 100644
index 00000000000..7eba0e41139
--- /dev/null
+++ b/apps/server/src/services/channel/ChannelService.shareVisitor.test.ts
@@ -0,0 +1,66 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ChannelError } from '@/database/repositories/channel';
+
+import { ChannelService } from './ChannelService';
+
+const { detail, readShareVisitorChannel } = vi.hoisted(() => ({
+ detail: vi.fn(),
+ readShareVisitorChannel: vi.fn(),
+}));
+vi.mock('@/database/repositories/channel', async (original) => ({
+ ...(await original<object>()),
+ ChannelRepository: class {
+ detail = detail;
+ },
+}));
+vi.mock('@/database/repositories/channel/shareVisitors', () => ({
+ listShareVisitorConversations: vi.fn(),
+ readShareVisitorChannel,
+}));
+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 {} }));
+vi.mock('./ChannelCoordinator', () => ({ ChannelCoordinator: class {} }));
+vi.mock('./notify', () => ({ notifyChannel: vi.fn() }));
+vi.mock('./queue', () => ({ wakeChannel: vi.fn() }));
+
+describe('reading a visitor’s conversation with a shared Agent', () => {
+ beforeEach(() => {
+ vi.resetAllMocks();
+ });
+ const service = () => new ChannelService({} as never, 'owner', null);
+ const notFound = new ChannelError('NOT_FOUND', 'Channel not found');
+
+ it('opens it read-only for the creator when the caller is not a member', async () => {
+ detail.mockRejectedValue(notFound);
+ readShareVisitorChannel.mockResolvedValue({ attachments: [], readOnly: true });
+
+ await expect(service().detail('chn_visitor', undefined)).resolves.toMatchObject({
+ readOnly: true,
+ });
+ expect(readShareVisitorChannel).toHaveBeenCalledWith(
+ expect.anything(),
+ 'owner',
+ 'chn_visitor',
+ undefined,
+ );
+ });
+
+ it('keeps the original not-found error when the share does not let the caller read it', async () => {
+ detail.mockRejectedValue(notFound);
+ readShareVisitorChannel.mockResolvedValue(undefined);
+
+ await expect(service().detail('chn_visitor', undefined)).rejects.toBe(notFound);
+ });
+
+ it('never falls back for other errors', async () => {
+ const forbidden = new ChannelError('FORBIDDEN', 'No access');
+ detail.mockRejectedValue(forbidden);
+
+ await expect(service().detail('chn_visitor', undefined)).rejects.toBe(forbidden);
+ expect(readShareVisitorChannel).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/channel/ChannelService.ts b/apps/server/src/services/channel/ChannelService.ts
index 130644ba639..d960b52d139 100644
--- a/apps/server/src/services/channel/ChannelService.ts
+++ b/apps/server/src/services/channel/ChannelService.ts
@@ -24,6 +24,10 @@ import type {
} from '@/database/repositories/channel';
import { ChannelError, ChannelRepository } from '@/database/repositories/channel';
import { findProjectMainChannelId } from '@/database/repositories/channel/projectMainChannel';
+import {
+ listShareVisitorConversations,
+ readShareVisitorChannel,
+} from '@/database/repositories/channel/shareVisitors';
import { users } from '@/database/schemas';
import { AgentService } from '@/server/services/agent';
import { deviceGateway } from '@/server/services/deviceGateway';
@@ -455,8 +459,29 @@ export class ChannelService {
changed = (channelId: string) => notifyChannel(this.db, channelId);
+ /** 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);
+
+ /**
+ * 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.
+ */
+ private readView = async (
+ channelId: string,
+ options: Parameters<ChannelRepository['detail']>[1],
+ ) => {
+ try {
+ return await this.repository.detail(channelId, options);
+ } catch (error) {
+ if (!(error instanceof ChannelError) || error.code !== 'NOT_FOUND') throw error;
+ const visitorView = await readShareVisitorChannel(this.db, this.userId, channelId, options);
+ if (!visitorView) throw error;
+ return visitorView;
+ }
+ };
+
detail = async (channelId: string, options: Parameters<ChannelRepository['detail']>[1]) => {
- const view = await this.repository.detail(channelId, options);
+ const view = await this.readView(channelId, options);
const files = new FileService(this.db, this.userId, this.workspaceId);
// The public message's attachment relation grants this read after membership authorization.
// Do not return private storage keys or route through an unrelated ordinary-chat ACL.
diff --git a/locales/en-US/agent.json b/locales/en-US/agent.json
index b173b9e26dc..3a79c8da906 100644
--- a/locales/en-US/agent.json
+++ b/locales/en-US/agent.json
@@ -733,8 +733,8 @@
"share.settings.notice.title": "You pay for visitor usage.",
"share.settings.notice.workspaceDesc": "Visitors don’t just read this Agent — they run it. Every reply is generated in the Workspace and charged to its shared budget, without consuming the creator’s or another member’s quota. The Agent only acts with the visitor access you grant below.",
"share.settings.notice.workspaceTitle": "Visitors run this Agent on the Workspace budget",
- "share.settings.permissions.allowCreatorViewSessions": "Let me read visitor topics",
- "share.settings.permissions.allowCreatorViewSessionsHint": "Off by default: visitor topics stay private to the visitor.",
+ "share.settings.permissions.allowCreatorViewSessions": "Let me read visitor conversations",
+ "share.settings.permissions.allowCreatorViewSessionsHint": "Off by default: visitor conversations stay private to the visitor. When on, they appear under Share on this agent's Topics page.",
"share.settings.permissions.allowReadMemory": "Allow reading my memory",
"share.settings.permissions.allowReadMemoryHint": "The Agent may draw on your long-term memory while answering a visitor.",
"share.settings.permissions.desc": "What a visitor’s run may read, and what the visitor gets to see back.",
diff --git a/locales/en-US/channel.json b/locales/en-US/channel.json
index 56d6390e823..2e7dec55694 100644
--- a/locales/en-US/channel.json
+++ b/locales/en-US/channel.json
@@ -260,6 +260,7 @@
"settings.visibility.privateHint": "Only invited members can see this channel. Turn it on to let everyone in the workspace find and join it.",
"settings.visibility.publicHint": "Everyone in the workspace can find and join this channel.",
"settings.visibility.title": "Public channel",
+ "shareVisitorReadOnlyNotice": "A visitor's conversation through your share link. You can read it but can't reply.",
"sort.by": "Sort by",
"sort.by.createdAt": "Date created",
"sort.by.title": "Name",
diff --git a/locales/en-US/topic.json b/locales/en-US/topic.json
index bc6bd33fc24..eb61dc8ad25 100644
--- a/locales/en-US/topic.json
+++ b/locales/en-US/topic.json
@@ -217,6 +217,7 @@
"management.filters.trigger.chat": "Chat",
"management.filters.trigger.eval": "Eval",
"management.filters.trigger.label": "Trigger",
+ "management.filters.trigger.share": "Share",
"management.filters.trigger.task": "Task",
"management.filters.trigger.webhook": "Webhook",
"management.group.byProject": "By project",
@@ -237,6 +238,9 @@
"management.moveModal.moving": "Moving…",
"management.moveModal.title": "Move topics",
"management.searchPlaceholder": "Search this agent's topics…",
+ "management.shareVisitors.desc": "Visitors who chat with this agent through its share link. Open one to read the conversation.",
+ "management.shareVisitors.title": "Shared with visitors",
+ "management.shareVisitors.unnamedVisitor": "Visitor",
"management.sidebarEntry": "Topics",
"management.sort.createdAt": "Created time",
"management.sort.label": "Sort",
diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.json
index 5272a40a870..93c615ad2b6 100644
--- a/locales/zh-CN/agent.json
+++ b/locales/zh-CN/agent.json
@@ -733,8 +733,8 @@
"share.settings.notice.title": "访客使用产生的费用由你承担。",
"share.settings.notice.workspaceDesc": "访客不只是查看这个助手,而是真的在运行它。每一次回复都在工作区内生成并从工作区共享预算扣费,不占用创建者或其他成员的个人额度。助手只会使用你在下面授予访客的权限。",
"share.settings.notice.workspaceTitle": "访客将使用工作区预算运行此助手",
- "share.settings.permissions.allowCreatorViewSessions": "允许我查看访客话题",
- "share.settings.permissions.allowCreatorViewSessionsHint": "默认关闭:访客的话题内容只有访客自己能看到。",
+ "share.settings.permissions.allowCreatorViewSessions": "允许我查看访客对话",
+ "share.settings.permissions.allowCreatorViewSessionsHint": "默认关闭:访客的对话只有访客自己能看到。开启后,可在该助手「话题」页的「分享」来源中查看。",
"share.settings.permissions.allowReadMemory": "允许读取我的记忆",
"share.settings.permissions.allowReadMemoryHint": "助手在回答访客时可以参考你的长期记忆。",
"share.settings.permissions.desc": "访客的运行可以读取什么,以及访客能看到什么。",
diff --git a/locales/zh-CN/channel.json b/locales/zh-CN/channel.json
index f1de0445e21..fd8ce6b65fa 100644
--- a/locales/zh-CN/channel.json
+++ b/locales/zh-CN/channel.json
@@ -260,6 +260,7 @@
"settings.visibility.privateHint": "只有被邀请的成员能看到这个频道。开启后,工作区里的所有人都可以找到并加入。",
"settings.visibility.publicHint": "工作区里的所有人都可以找到并加入这个频道。",
"settings.visibility.title": "公开频道",
+ "shareVisitorReadOnlyNotice": "这是访客通过你的分享链接发起的对话,你只能查看,不能回复。",
"sort.by": "排序方式",
"sort.by.createdAt": "创建时间",
"sort.by.title": "名称",
diff --git a/locales/zh-CN/topic.json b/locales/zh-CN/topic.json
index b8a12d8494f..9a2a059d355 100644
--- a/locales/zh-CN/topic.json
+++ b/locales/zh-CN/topic.json
@@ -217,6 +217,7 @@
"management.filters.trigger.chat": "对话",
"management.filters.trigger.eval": "评测",
"management.filters.trigger.label": "来源",
+ "management.filters.trigger.share": "分享",
"management.filters.trigger.task": "任务",
"management.filters.trigger.webhook": "Webhook",
"management.group.byProject": "按项目",
@@ -237,6 +238,9 @@
"management.moveModal.moving": "正在移动…",
"management.moveModal.title": "移动话题",
"management.searchPlaceholder": "在当前助手的话题中搜索…",
+ "management.shareVisitors.desc": "通过分享链接和这个助手对话的访客,打开即可查看对话。",
+ "management.shareVisitors.title": "分享访客",
+ "management.shareVisitors.unnamedVisitor": "访客",
"management.sidebarEntry": "话题",
"management.sort.createdAt": "按创建时间",
"management.sort.label": "排序",
diff --git a/packages/database/src/models/__tests__/topics/topic.query.test.ts b/packages/database/src/models/__tests__/topics/topic.query.test.ts
index 1c841a89804..3ec0701dc61 100644
--- a/packages/database/src/models/__tests__/topics/topic.query.test.ts
+++ b/packages/database/src/models/__tests__/topics/topic.query.test.ts
@@ -1097,7 +1097,7 @@ describe('TopicModel - Query', () => {
'a short description',
'cron',
);
-
+ await serverDB.update(topics).set({ totalCost: 0.25, totalTokens: 300 });
const result = await topicModel.query({
agentId: 'agt-detailed-topic',
withDetails: true,
@@ -1110,10 +1110,9 @@ describe('TopicModel - Query', () => {
expect(item.messageCount).toBe(4);
expect(item.description).toBe('a short description');
expect(item.trigger).toBe('cron');
- // cost / tokenUsage are not yet returned — waiting on a schema
- // migration to add real columns before they come back.
- expect(item).not.toHaveProperty('cost');
- expect(item).not.toHaveProperty('tokenUsage');
+ // Spend totals are the topic's own rolled-up usage columns.
+ expect(item.cost).toBe(0.25);
+ expect(item.tokenUsage).toBe(300);
});
it('returns null firstUserMessage when no user message exists', async () => {
diff --git a/packages/database/src/models/topic/list.ts b/packages/database/src/models/topic/list.ts
index 9f072e64ede..53e024ffa85 100644
--- a/packages/database/src/models/topic/list.ts
+++ b/packages/database/src/models/topic/list.ts
@@ -101,9 +101,8 @@ export const query = async (
// Heavier columns gated behind `withDetails` and used by the per-agent
// Topics management page: real aggregates from the `messages` table
// (firstUserMessage + messageCount), plus the `description` / `trigger`
- // columns that sidebar paths don't consume. `cost` and `tokenUsage`
- // intentionally stay undefined here — they need their own schema
- // migration before they can be backed by real numbers.
+ // columns that sidebar paths don't consume, and the topic's `cost` /
+ // `tokenUsage` totals.
//
// The two correlated subqueries are built with Drizzle's query builder
// (not a raw `sql` template) so the inner `eq(messages.topicId,
@@ -139,11 +138,14 @@ export const query = async (
const detailColumns = withDetails
? {
+ // Rolled up on the topic by `recomputeTopicUsage` as messages and runs settle.
+ cost: topics.totalCost,
description: topics.description,
firstUserMessage: sql<string | null>`(${firstUserMessageSubquery})`.as(
'first_user_message',
),
messageCount: sql<number>`(${messageCountSubquery})`.as('message_count'),
+ tokenUsage: topics.totalTokens,
trigger: topics.trigger,
}
: {};
diff --git a/packages/database/src/models/topic/types.ts b/packages/database/src/models/topic/types.ts
index aa2cf491688..d4859dfac31 100644
--- a/packages/database/src/models/topic/types.ts
+++ b/packages/database/src/models/topic/types.ts
@@ -101,9 +101,9 @@ export interface CreateTopicParams {
* `queryTopics`, `queryRecent` and `rank`) while the share surface scopes
* reads per visitor (`queryBySender` / `countMessagesBySender`).
*
- * A future opt-in surface (`allowCreatorViewSessions`) may let a creator
- * explicitly browse visitor sessions; that is not wired up yet — every
- * creator-facing read today unconditionally excludes senderId rows.
+ * Topic reads always exclude senderId rows. When a share enables
+ * `allowCreatorViewSessions`, the creator reads the visitor's Channel instead
+ * (`repositories/channel/shareVisitors.ts`), never these run topics.
*/
senderId?: string | null;
sessionId?: string | null;
@@ -183,9 +183,8 @@ export interface QueryTopicParams {
/**
* When true, the SELECT also returns the heavier card-detail columns used
* by the per-agent Topics management page: `firstUserMessage` (subquery),
- * `messageCount` (subquery), `description`, `trigger`. `cost` and
- * `tokenUsage` are intentionally omitted until a dedicated schema migration
- * adds real columns to back them. Defaults to false so sidebar paths stay
+ * `messageCount` (subquery), `description`, `trigger`, and the topic's
+ * `cost` / `tokenUsage` totals. Defaults to false so sidebar paths stay
* cheap.
*/
withDetails?: boolean;
diff --git a/packages/database/src/repositories/channel/__tests__/shareVisitors.test.ts b/packages/database/src/repositories/channel/__tests__/shareVisitors.test.ts
new file mode 100644
index 00000000000..63788160af4
--- /dev/null
+++ b/packages/database/src/repositories/channel/__tests__/shareVisitors.test.ts
@@ -0,0 +1,136 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+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 { createChannelFixture, jobsOf, lease } from './testUtils';
+
+const db = await getTestDB();
+const fixture = createChannelFixture(db, 'channel-share-visitors');
+const execution = new ChannelExecutionRepository(db);
+
+// The fixture's member is the visitor; its owner shares an Agent.
+const visitorId = fixture.memberId;
+const ownerId = fixture.ownerId;
+const agentId = 'agt_channel_share_visitors';
+const visitor = new ChannelRepository(db, visitorId);
+
+let shareId: string;
+
+const setCreatorView = (allowCreatorViewSessions: boolean) =>
+ db
+ .update(agentShares)
+ .set({ shareConfig: { allowCreatorViewSessions, slug: 'visitor-helper' } })
+ .where(eq(agentShares.id, shareId));
+
+/** A visitor's direct conversation with one claimed run, whose topic cost `cost`. */
+const openConversation = async (cost: number, tokens: number) => {
+ const { channel } = await visitor.create({ agentId, sharedAgent: true, title: 'Helper' });
+ const message = await visitor.send(channel.id, {
+ content: 'Hello helper',
+ requestKey: 'first',
+ routing: 'fallback',
+ });
+ const [job] = await jobsOf(db, message.id);
+ const claim = (await execution.claim(channel.id, job.id, lease))!;
+ await db
+ .update(topics)
+ .set({ totalCost: cost, totalTokens: tokens })
+ .where(eq(topics.id, claim.topic.id));
+ return { channel, topicId: claim.topic.id };
+};
+
+beforeEach(async () => {
+ await fixture.setup();
+ await db.update(users).set({ fullName: 'Visitor Vee' }).where(eq(users.id, visitorId));
+ await db.insert(agents).values({
+ id: agentId,
+ model: 'owner-model',
+ provider: 'owner-provider',
+ title: 'Helper',
+ userId: ownerId,
+ });
+ const [share] = await db
+ .insert(agentShares)
+ .values({ agentId, shareConfig: { slug: 'visitor-helper' }, visibility: 'link' })
+ .returning();
+ shareId = share.id;
+});
+
+afterEach(async () => {
+ await fixture.cleanup();
+});
+
+describe('share visitor conversations', () => {
+ it('stay hidden from the creator until the share lets them read them', async () => {
+ const { channel } = await openConversation(0.5, 1200);
+
+ expect(await listShareVisitorConversations(db, ownerId, agentId)).toEqual([]);
+ expect(await readShareVisitorChannel(db, ownerId, channel.id)).toBeUndefined();
+ });
+
+ it('list one entry per visitor with the cost and tokens of its runs', async () => {
+ await setCreatorView(true);
+ const { channel } = await openConversation(0.25, 1500);
+
+ const [listed, ...rest] = await listShareVisitorConversations(db, ownerId, agentId);
+ expect(rest).toEqual([]);
+ expect(listed).toMatchObject({
+ id: channel.id,
+ lastMessage: expect.objectContaining({ content: 'Hello helper' }),
+ totalCost: 0.25,
+ totalTokens: 1500,
+ visitor: { id: visitorId, name: 'Visitor Vee' },
+ });
+ });
+
+ it('are listed and read only by the Agent owner', async () => {
+ await setCreatorView(true);
+ const { channel } = await openConversation(0.25, 1500);
+
+ expect(await listShareVisitorConversations(db, visitorId, agentId)).toEqual([]);
+ expect(await readShareVisitorChannel(db, visitorId, channel.id)).toBeUndefined();
+ });
+
+ it('open read-only for the creator, without links to the private run topics', async () => {
+ await setCreatorView(true);
+ const { channel } = await openConversation(0.25, 1500);
+
+ const view = (await readShareVisitorChannel(db, ownerId, channel.id))!;
+ expect(view).toMatchObject({
+ channel: { canDelete: false, id: channel.id, title: 'Visitor Vee' },
+ joined: false,
+ readOnly: true,
+ });
+ expect(view.messages.map((message) => message.content)).toContain('Hello helper');
+ expect(view.messages.every((message) => message.sourceTopicId === null)).toBe(true);
+ expect(view.jobs.length).toBeGreaterThan(0);
+ expect(view.jobs.every((job) => !('topicId' in job))).toBe(true);
+ });
+
+ it('keep a Workspace member’s own conversation private, even after the Agent turns 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(claim.job.executionConfig?.share).toBeUndefined();
+
+ // Making the Agent private does not turn the member's earlier conversation into a share visit.
+ await db.update(agents).set({ visibility: 'private' }).where(eq(agents.id, agentId));
+ expect(await listShareVisitorConversations(db, ownerId, agentId)).toEqual([]);
+ expect(await readShareVisitorChannel(db, ownerId, channel.id)).toBeUndefined();
+ });
+});
diff --git a/packages/database/src/repositories/channel/shareVisitors.ts b/packages/database/src/repositories/channel/shareVisitors.ts
new file mode 100644
index 00000000000..8d68c85f417
--- /dev/null
+++ b/packages/database/src/repositories/channel/shareVisitors.ts
@@ -0,0 +1,139 @@
+import type { ShareVisitorConversation } from '@lobechat/types';
+import { and, desc, eq, inArray, isNotNull, ne, sql } from 'drizzle-orm';
+
+import { agents, agentShares, channelJobs, channels, topics, users } from '../../schemas';
+import type { LobeChatDatabase, Transaction } from '../../type';
+import { notTrashed } from '../../utils/softDelete';
+import { channelLastMessages } from './lastMessage';
+import { readChannelView, viewerJobs } from './view';
+
+/** Visitor conversations one list returns; the Topics page shows them all at once. */
+const SHARE_VISITOR_LIST_LIMIT = 200;
+
+/**
+ * Direct Channels visitors opened with `ownerId`'s shared Agent, while its share lets the creator
+ * read them (`allowCreatorViewSessions`). Each visitor has one such Channel per scope.
+ *
+ * Admission follows each run's frozen share provenance (`executionConfig.share`, set at claim), not
+ * the Agent's current visibility: a Workspace member's own conversation with a Workspace-visible
+ * Agent runs as that member and must stay private even after the Agent is made private. A Channel
+ * qualifies once a run went through the share and no claimed run ran outside it; unclaimed jobs
+ * carry no config yet and do not count.
+ */
+const shareVisitorChannelWhere = (ownerId: string) =>
+ and(
+ eq(agents.userId, ownerId),
+ isNotNull(channels.userId),
+ ne(channels.userId, ownerId),
+ notTrashed(channels.isDeleted),
+ sql`${agentShares.shareConfig}->>'allowCreatorViewSessions' = 'true'`,
+ sql`EXISTS (SELECT 1 FROM ${channelJobs} WHERE ${channelJobs.channelId} = ${channels.id} AND jsonb_typeof(${channelJobs.executionConfig}->'share') = 'object')`,
+ sql`NOT EXISTS (SELECT 1 FROM ${channelJobs} WHERE ${channelJobs.channelId} = ${channels.id} AND ${channelJobs.executionConfig} IS NOT NULL AND coalesce(jsonb_typeof(${channelJobs.executionConfig}->'share'), 'null') <> 'object')`,
+ );
+
+const shareVisitorChannels = (db: LobeChatDatabase | Transaction) =>
+ db
+ .select({
+ channel: channels,
+ visitorAvatar: users.avatar,
+ visitorName: users.fullName,
+ visitorUsername: users.username,
+ })
+ .from(channels)
+ .innerJoin(agents, eq(agents.id, channels.agentId))
+ .innerJoin(agentShares, eq(agentShares.agentId, agents.id))
+ .leftJoin(users, eq(users.id, channels.userId));
+
+/**
+ * Tokens and cost of the runs behind each Channel: every job's private run topic, counted once.
+ * The run topics belong to the share's owner, who is the only reader of these totals.
+ */
+const runUsageByChannel = async (db: LobeChatDatabase, channelIds: string[]) => {
+ if (!channelIds.length) return new Map<string, { totalCost: number; totalTokens: number }>();
+ const runTopics = db
+ .selectDistinct({ channelId: channelJobs.channelId, topicId: channelJobs.topicId })
+ .from(channelJobs)
+ .where(and(inArray(channelJobs.channelId, channelIds), isNotNull(channelJobs.topicId)))
+ .as('run_topics');
+ const rows = await db
+ .select({
+ channelId: runTopics.channelId,
+ totalCost: sql<number>`coalesce(sum(${topics.totalCost}), 0)`.mapWith(Number),
+ totalTokens: sql<number>`coalesce(sum(${topics.totalTokens}), 0)`.mapWith(Number),
+ })
+ .from(runTopics)
+ .innerJoin(topics, eq(topics.id, runTopics.topicId))
+ .groupBy(runTopics.channelId);
+ return new Map(rows.map(({ channelId, ...usage }) => [channelId, usage]));
+};
+
+/** The visitor conversations with `ownerId`'s Agent the owner may read, newest first. */
+export const listShareVisitorConversations = async (
+ db: LobeChatDatabase,
+ ownerId: string,
+ agentId: string,
+): Promise<ShareVisitorConversation[]> => {
+ const rows = await shareVisitorChannels(db)
+ .where(and(eq(channels.agentId, agentId), shareVisitorChannelWhere(ownerId)))
+ .orderBy(desc(channels.updatedAt))
+ .limit(SHARE_VISITOR_LIST_LIMIT);
+ const ids = rows.map(({ channel }) => channel.id);
+ const [lastMessages, usage] = await Promise.all([
+ channelLastMessages(db, ids),
+ runUsageByChannel(db, ids),
+ ]);
+
+ return rows.map(({ channel, visitorAvatar, visitorName, visitorUsername }) => ({
+ createdAt: channel.createdAt,
+ id: channel.id,
+ lastMessage: lastMessages.get(channel.id) ?? null,
+ totalCost: usage.get(channel.id)?.totalCost ?? 0,
+ totalTokens: usage.get(channel.id)?.totalTokens ?? 0,
+ updatedAt: channel.updatedAt,
+ visitor: {
+ avatar: visitorAvatar,
+ id: channel.userId!,
+ name: visitorName || 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
+ * "open topic" would lead nowhere. Undefined when `viewerId` may not read it.
+ */
+export const readShareVisitorChannel = (
+ db: LobeChatDatabase,
+ viewerId: string,
+ channelId: string,
+ options?: Parameters<typeof readChannelView>[2],
+) =>
+ db.transaction(async (tx) => {
+ const [found] = await shareVisitorChannels(tx)
+ .where(and(eq(channels.id, channelId), shareVisitorChannelWhere(viewerId)))
+ .limit(1);
+ if (!found) return;
+
+ const view = await readChannelView(tx, channelId, options, viewerId);
+ const withoutTopic = <
+ T extends { sourceTopicId: string | null; sourceTopicTitle: string | null },
+ >(
+ message: T,
+ ) => ({ ...message, sourceTopicId: null, sourceTopicTitle: null });
+ return {
+ channel: {
+ ...found.channel,
+ canDelete: false,
+ sharedAgent: true,
+ // Every visitor's Channel is titled after the Agent; to its owner, the visitor names it.
+ title: found.visitorName || found.visitorUsername || found.channel.title,
+ },
+ joined: false,
+ readOnly: true as const,
+ ...view,
+ jobs: viewerJobs(view.jobs, viewerId, () => false).map(({ topicId: _, ...job }) => job),
+ messages: view.messages.map(withoutTopic),
+ rootMessage: view.rootMessage && withoutTopic(view.rootMessage),
+ };
+ });
diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.ts
index 90508660936..904f657c914 100644
--- a/packages/locales/src/default/agent.ts
+++ b/packages/locales/src/default/agent.ts
@@ -952,9 +952,9 @@ export default {
'share.settings.notice.workspaceDesc':
'Visitors don’t just read this Agent — they run it. Every reply is generated in the Workspace and charged to its shared budget, without consuming the creator’s or another member’s quota. The Agent only acts with the visitor access you grant below.',
'share.settings.notice.workspaceTitle': 'Visitors run this Agent on the Workspace budget',
- 'share.settings.permissions.allowCreatorViewSessions': 'Let me read visitor topics',
+ 'share.settings.permissions.allowCreatorViewSessions': 'Let me read visitor conversations',
'share.settings.permissions.allowCreatorViewSessionsHint':
- 'Off by default: visitor topics stay private to the visitor.',
+ "Off by default: visitor conversations stay private to the visitor. When on, they appear under Share on this agent's Topics page.",
'share.settings.permissions.allowReadMemory': 'Allow reading my memory',
'share.settings.permissions.allowReadMemoryHint':
'The Agent may draw on your long-term memory while answering a visitor.',
diff --git a/packages/locales/src/default/channel.ts b/packages/locales/src/default/channel.ts
index 65b4b73c417..9a6cf6493a8 100644
--- a/packages/locales/src/default/channel.ts
+++ b/packages/locales/src/default/channel.ts
@@ -118,6 +118,8 @@ export default {
'actionFailed': 'Something went wrong. Try again.',
'send': 'Send',
'sendFailed': 'Message was not sent. Your draft is preserved; try again.',
+ 'shareVisitorReadOnlyNotice':
+ "A visitor's conversation through your share link. You can read it but can't reply.",
'outgoing.discard': 'Delete',
'outgoing.failed': 'Not sent',
'outgoing.retry': 'Retry',
diff --git a/packages/locales/src/default/topic.ts b/packages/locales/src/default/topic.ts
index abb6c7fdc27..929f683033f 100644
--- a/packages/locales/src/default/topic.ts
+++ b/packages/locales/src/default/topic.ts
@@ -275,6 +275,7 @@ export default {
'management.filters.trigger.chat': 'Chat',
'management.filters.trigger.eval': 'Eval',
'management.filters.trigger.label': 'Trigger',
+ 'management.filters.trigger.share': 'Share',
'management.filters.trigger.task': 'Task',
'management.filters.trigger.webhook': 'Webhook',
'management.group.byProject': 'By project',
@@ -295,6 +296,10 @@ export default {
'management.moveModal.moving': 'Moving…',
'management.moveModal.title': 'Move topics',
'management.searchPlaceholder': "Search this agent's topics…",
+ 'management.shareVisitors.desc':
+ 'Visitors who chat with this agent through its share link. Open one to read the conversation.',
+ 'management.shareVisitors.title': 'Shared with visitors',
+ 'management.shareVisitors.unnamedVisitor': 'Visitor',
'management.sidebarEntry': 'Topics',
'management.sort.createdAt': 'Created time',
'management.sort.label': 'Sort',
diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.ts
index 39f2bcb316c..529a058bb74 100644
--- a/packages/types/src/channel.ts
+++ b/packages/types/src/channel.ts
@@ -812,6 +812,27 @@ export interface ChannelDetail {
joined?: boolean;
members: ChannelPublicMember[];
messages: ChannelPublicMessage[];
+ /**
+ * True while a shared Agent's owner reads a visitor's conversation with it: the same view, with
+ * no composer and no message actions.
+ */
+ readOnly?: boolean;
rootMessage: ChannelPublicMessage | null;
threads: ChannelPublicThread[];
}
+
+/**
+ * A visitor's direct conversation with a shared Agent, as its owner lists them when the share
+ * lets the owner read visitor conversations.
+ */
+export interface ShareVisitorConversation {
+ createdAt: Date;
+ /** The visitor's Channel. */
+ id: string;
+ lastMessage: ChannelLastMessage | null;
+ /** USD cost of every run in the conversation, from its run topics. */
+ totalCost: number;
+ totalTokens: number;
+ updatedAt: Date;
+ visitor: { avatar: string | null; id: string; name: string | null };
+}
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.ts
index cbd6ea412a6..4226d56188d 100644
--- a/packages/types/src/topic/topic.ts
+++ b/packages/types/src/topic/topic.ts
@@ -812,7 +812,7 @@ export type ChatTopicStatus = z.infer<typeof chatTopicStatusSchema>;
export interface ChatTopic extends Omit<BaseDataModel, 'meta'> {
completedAt?: Date | null;
- /** Server-side mock until real cost aggregation lands. */
+ /** USD cost of the topic, rolled up from its messages and runs; set by detail queries. */
cost?: number | null;
description?: string | null;
favorite?: boolean;
@@ -860,7 +860,7 @@ export interface ChatTopic extends Omit<BaseDataModel, 'meta'> {
sortUpdatedAt?: number;
status?: ChatTopicStatus | null;
title: string;
- /** Server-side mock until real token aggregation lands. */
+ /** Tokens the topic used, rolled up with `cost`; set by detail queries. */
tokenUsage?: number | null;
trigger?: string | null;
userId?: string;
diff --git a/src/features/AgentTopicManager/ChannelSection.tsx b/src/features/AgentTopicManager/ChannelSection.tsx
index 9cfcfadf650..e6529b6cd8d 100644
--- a/src/features/AgentTopicManager/ChannelSection.tsx
+++ b/src/features/AgentTopicManager/ChannelSection.tsx
@@ -13,7 +13,7 @@ import { useTranslation } from 'react-i18next';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useActivityTime } from '@/hooks/useActivityTime';
-const styles = stylex.create({
+export const channelCardStyles = stylex.create({
// Same column rules as the topic grid, so Channel cards line up with the topics below them.
grid: {
display: 'grid',
@@ -61,7 +61,7 @@ const ChannelCard = memo<{ channel: ChannelListItem }>(({ channel }) => {
return (
<Block
- className={stylex.props(styles.card).className}
+ className={stylex.props(channelCardStyles.card).className}
gap={8}
role={'link'}
tabIndex={0}
@@ -72,8 +72,13 @@ const ChannelCard = memo<{ channel: ChannelListItem }>(({ channel }) => {
}}
>
<Flexbox horizontal align={'center'} gap={6}>
- <Icon className={stylex.props(styles.icon).className} icon={Hash} size={14} />
- <Text ellipsis className={stylex.props(styles.title).className} fontSize={14} weight={600}>
+ <Icon className={stylex.props(channelCardStyles.icon).className} icon={Hash} size={14} />
+ <Text
+ ellipsis
+ className={stylex.props(channelCardStyles.title).className}
+ fontSize={14}
+ weight={600}
+ >
{channel.title}
</Text>
{channel.status === 'archived' && (
@@ -81,11 +86,15 @@ const ChannelCard = memo<{ channel: ChannelListItem }>(({ channel }) => {
)}
</Flexbox>
{preview && (
- <Text className={stylex.props(styles.preview).className} fontSize={12} type={'secondary'}>
+ <Text
+ className={stylex.props(channelCardStyles.preview).className}
+ fontSize={12}
+ type={'secondary'}
+ >
{preview}
</Text>
)}
- <span title={activity.title} {...stylex.props(styles.footer)}>
+ <span title={activity.title} {...stylex.props(channelCardStyles.footer)}>
{activity.text}
</span>
</Block>
@@ -112,7 +121,7 @@ const ChannelSection = memo<{ channels: ChannelListItem[] }>(({ channels }) => {
{t('management.channels.desc')}
</Text>
</Flexbox>
- <div {...stylex.props(styles.grid)}>
+ <div {...stylex.props(channelCardStyles.grid)}>
{channels.map((channel) => (
<ChannelCard channel={channel} key={channel.id} />
))}
diff --git a/src/features/AgentTopicManager/ShareVisitorSection.tsx b/src/features/AgentTopicManager/ShareVisitorSection.tsx
new file mode 100644
index 00000000000..27929ddd807
--- /dev/null
+++ b/src/features/AgentTopicManager/ShareVisitorSection.tsx
@@ -0,0 +1,123 @@
+'use client';
+
+import { 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';
+import * as stylex from '@stylexjs/stylex';
+import { CircleDollarSign, Zap } from 'lucide-react';
+import { type KeyboardEvent, memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import UserAvatar from '@/components/UserAvatar';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useActivityTime } from '@/hooks/useActivityTime';
+
+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 }) => {
+ const { t } = useTranslation('topic');
+ const navigate = useWorkspaceAwareNavigate();
+ const activity = useActivityTime(conversation.updatedAt ?? conversation.createdAt);
+ const open = () => navigate(CHANNEL_URL(conversation.id));
+ const name = conversation.visitor.name || t('management.shareVisitors.unnamedVisitor');
+ const preview = conversation.lastMessage?.content?.trim();
+ const { totalCost, totalTokens } = conversation;
+
+ return (
+ <Block
+ className={stylex.props(styles.card).className}
+ gap={8}
+ role={'link'}
+ tabIndex={0}
+ variant={'outlined'}
+ onClick={open}
+ onKeyDown={(event: KeyboardEvent) => {
+ if (event.key === 'Enter') open();
+ }}
+ >
+ <Flexbox horizontal align={'center'} gap={8}>
+ <UserAvatar
+ avatar={conversation.visitor.avatar}
+ name={name}
+ shape={'circle'}
+ size={20}
+ style={{ flex: 'none' }}
+ />
+ <Text ellipsis className={stylex.props(styles.title).className} fontSize={14} weight={600}>
+ {name}
+ </Text>
+ </Flexbox>
+ {preview && (
+ <Text className={stylex.props(styles.preview).className} fontSize={12} type={'secondary'}>
+ {preview}
+ </Text>
+ )}
+ <Flexbox horizontal align={'center'} gap={12} {...stylex.props(styles.footer)}>
+ <span title={activity.title}>{activity.text}</span>
+ {totalTokens > 0 && (
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={3}
+ style={NUMBER_STYLE}
+ title={`${totalTokens} tokens`}
+ >
+ <Icon icon={Zap} size={11} />
+ {formatTokenNumber(totalTokens)}
+ </Flexbox>
+ )}
+ {totalCost > 0 && (
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={3}
+ style={NUMBER_STYLE}
+ title={`$${totalCost.toFixed(4)}`}
+ >
+ <Icon icon={CircleDollarSign} size={11} />
+ {formatPrice(totalCost, 2)}
+ </Flexbox>
+ )}
+ </Flexbox>
+ </Block>
+ );
+});
+
+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.
+ */
+const ShareVisitorSection = memo<{ conversations: ShareVisitorConversation[] }>(
+ ({ conversations }) => {
+ const { t } = useTranslation('topic');
+ if (conversations.length === 0) return null;
+
+ return (
+ <Flexbox gap={12}>
+ <Flexbox gap={2}>
+ <Text fontSize={13} type={'secondary'} weight={500}>
+ {t('management.shareVisitors.title')}
+ </Text>
+ <Text fontSize={12} type={'secondary'}>
+ {t('management.shareVisitors.desc')}
+ </Text>
+ </Flexbox>
+ <div {...stylex.props(styles.grid)}>
+ {conversations.map((conversation) => (
+ <ShareVisitorCard conversation={conversation} key={conversation.id} />
+ ))}
+ </div>
+ </Flexbox>
+ );
+ },
+);
+
+ShareVisitorSection.displayName = 'AgentTopicManagerShareVisitorSection';
+
+export default ShareVisitorSection;
diff --git a/src/features/AgentTopicManager/Toolbar.tsx b/src/features/AgentTopicManager/Toolbar.tsx
index 803642aa79c..3de83ab9b54 100644
--- a/src/features/AgentTopicManager/Toolbar.tsx
+++ b/src/features/AgentTopicManager/Toolbar.tsx
@@ -30,6 +30,7 @@ import {
MessageCircle,
MoreHorizontal,
Plus,
+ Share2,
TestTubeIcon,
Webhook,
X,
@@ -171,6 +172,7 @@ const STATUS_OPTIONS: { key: StatusFilter; labelKey: string }[] = [
const TRIGGER_OPTIONS: TriggerFilter[] = [
'chat',
'channel',
+ 'share',
'bot',
'webhook',
'api',
@@ -184,6 +186,7 @@ const TRIGGER_ICON: Record<TriggerFilter, LucideIcon> = {
channel: Hash,
chat: MessageCircle,
eval: TestTubeIcon,
+ share: Share2,
task: ListTodoIcon,
webhook: Webhook,
};
@@ -268,13 +271,16 @@ const Toolbar = memo<ToolbarProps>(({ projects, statusCounts, botChannelOptions
const channelsEnabled = useChannelsEnabled();
const triggerItems: DropdownItem[] = useMemo(
() =>
- TRIGGER_OPTIONS.filter((tr) => tr !== 'channel' || channelsEnabled).map((tr) => ({
- extra: <CheckMark visible={triggers.includes(tr)} />,
- icon: <Icon icon={TRIGGER_ICON[tr]} size={14} />,
- key: tr,
- label: t(`management.filters.trigger.${tr}` as any) as string,
- onClick: () => toggleTrigger(tr),
- })),
+ // Visitor conversations are Channels too, opened on the Channel page.
+ TRIGGER_OPTIONS.filter((tr) => (tr !== 'channel' && tr !== 'share') || channelsEnabled).map(
+ (tr) => ({
+ extra: <CheckMark visible={triggers.includes(tr)} />,
+ icon: <Icon icon={TRIGGER_ICON[tr]} size={14} />,
+ key: tr,
+ label: t(`management.filters.trigger.${tr}` as any) as string,
+ onClick: () => toggleTrigger(tr),
+ }),
+ ),
[channelsEnabled, triggers, t, toggleTrigger],
);
diff --git a/src/features/AgentTopicManager/index.tsx b/src/features/AgentTopicManager/index.tsx
index 4a2afde0cd9..410bc5b0769 100644
--- a/src/features/AgentTopicManager/index.tsx
+++ b/src/features/AgentTopicManager/index.tsx
@@ -23,11 +23,13 @@ import BulkActionBar from './BulkActionBar';
import ChannelSection from './ChannelSection';
import EmptyState from './EmptyState';
import Header from './Header';
+import ShareVisitorSection from './ShareVisitorSection';
import { useTopicsViewStore } from './store';
import Toolbar from './Toolbar';
import TopicGrid from './TopicGrid';
import TopicListView from './TopicListView';
import type { StatusFilter } from './types';
+import { useShareVisitors } from './useShareVisitors';
import {
agentGroupChannels,
buildBotChannelOptions,
@@ -37,10 +39,13 @@ import {
matchesChannelSearch,
matchesChannelStatus,
matchesGroup,
+ matchesShareVisitorSearch,
+ matchesShareVisitorStatus,
matchesStatus,
matchesTimeRange,
matchesTrigger,
sortChannelsBy,
+ sortShareVisitorsBy,
sortTopics,
} from './utils';
@@ -119,6 +124,10 @@ const AgentTopicManager = memo(() => {
const retryChannels = () => {
void channelActions.refreshList().catch(() => {});
};
+ const shareVisitors = useShareVisitors(
+ activeAgentId,
+ channelsEnabled && triggers.includes('share'),
+ );
const trimmedSearch = search.trim();
const { data: searchResults } = useSearchTopics(
@@ -172,10 +181,29 @@ const AgentTopicManager = memo(() => {
[channelPool, status, sortBy],
);
+ // Project and bot-platform filters describe topics only, as for Channels.
+ const shareVisitorPool = useMemo(
+ () =>
+ groupIds.length === 0 && botChannels.length === 0
+ ? shareVisitors.conversations.filter(
+ (conversation) =>
+ matchesShareVisitorSearch(conversation, trimmedSearch) &&
+ matchesTimeRange(conversation, timeRange),
+ )
+ : [],
+ [shareVisitors.conversations, groupIds, botChannels, trimmedSearch, timeRange],
+ );
+
+ const visibleShareVisitors = useMemo(
+ () => (matchesShareVisitorStatus(status) ? sortShareVisitorsBy(shareVisitorPool, sortBy) : []),
+ [shareVisitorPool, status, sortBy],
+ );
+
const statusCounts = useMemo(() => {
const count = (tab: StatusFilter) =>
preStatusPool.filter((t) => matchesStatus(t, tab)).length +
- channelPool.filter((channel) => matchesChannelStatus(channel, tab)).length;
+ channelPool.filter((channel) => matchesChannelStatus(channel, tab)).length +
+ (matchesShareVisitorStatus(tab) ? shareVisitorPool.length : 0);
return {
active: count('active'),
all: count('all'),
@@ -185,7 +213,7 @@ const AgentTopicManager = memo(() => {
completed: count('completed'),
running: count('running'),
};
- }, [preStatusPool, channelPool]);
+ }, [preStatusPool, channelPool, shareVisitorPool]);
// Search results are flat — grouping by time confuses the relevance order
// returned by the BM25 keyword search.
@@ -299,11 +327,19 @@ const AgentTopicManager = memo(() => {
}}
/>
) : (isLoading && baseTopics.length === 0) ||
- (channelsLoading && totalAfterFilter === 0) ? (
+ ((channelsLoading || shareVisitors.loading) && totalAfterFilter === 0) ? (
<TopicsSkeleton chrome={'body'} />
) : channelsError && totalAfterFilter === 0 ? (
<AsyncError error={channelsError} variant={'block'} onRetry={retryChannels} />
- ) : totalAfterFilter === 0 && visibleChannels.length === 0 ? (
+ ) : shareVisitors.error && totalAfterFilter === 0 && visibleChannels.length === 0 ? (
+ <AsyncError
+ error={shareVisitors.error}
+ variant={'block'}
+ onRetry={shareVisitors.retry}
+ />
+ ) : totalAfterFilter === 0 &&
+ visibleChannels.length === 0 &&
+ visibleShareVisitors.length === 0 ? (
<EmptyState
agentId={activeAgentId}
hasFilters={hasActiveFilters}
@@ -316,6 +352,15 @@ const AgentTopicManager = memo(() => {
) : (
<ChannelSection channels={visibleChannels} />
)}
+ {shareVisitors.error ? (
+ <AsyncError
+ error={shareVisitors.error}
+ variant={'inline'}
+ onRetry={shareVisitors.retry}
+ />
+ ) : (
+ <ShareVisitorSection conversations={visibleShareVisitors} />
+ )}
{totalAfterFilter === 0 ? null : viewMode === 'card' ? (
<TopicGrid
agentId={activeAgentId}
diff --git a/src/features/AgentTopicManager/types.ts b/src/features/AgentTopicManager/types.ts
index 14aabd0c3ef..a087c60fbe1 100644
--- a/src/features/AgentTopicManager/types.ts
+++ b/src/features/AgentTopicManager/types.ts
@@ -4,9 +4,11 @@ export type StatusFilter = 'all' | 'active' | 'running' | 'completed' | 'archive
/**
* `bot` is an IM bot platform (Discord, Telegram, …); `channel` is a multi-agent Channel, whose
- * conversations are listed as Channels rather than as topics.
+ * conversations are listed as Channels rather than as topics; `share` lists visitors' direct
+ * Channels with the Agent through its share link.
*/
-export type TriggerFilter = 'chat' | 'api' | 'task' | 'eval' | 'bot' | 'channel' | 'webhook';
+export type TriggerFilter =
+ 'chat' | 'api' | 'task' | 'eval' | 'bot' | 'channel' | 'share' | 'webhook';
export type TimeRangeFilter = 'all' | 'today' | 'week' | 'month';
diff --git a/src/features/AgentTopicManager/useShareVisitors.ts b/src/features/AgentTopicManager/useShareVisitors.ts
new file mode 100644
index 00000000000..3545ddbc930
--- /dev/null
+++ b/src/features/AgentTopicManager/useShareVisitors.ts
@@ -0,0 +1,22 @@
+import { useClientDataSWR } from '@/libs/swr';
+import { channelService } from '@/services/channel';
+import { CHANNEL_IDLE_REFRESH_MS } from '@/store/channel/action';
+
+/**
+ * Visitors' conversations with the Agent's share, read only while the 「Share」 source is picked.
+ * Empty unless the share lets its owner read visitor conversations. Visitors keep talking and runs
+ * settle without notifying the creator, so the list refreshes like the idle Channel list.
+ */
+export const useShareVisitors = (agentId: string | undefined, enabled: boolean) => {
+ const { data, error, isLoading, mutate } = useClientDataSWR(
+ enabled && agentId ? ['agentTopicManager', 'shareVisitors', agentId] : null,
+ () => channelService.shareVisitors(agentId!),
+ { refreshInterval: CHANNEL_IDLE_REFRESH_MS },
+ );
+ return {
+ conversations: enabled ? (data ?? []) : [],
+ error: enabled && !data ? error : undefined,
+ loading: enabled && isLoading,
+ retry: () => void mutate(),
+ };
+};
diff --git a/src/features/AgentTopicManager/utils.test.ts b/src/features/AgentTopicManager/utils.test.ts
index bc5f7d5b4ba..d1c8217a216 100644
--- a/src/features/AgentTopicManager/utils.test.ts
+++ b/src/features/AgentTopicManager/utils.test.ts
@@ -1,4 +1,4 @@
-import type { ChannelListItem } from '@lobechat/types';
+import type { ChannelListItem, ShareVisitorConversation } from '@lobechat/types';
import type { ChatTopic } from '@/types/topic';
@@ -15,8 +15,11 @@ import {
matchesChannelSearch,
matchesChannelStatus,
matchesGroup,
+ matchesShareVisitorSearch,
+ matchesShareVisitorStatus,
matchesTrigger,
sortChannelsBy,
+ sortShareVisitorsBy,
} from './utils';
const createChannel = (overrides: Partial<ChannelListItem> = {}): ChannelListItem => ({
@@ -237,4 +240,29 @@ describe('AgentTopicManager utils', () => {
expect(sortChannelsBy([alpha, beta], 'updatedAt').map((c) => c.id)).toEqual(['b', 'a']);
expect(sortChannelsBy([beta, alpha], 'title').map((c) => c.id)).toEqual(['a', 'b']);
});
+
+ it('counts share visitors as active, finds them by name or message, and sorts them', () => {
+ const visit = (id: string, name: string | null, content: string, updatedAt: string) =>
+ ({
+ createdAt: new Date('2026-01-01T00:00:00Z'),
+ id,
+ lastMessage: { content },
+ totalCost: 0,
+ totalTokens: 0,
+ updatedAt: new Date(updatedAt),
+ visitor: { avatar: null, id: `u_${id}`, name },
+ }) as ShareVisitorConversation;
+ const ada = visit('a', 'Ada', 'Plan my trip', '2026-01-02T00:00:00Z');
+ const bob = visit('b', null, 'Write a poem', '2026-01-03T00:00:00Z');
+
+ expect(['all', 'active'].every((s) => matchesShareVisitorStatus(s as never))).toBe(true);
+ expect(
+ ['running', 'completed', 'archived'].some((s) => matchesShareVisitorStatus(s as never)),
+ ).toBe(false);
+ expect(matchesShareVisitorSearch(ada, ' ada ')).toBe(true);
+ expect(matchesShareVisitorSearch(bob, 'poem')).toBe(true);
+ expect(matchesShareVisitorSearch(bob, 'ada')).toBe(false);
+ expect(sortShareVisitorsBy([ada, bob], 'updatedAt').map((c) => c.id)).toEqual(['b', 'a']);
+ expect(sortShareVisitorsBy([bob, ada], 'title').map((c) => c.id)).toEqual(['b', 'a']);
+ });
});
diff --git a/src/features/AgentTopicManager/utils.ts b/src/features/AgentTopicManager/utils.ts
index 98f932ddcea..191bea01c62 100644
--- a/src/features/AgentTopicManager/utils.ts
+++ b/src/features/AgentTopicManager/utils.ts
@@ -1,4 +1,4 @@
-import type { ChannelListItem, GroupedTopic } from '@lobechat/types';
+import type { ChannelListItem, GroupedTopic, ShareVisitorConversation } from '@lobechat/types';
import {
getTopicWorkingDirectoryEffectivePath,
getTopicWorkingDirectorySourcePath,
@@ -153,6 +153,37 @@ export const sortChannelsBy = (channels: ChannelListItem[], sortBy: SortBy): Cha
});
};
+/**
+ * A visitor's conversation under the topic status tabs: it is never archived or completed and
+ * reports no run, so it counts as active.
+ */
+export const matchesShareVisitorStatus = (status: StatusFilter): boolean =>
+ status === 'all' || status === 'active';
+
+/** Search matches the visitor's name or the conversation's latest message. */
+export const matchesShareVisitorSearch = (
+ conversation: ShareVisitorConversation,
+ search: string,
+): boolean => {
+ const keyword = search.trim().toLowerCase();
+ if (!keyword) return true;
+ return [conversation.visitor.name, conversation.lastMessage?.content].some((text) =>
+ text?.toLowerCase().includes(keyword),
+ );
+};
+
+export const sortShareVisitorsBy = (
+ conversations: ShareVisitorConversation[],
+ sortBy: SortBy,
+): ShareVisitorConversation[] => {
+ const time = (value: Date | string) => new Date(value).getTime();
+ return [...conversations].sort((a, b) => {
+ if (sortBy === 'title') return (a.visitor.name ?? '').localeCompare(b.visitor.name ?? '');
+ if (sortBy === 'createdAt') return time(b.createdAt) - time(a.createdAt);
+ return time(b.updatedAt) - time(a.updatedAt);
+ });
+};
+
export const sortTopics = (topics: ChatTopic[], sortBy: SortBy): ChatTopic[] => {
const sorted = [...topics];
switch (sortBy) {
diff --git a/src/features/Channels/ChannelConversation.tsx b/src/features/Channels/ChannelConversation.tsx
index dfce7af3367..876f64c5d5f 100644
--- a/src/features/Channels/ChannelConversation.tsx
+++ b/src/features/Channels/ChannelConversation.tsx
@@ -27,6 +27,7 @@ import { isCurrentUserMember } from './memberName';
import { channelTimeFormatters, presentChannelTimeline } from './messagePresentation';
import { presentOutgoingMessage, timelineTail } from './outgoing';
import { OutgoingStatus } from './OutgoingStatus';
+import { ReadOnlyNotice } from './ReadOnlyNotice';
import { ReplyActivity } from './ReplyActivity';
import type { ReplyTopic } from './ReplyTopicPanel';
import { styles } from './styles';
@@ -124,6 +125,8 @@ const Timeline = ({
const thread = threadId ? detail?.threads.find((entry) => entry.id === threadId) : undefined;
const selectReply = (message: ChannelPublicMessage) => reply.select(message);
const channelArchived = detail?.channel.status === 'archived';
+ // A shared Agent's owner reading a visitor's conversation: nothing to send, reply to or branch.
+ const readOnly = !!detail?.readOnly;
const direct = !!detail?.channel.agentId;
// Join lines belong to the main conversation; a thread starts from its root message. A direct
// conversation reads like a chat with its Agent, so it has no "invited" lines at all.
@@ -202,7 +205,9 @@ const Timeline = ({
highlighted={highlighted === detail.rootMessage.id}
root={detail.rootMessage}
onReply={
- channelArchived || thread?.status === 'archived' ? undefined : selectReply
+ channelArchived || readOnly || thread?.status === 'archived'
+ ? undefined
+ : selectReply
}
/>
)}
@@ -256,9 +261,11 @@ const Timeline = ({
onJumpToMessage={jumpToMessage}
onOpenThread={onOpenThread}
onOpenTopic={onOpenTopic}
- onStartThread={channelArchived ? undefined : onStartThread}
+ onStartThread={channelArchived || readOnly ? undefined : onStartThread}
onReply={
- channelArchived || thread?.status === 'archived' ? undefined : selectReply
+ channelArchived || readOnly || thread?.status === 'archived'
+ ? undefined
+ : selectReply
}
/>
)}
@@ -266,7 +273,9 @@ const Timeline = ({
))}
</WideScreenContainer>
</Flexbox>
- {channelArchived || thread?.status === 'archived' ? (
+ {readOnly ? (
+ <ReadOnlyNotice />
+ ) : channelArchived || thread?.status === 'archived' ? (
<ArchivedNotice channel={detail.channel} threadId={threadId} />
) : (
<Composer
diff --git a/src/features/Channels/ReadOnlyNotice.tsx b/src/features/Channels/ReadOnlyNotice.tsx
new file mode 100644
index 00000000000..e34d5527f6d
--- /dev/null
+++ b/src/features/Channels/ReadOnlyNotice.tsx
@@ -0,0 +1,27 @@
+import { Flexbox, Icon } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
+import { Eye } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import WideScreenContainer from '@/features/WideScreenContainer';
+
+import { styles } from './styles';
+
+/**
+ * Stands in for the composer while a shared Agent's owner reads a visitor's conversation with it:
+ * the owner can follow the conversation but never takes part in it.
+ */
+export function ReadOnlyNotice() {
+ const { t } = useTranslation('channel');
+
+ return (
+ <WideScreenContainer fullWidth paddingInline={8}>
+ <div role="status" {...stylex.props(styles.archivedNotice)}>
+ <Flexbox horizontal align="center" gap={8} style={{ minWidth: 0 }}>
+ <Icon icon={Eye} size={16} />
+ <span>{t('shareVisitorReadOnlyNotice')}</span>
+ </Flexbox>
+ </div>
+ </WideScreenContainer>
+ );
+}
diff --git a/src/services/channel.ts b/src/services/channel.ts
index 7a39f741a49..3418305c29e 100644
--- a/src/services/channel.ts
+++ b/src/services/channel.ts
@@ -3,6 +3,7 @@ import type {
ChannelJoinableItem,
ChannelListItem,
ChannelVisibility,
+ ShareVisitorConversation,
} from '@lobechat/types';
import { lambdaClient } from '@/libs/trpc/client';
@@ -87,6 +88,9 @@ class ChannelService {
/** The caller's direct Channel with another person's shared Agent, from its share id or handle. */
openShared = async (input: { share: string }) =>
(await lambdaClient.channel.openShared.mutate(input)).data;
+ /** 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;
detail = async (params: ChannelViewParams): Promise<ChannelDetail> =>
(await lambdaClient.channel.detail.query(params)).data;
list = async (): Promise<ChannelListItem[]> => (await lambdaClient.channel.list.query()).data;