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.

♻️ refactor(agent-share): move the share surface out of the open-source tree (#19467)

Arvin Xuab5ec4c81d99
diff --git a/apps/server/src/routers/lambda/__tests__/share.test.ts b/apps/server/src/routers/lambda/__tests__/share.test.ts
index 061af14342b..4b4aa27eac2 100644
--- a/apps/server/src/routers/lambda/__tests__/share.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/share.test.ts
@@ -14,6 +14,18 @@ vi.mock('@/database/models/agentShare', () => ({
},
}));
+const countShareVisitors = vi.fn();
+const topicModelConstructor = vi.fn();
+
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: class {
+ constructor(...args: unknown[]) {
+ topicModelConstructor(...args);
+ }
+ countShareVisitors = countShareVisitors;
+ },
+}));
+
vi.mock('@/database/models/topicShare', () => ({
TopicShareModel: {
findByShareIdWithAccessCheck: vi.fn(),
@@ -22,9 +34,7 @@ vi.mock('@/database/models/topicShare', () => ({
}));
vi.mock('@/database/core/db-adaptor', () => ({
- getServerDB: vi.fn(function () {
- return {};
- }),
+ getServerDB: vi.fn(() => ({})),
}));
vi.mock('@/database/server', () => ({
@@ -74,9 +84,19 @@ describe('shareRouter', () => {
agentDescription: 'A shared agent',
agentId: 'agent-1',
agentName: 'Alice',
+ agentOpeningQuestions: ['What can you do?'],
+ agentTags: ['research'],
agentTitle: 'Research Assistant',
ownerId: 'owner-user',
- shareConfig: { maxTopicsPerVisitor: 5, maxTurnsPerTopic: 20, slug: 'shared-agent' },
+ ownerAvatar: 'owner.png',
+ ownerFullName: 'Owner Person',
+ ownerUsername: 'owner',
+ shareConfig: {
+ maxTopicsPerVisitor: 5,
+ maxTurnsPerTopic: 20,
+ slug: 'shared-agent',
+ toolGrants: [{ apis: ['search'], identifier: 'lobe-web-browsing' }],
+ },
shareId: 'agent-share-1',
userViewCount: 42,
visibility: 'link',
@@ -89,6 +109,7 @@ describe('shareRouter', () => {
vi.mocked(AgentShareModel.findBySlugOrId).mockResolvedValue(agentShare as any);
vi.mocked(AgentShareModel.assertShareAccess).mockReturnValue(undefined);
vi.mocked(AgentShareModel.incrementUserViewCount).mockResolvedValue(undefined);
+ countShareVisitors.mockResolvedValue({ topicCount: 12, visitorCount: 7 });
});
it('requires authentication without resolving or counting the share', async () => {
@@ -113,16 +134,30 @@ describe('shareRouter', () => {
backgroundColor: '#ffffff',
description: 'A shared agent',
name: 'Alice',
+ openingQuestions: ['What can you do?'],
+ tags: ['research'],
title: 'Research Assistant',
},
+ creator: { avatar: 'owner.png', name: 'Owner Person' },
isOwner: false,
shareId: 'agent-share-1',
slug: 'shared-agent',
+ stats: { conversations: 12, views: 42, visitors: 7 },
+ terms: {
+ allowCreatorViewSessions: false,
+ maxTopicsPerVisitor: 5,
+ maxTurnsPerTopic: 20,
+ },
+ // Identifier only: the granted API list is owner-facing configuration.
+ toolGrants: ['lobe-web-browsing'],
visibility: 'link',
});
expect(result).not.toHaveProperty('ownerId');
expect(result).not.toHaveProperty('shareConfig');
expect(result).not.toHaveProperty('userViewCount');
+ // Visitor topics live under the creator's account, so the counter has to
+ // run as the owner rather than the caller.
+ expect(topicModelConstructor).toHaveBeenCalledWith(expect.anything(), 'owner-user');
expect(AgentShareModel.findBySlugOrId).toHaveBeenCalledWith(
expect.anything(),
'shared-agent',
@@ -189,7 +224,7 @@ describe('shareRouter', () => {
it('does not count a failed FORBIDDEN access', async () => {
const code = 'FORBIDDEN';
- vi.mocked(AgentShareModel.assertShareAccess).mockImplementation(function () {
+ vi.mocked(AgentShareModel.assertShareAccess).mockImplementation(() => {
throw new TRPCError({ code, message: 'This share is private' });
});
const caller = shareRouter.createCaller(await createContextInner({ userId: 'visitor-user' }));
diff --git a/apps/server/src/routers/lambda/share.ts b/apps/server/src/routers/lambda/share.ts
index 4e9a62f289c..d793a5d9702 100644
--- a/apps/server/src/routers/lambda/share.ts
+++ b/apps/server/src/routers/lambda/share.ts
@@ -1,9 +1,14 @@
+import {
+ AGENT_SHARE_DEFAULT_MAX_TOPICS_PER_VISITOR,
+ AGENT_SHARE_DEFAULT_MAX_TURNS_PER_TOPIC,
+} from '@lobechat/const';
import { type SharedAgentData, type SharedTopicData } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import debug from 'debug';
import { z } from 'zod';
import { AgentShareModel } from '@/database/models/agentShare';
+import { TopicModel } from '@/database/models/topic';
import { TopicShareModel } from '@/database/models/topicShare';
import { authedProcedure, publicProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
@@ -53,6 +58,19 @@ export const shareRouter = router({
}
}
+ // Reach numbers are scoped to the SHARE OWNER, not the caller: visitor
+ // topics live under the creator's account, so the counter has to run as
+ // them. Best-effort — analytics must never turn a valid share page into
+ // an error.
+ let stats = { conversations: 0, visitors: 0 };
+ try {
+ const topicModel = new TopicModel(ctx.serverDB, share.ownerId);
+ const counts = await topicModel.countShareVisitors({ agentId: share.agentId });
+ stats = { conversations: counts.topicCount, visitors: counts.visitorCount };
+ } catch (error) {
+ log('failed to count share visitors for %s: %O', share.shareId, error);
+ }
+
return {
agentId: share.agentId,
agentMeta: {
@@ -60,11 +78,28 @@ export const shareRouter = router({
backgroundColor: share.agentBackgroundColor,
description: share.agentDescription,
name: share.agentName,
+ openingQuestions: share.agentOpeningQuestions ?? [],
+ tags: share.agentTags ?? [],
title: share.agentTitle,
},
+ creator: {
+ avatar: share.ownerAvatar ?? null,
+ name: share.ownerFullName ?? share.ownerUsername ?? null,
+ },
isOwner,
shareId: share.shareId,
slug: share.shareConfig.slug ?? null,
+ stats: { ...stats, views: share.userViewCount },
+ terms: {
+ allowCreatorViewSessions: share.shareConfig.allowCreatorViewSessions ?? false,
+ maxTopicsPerVisitor:
+ share.shareConfig.maxTopicsPerVisitor ?? AGENT_SHARE_DEFAULT_MAX_TOPICS_PER_VISITOR,
+ maxTurnsPerTopic:
+ share.shareConfig.maxTurnsPerTopic ?? AGENT_SHARE_DEFAULT_MAX_TURNS_PER_TOPIC,
+ },
+ // Identifiers only. The granted API list is owner-facing configuration
+ // and must not reach a visitor.
+ toolGrants: (share.shareConfig.toolGrants ?? []).map((grant) => grant.identifier),
// TODO(cloud budget gate): the spend gate itself is already enforced —
// `shareChat.execAgent` checks `checkAgentShareSpendAllowance` before
// dispatching a run. This READ-ONLY endpoint just doesn't yet expose
diff --git a/e2e/src/features/routes/core-routes.feature b/e2e/src/features/routes/core-routes.feature
index a837e8ef3eb..e727b0f5301 100644
--- a/e2e/src/features/routes/core-routes.feature
+++ b/e2e/src/features/routes/core-routes.feature
@@ -38,8 +38,3 @@ Feature: Core Routes Accessibility
| proxy |
| storage |
| tts |
-
- @ROUTES-003 @P2
- Scenario: Return home from an agent share using the keyboard
- When I navigate to "/a/e2e-missing-share"
- Then I can return home from the agent share page using the keyboard
diff --git a/e2e/src/steps/routes/routes.steps.ts b/e2e/src/steps/routes/routes.steps.ts
index f521393b728..c989235bfa4 100644
--- a/e2e/src/steps/routes/routes.steps.ts
+++ b/e2e/src/steps/routes/routes.steps.ts
@@ -17,18 +17,6 @@ Given('the application is running', async function (this: CustomWorld) {
this.testContext.lastResponse = response;
});
-Then(
- 'I can return home from the agent share page using the keyboard',
- async function (this: CustomWorld) {
- const home = this.page.getByRole('link', { name: 'Go to my LobeHub' }).first();
- await expect(home).toBeVisible();
- await this.page.keyboard.press('Tab');
- await expect(home).toBeFocused();
- await this.page.keyboard.press('Enter');
- await expect(this.page).toHaveURL(/\/$/);
- },
-);
-
// ============================================
// Then Steps (Assertions)
// ============================================
diff --git a/locales/en-US/agent.json b/locales/en-US/agent.json
index 3cf53c3c094..71b36a36054 100644
--- a/locales/en-US/agent.json
+++ b/locales/en-US/agent.json
@@ -390,6 +390,32 @@
"share.visitor.input.send": "Send",
"share.visitor.input.stop": "Stop",
"share.visitor.privacyNotice": "This conversation runs on the owner’s account and may be visible to them. Avoid sharing sensitive information.",
+ "share.visitor.profile.about": "About",
+ "share.visitor.profile.createdBy": "Created by {{creator}}",
+ "share.visitor.profile.cta": "Start a conversation",
+ "share.visitor.profile.ctaSignIn": "Sign in to start",
+ "share.visitor.profile.freeNote": "Free · paid for by the creator",
+ "share.visitor.profile.metrics.conversations": "Conversations",
+ "share.visitor.profile.metrics.conversationsCaption": "started so far",
+ "share.visitor.profile.metrics.tools": "Open tools",
+ "share.visitor.profile.metrics.toolsCaption": "available to you",
+ "share.visitor.profile.metrics.turns": "Each conversation",
+ "share.visitor.profile.metrics.turnsCaption": "turns at most",
+ "share.visitor.profile.metrics.views": "Views",
+ "share.visitor.profile.metrics.viewsCaption": "on this page",
+ "share.visitor.profile.metrics.visitors": "People who used it",
+ "share.visitor.profile.metrics.visitorsCaption": "visitors",
+ "share.visitor.profile.starters.desc": "Pick one and it goes straight into the composer.",
+ "share.visitor.profile.starters.title": "Not sure where to start?",
+ "share.visitor.profile.terms.account": "It runs on the creator’s account, and every reply is paid for by them.",
+ "share.visitor.profile.terms.desc": "Today these rules only show up as errors once you hit them. Here they are up front.",
+ "share.visitor.profile.terms.title": "Before you start",
+ "share.visitor.profile.terms.tools_one": "{{count}} tool is open to visitors.",
+ "share.visitor.profile.terms.tools_other": "{{count}} tools are open to visitors.",
+ "share.visitor.profile.terms.topics": "You can open up to {{count}} conversations.",
+ "share.visitor.profile.terms.turns": "Each conversation allows up to {{count}} turns.",
+ "share.visitor.profile.terms.visibilityCreator": "The creator has turned on session review, so they can read this conversation.",
+ "share.visitor.profile.terms.visibilityPrivate": "Only you can see your conversations.",
"share.visitor.topBar.home": "Go to my LobeHub",
"share.visitor.topics.empty": "No conversations yet",
"share.visitor.topics.new": "New conversation",
diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.json
index a1896267116..4fe63ef926c 100644
--- a/locales/zh-CN/agent.json
+++ b/locales/zh-CN/agent.json
@@ -390,6 +390,31 @@
"share.visitor.input.send": "发送",
"share.visitor.input.stop": "停止",
"share.visitor.privacyNotice": "本次会话运行在创建者的账号下,内容可能对创建者可见,请勿发送敏感信息。",
+ "share.visitor.profile.about": "简介",
+ "share.visitor.profile.createdBy": "由 {{creator}} 创建",
+ "share.visitor.profile.cta": "开始对话",
+ "share.visitor.profile.ctaSignIn": "登录后开始",
+ "share.visitor.profile.freeNote": "免费 · 由创建者付费",
+ "share.visitor.profile.metrics.conversations": "累计对话",
+ "share.visitor.profile.metrics.conversationsCaption": "次会话",
+ "share.visitor.profile.metrics.tools": "开放工具",
+ "share.visitor.profile.metrics.toolsCaption": "项可用",
+ "share.visitor.profile.metrics.turns": "每个会话",
+ "share.visitor.profile.metrics.turnsCaption": "轮上限",
+ "share.visitor.profile.metrics.views": "浏览",
+ "share.visitor.profile.metrics.viewsCaption": "次访问",
+ "share.visitor.profile.metrics.visitors": "用过的人",
+ "share.visitor.profile.metrics.visitorsCaption": "位访客",
+ "share.visitor.profile.starters.desc": "点一条,它会直接带进输入框。",
+ "share.visitor.profile.starters.title": "不知道从哪开始?",
+ "share.visitor.profile.terms.account": "它运行在创建者的账号上,每一次回复都由创建者付费。",
+ "share.visitor.profile.terms.desc": "这几条规则今天只在你撞上时以报错的形式出现,这里把它们提前讲清楚。",
+ "share.visitor.profile.terms.title": "开始之前",
+ "share.visitor.profile.terms.tools_other": "有 {{count}} 个工具对访客开放。",
+ "share.visitor.profile.terms.topics": "你最多可以开 {{count}} 个会话。",
+ "share.visitor.profile.terms.turns": "每个会话最多 {{count}} 轮。",
+ "share.visitor.profile.terms.visibilityCreator": "创建者开启了会话查看权限,可以读到这段对话。",
+ "share.visitor.profile.terms.visibilityPrivate": "你的对话只有你自己能看到。",
"share.visitor.topBar.home": "回到我的 LobeHub",
"share.visitor.topics.empty": "还没有会话",
"share.visitor.topics.new": "新建会话",
diff --git a/packages/database/src/models/agentShare.ts b/packages/database/src/models/agentShare.ts
index 566e73ad324..41937f34f80 100644
--- a/packages/database/src/models/agentShare.ts
+++ b/packages/database/src/models/agentShare.ts
@@ -15,7 +15,7 @@ import type {
AgentShareItem,
NormalizedAgentShareConfig,
} from '../schemas';
-import { agents, agentShares } from '../schemas';
+import { agents, agentShares, users } from '../schemas';
import type { LobeChatDatabase } from '../type';
import { normalizeInboxAgentAvatar, normalizeInboxAgentTitle } from '../utils/inboxAgent';
import { isUuid } from '../utils/uuid';
@@ -484,9 +484,18 @@ export class AgentShareModel {
agentDescription: agents.description,
agentId: agentShares.agentId,
agentName: agents.name,
+ agentOpeningQuestions: agents.openingQuestions,
agentSlug: agents.slug,
+ agentTags: agents.tags,
agentTitle: agents.title,
+ // Creator identity for the visitor-facing profile. Left-joined on the
+ // owner rather than read through a second query: the share page needs
+ // it on its only round trip, and the row is already joined for the
+ // personal-scope guard below.
+ ownerAvatar: users.avatar,
+ ownerFullName: users.fullName,
ownerId: agents.userId,
+ ownerUsername: users.username,
shareConfig: agentShares.shareConfig,
shareId: agentShares.id,
userViewCount: agentShares.userViewCount,
@@ -494,6 +503,7 @@ export class AgentShareModel {
})
.from(agentShares)
.innerJoin(agents, eq(agentShares.agentId, agents.id))
+ .leftJoin(users, eq(agents.userId, users.id))
.where(and(eq(agentShares.id, shareId), isNull(agents.workspaceId)))
.limit(1);
@@ -502,6 +512,8 @@ export class AgentShareModel {
return {
...share,
agentAvatar: normalizeInboxAgentAvatar(share.agentAvatar, { slug: share.agentSlug }),
+ agentOpeningQuestions: share.agentOpeningQuestions ?? [],
+ agentTags: share.agentTags ?? [],
agentTitle: normalizeInboxAgentTitle(share.agentTitle, { slug: share.agentSlug }),
shareConfig: normalizeAgentShareConfig(share.shareConfig),
};
diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.ts
index 4689d3fcd27..7a4a42e4068 100644
--- a/packages/locales/src/default/agent.ts
+++ b/packages/locales/src/default/agent.ts
@@ -509,6 +509,35 @@ export default {
'share.visitor.input.stop': 'Stop',
'share.visitor.privacyNotice':
'This conversation runs on the owner’s account and may be visible to them. Avoid sharing sensitive information.',
+ 'share.visitor.profile.about': 'About',
+ 'share.visitor.profile.createdBy': 'Created by {{creator}}',
+ 'share.visitor.profile.cta': 'Start a conversation',
+ 'share.visitor.profile.ctaSignIn': 'Sign in to start',
+ 'share.visitor.profile.freeNote': 'Free · paid for by the creator',
+ 'share.visitor.profile.metrics.conversations': 'Conversations',
+ 'share.visitor.profile.metrics.conversationsCaption': 'started so far',
+ 'share.visitor.profile.metrics.tools': 'Open tools',
+ 'share.visitor.profile.metrics.toolsCaption': 'available to you',
+ 'share.visitor.profile.metrics.turns': 'Each conversation',
+ 'share.visitor.profile.metrics.turnsCaption': 'turns at most',
+ 'share.visitor.profile.metrics.views': 'Views',
+ 'share.visitor.profile.metrics.viewsCaption': 'on this page',
+ 'share.visitor.profile.metrics.visitors': 'People who used it',
+ 'share.visitor.profile.metrics.visitorsCaption': 'visitors',
+ 'share.visitor.profile.starters.desc': 'Pick one and it goes straight into the composer.',
+ 'share.visitor.profile.starters.title': 'Not sure where to start?',
+ 'share.visitor.profile.terms.account':
+ 'It runs on the creator’s account, and every reply is paid for by them.',
+ 'share.visitor.profile.terms.desc':
+ 'Today these rules only show up as errors once you hit them. Here they are up front.',
+ 'share.visitor.profile.terms.title': 'Before you start',
+ 'share.visitor.profile.terms.tools_one': '{{count}} tool is open to visitors.',
+ 'share.visitor.profile.terms.tools_other': '{{count}} tools are open to visitors.',
+ 'share.visitor.profile.terms.topics': 'You can open up to {{count}} conversations.',
+ 'share.visitor.profile.terms.turns': 'Each conversation allows up to {{count}} turns.',
+ 'share.visitor.profile.terms.visibilityCreator':
+ 'The creator has turned on session review, so they can read this conversation.',
+ 'share.visitor.profile.terms.visibilityPrivate': 'Only you can see your conversations.',
'share.visitor.topBar.home': 'Go to my LobeHub',
'share.visitor.topics.empty': 'No conversations yet',
'share.visitor.topics.new': 'New conversation',
diff --git a/packages/types/src/agent/share.ts b/packages/types/src/agent/share.ts
index 100c213d229..196aeaaa46c 100644
--- a/packages/types/src/agent/share.ts
+++ b/packages/types/src/agent/share.ts
@@ -1,5 +1,30 @@
import type { ShareVisibility } from '../topic';
+/**
+ * The share's own rules, restated for the visitor BEFORE they invest in a
+ * conversation. Every value here already governs the runtime; the profile
+ * surface exists so the visitor learns them up front instead of by hitting
+ * an error mid-chat.
+ */
+export interface SharedAgentTerms {
+ /** Whether the creator opted into reading visitor conversations. */
+ allowCreatorViewSessions: boolean;
+ /** Maximum conversations this visitor may open against the share. */
+ maxTopicsPerVisitor: number;
+ /** Maximum message turns allowed inside one shared conversation. */
+ maxTurnsPerTopic: number;
+}
+
+/**
+ * Aggregate reach of the share. `views` is a raw page-view counter (not
+ * deduplicated); `visitors` and `conversations` come from the share's topics.
+ */
+export interface SharedAgentStats {
+ conversations: number;
+ views: number;
+ visitors: number;
+}
+
/** Agent metadata exposed to signed-in visitors of an agent share. */
export interface SharedAgentData {
agentId: string;
@@ -8,8 +33,24 @@ export interface SharedAgentData {
backgroundColor: string | null;
description: string | null;
name: string | null;
+ /**
+ * Creator-authored starter prompts. The owner-facing surface has always
+ * had these; the visitor profile is the first place they reach the person
+ * who actually needs the hint.
+ */
+ openingQuestions: string[];
+ /** Free-form labels from `agents.tags`. */
+ tags: string[];
title: string | null;
};
+ /**
+ * Who published this share. In a market of user-made agents the creator is
+ * the quality signal a visitor has before any usage number exists.
+ */
+ creator: {
+ avatar: string | null;
+ name: string | null;
+ };
/**
* True when the requesting user (`ctx.userId`) is the creator of the
* shared agent — lets the client render owner-only affordances (e.g. an
@@ -19,6 +60,13 @@ export interface SharedAgentData {
shareId: string;
/** The share's custom URL slug, if the creator has set one. `null` otherwise. */
slug: string | null;
+ stats: SharedAgentStats;
+ terms: SharedAgentTerms;
+ /**
+ * Identifiers of the tools the creator opened to visitors. Identifiers only
+ * — never the granted API list, which is owner-facing configuration.
+ */
+ toolGrants: string[];
visibility: ShareVisibility;
}
diff --git a/src/business/client/AgentShareSettingsPage.tsx b/src/business/client/AgentShareSettingsPage.tsx
new file mode 100644
index 00000000000..8b5bb57819c
--- /dev/null
+++ b/src/business/client/AgentShareSettingsPage.tsx
@@ -0,0 +1,10 @@
+/**
+ * Business slot: the creator-facing Agent Share settings page.
+ *
+ * Every entry point to this route is hidden when
+ * {@link useAgentShareSupported} reports "not supported", so the open-source
+ * default renders nothing rather than a broken surface.
+ */
+const AgentShareSettingsPage = () => null;
+
+export default AgentShareSettingsPage;
diff --git a/src/business/client/useAgentShareSupported.ts b/src/business/client/useAgentShareSupported.ts
new file mode 100644
index 00000000000..7872298a731
--- /dev/null
+++ b/src/business/client/useAgentShareSupported.ts
@@ -0,0 +1,24 @@
+/**
+ * Business slot: whether the Agent Share surface applies to an agent.
+ *
+ * Agent sharing runs a visitor's conversation on the creator's account and
+ * bills it to them, so the surface ships only where that accounting exists.
+ * This open-source default reports "not supported", which hides every share
+ * entry point (profile tab, header action, settings page).
+ */
+
+export interface AgentShareSupport {
+ /** Whether a *new* share may be published right now. */
+ publishable: boolean;
+ /** Whether the share management surface applies to this agent at all. */
+ supported: boolean;
+ /**
+ * Whether the share entry should be shown: `true` when it may publish or
+ * already has a live share to revoke, `undefined` while still resolving.
+ */
+ visible: boolean | undefined;
+}
+
+const UNSUPPORTED: AgentShareSupport = { publishable: false, supported: false, visible: false };
+
+export const useAgentShareSupported = (_agentId?: null | string): AgentShareSupport => UNSUPPORTED;
diff --git a/src/components/Skeleton/AgentShareVisitor.tsx b/src/components/Skeleton/AgentShareVisitor.tsx
deleted file mode 100644
index 37738bb4f04..00000000000
--- a/src/components/Skeleton/AgentShareVisitor.tsx
+++ /dev/null
@@ -1,95 +0,0 @@
-'use client';
-
-import { Flexbox } from '@lobehub/ui';
-import { createStaticStyles, cssVar } from 'antd-style';
-
-import { useIsMobile } from '@/hooks/useIsMobile';
-
-import SkeletonBar from './Bar';
-import ConversationSegmentSkeleton from './Conversation/Segment';
-
-/** Mirrors `SIDEBAR_WIDTH` of `AgentShareVisitor/Page`. */
-const SIDEBAR_WIDTH = 260;
-
-const styles = createStaticStyles(({ css }) => ({
- header: css`
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
- `,
- sidebar: css`
- border-inline-end: 1px solid ${cssVar.colorBorderSecondary};
- `,
- topBar: css`
- flex: none;
- block-size: 48px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
- background: ${cssVar.colorBgLayout};
- `,
-}));
-
-/**
- * Skeleton of the agent-share visitor page (`/a/:slugOrId`): the product bar
- * on top, the topic list on the left, the shared agent's header row and
- * conversation on the right.
- *
- * Keep this synchronously imported fallback structural: the real brand logo
- * pulls image and icon modules onto every route's first-screen import graph.
- * The visitor page renders the logo after its lazy chunk has loaded.
- *
- * Used at every step of the visitor's arrival — the chunk load and the share
- * fetch — so the page does not swap skeleton shapes on the way in.
- */
-const AgentShareVisitorSkeleton = () => {
- const isMobile = useIsMobile();
-
- return (
- <Flexbox aria-busy height={'100%'} style={{ overflow: 'hidden' }} width={'100%'}>
- <Flexbox
- horizontal
- align={'center'}
- className={styles.topBar}
- justify={'space-between'}
- paddingInline={12}
- >
- <SkeletonBar height={22} radius={cssVar.borderRadius} width={22} />
- <SkeletonBar height={26} radius={cssVar.borderRadius} width={26} />
- </Flexbox>
- <Flexbox horizontal flex={1} style={{ minHeight: 0, overflow: 'hidden' }} width={'100%'}>
- {!isMobile && (
- <Flexbox
- className={styles.sidebar}
- flex={'none'}
- gap={12}
- padding={12}
- width={SIDEBAR_WIDTH}
- >
- <SkeletonBar height={32} radius={cssVar.borderRadiusLG} />
- <Flexbox gap={8} paddingBlock={4}>
- <SkeletonBar height={14} width={'80%'} />
- <SkeletonBar height={14} width={'60%'} />
- <SkeletonBar height={14} width={'70%'} />
- </Flexbox>
- </Flexbox>
- )}
- <Flexbox flex={1} style={{ minWidth: 0, overflow: 'hidden' }}>
- <Flexbox
- horizontal
- align={'center'}
- className={styles.header}
- flex={'none'}
- gap={8}
- padding={12}
- >
- <SkeletonBar height={28} radius={'50%'} width={28} />
- <Flexbox gap={6}>
- <SkeletonBar height={14} width={120} />
- <SkeletonBar height={12} width={200} />
- </Flexbox>
- </Flexbox>
- <ConversationSegmentSkeleton />
- </Flexbox>
- </Flexbox>
- </Flexbox>
- );
-};
-
-export default AgentShareVisitorSkeleton;
diff --git a/src/features/AgentProfileTabs/index.tsx b/src/features/AgentProfileTabs/index.tsx
index 788dc35484d..68ba76dfa9a 100644
--- a/src/features/AgentProfileTabs/index.tsx
+++ b/src/features/AgentProfileTabs/index.tsx
@@ -4,7 +4,7 @@ import { Segmented } from '@lobehub/ui/base-ui';
import { type CSSProperties, memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useAgentShareSupported } from '@/features/AgentShareSettings/useAgentShareSupported';
+import { useAgentShareSupported } from '@/business/client/useAgentShareSupported';
import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { usePermission } from '@/hooks/usePermission';
diff --git a/src/features/AgentShareSettings/Content.tsx b/src/features/AgentShareSettings/Content.tsx
deleted file mode 100644
index 1193d1ce7c5..00000000000
--- a/src/features/AgentShareSettings/Content.tsx
+++ /dev/null
@@ -1,148 +0,0 @@
-'use client';
-
-import { Flexbox } from '@lobehub/ui';
-import { Alert, toast } from '@lobehub/ui/base-ui';
-import { memo, useCallback } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import AgentShareSpendDetail from '@/business/client/features/AgentShareSpendDetail';
-import AsyncError from '@/components/AsyncError';
-import { AgentShareSettingsBodySkeleton } from '@/components/Skeleton/AgentShare';
-import { useGlobalStore } from '@/store/global';
-import { systemStatusSelectors } from '@/store/global/selectors';
-
-import LimitsSection from './LimitsSection';
-import LinkSection from './LinkSection';
-import PermissionsSection from './PermissionsSection';
-import ShareTabs from './ShareTabs';
-import ToolsSection from './ToolsSection';
-import UsageSection from './UsageSection';
-import { type AgentShareConfigPatch, useAgentShare } from './useAgentShare';
-import { useAgentShareSupported } from './useAgentShareSupported';
-import { useShareSettingsTab } from './useShareSettingsTab';
-
-/**
- * `dismissedBannerIds` entry for the "visitors run on your account" notice.
- * Dismissal is per device (global store, persisted): the notice is a one-time
- * briefing, not a per-agent warning, so it stays away for every agent once
- * the owner has read it.
- */
-const NOTICE_DISMISS_ID = 'agent-share-visitor-runs-notice';
-
-interface AgentShareSettingsContentProps {
- agentId: string;
-}
-
-/**
- * Creator-side share settings for one agent, the body of `/agent/:aid/share`.
- * Every control saves immediately; the server merges each config patch
- * atomically, so a failed write leaves the other fields untouched.
- *
- * Layout: the link card (master switch + url) always sits on top, then two
- * tabs split what the owner GRANTS (permissions, tools, limits) from what the
- * share has DONE (usage roll-up and, on deployments that meter it, the
- * per-call spend detail).
- */
-const AgentShareSettingsContent = memo<AgentShareSettingsContentProps>(({ agentId }) => {
- const { t } = useTranslation('agent');
- const { disable, enable, error, isLoading, mutate, share, updateConfig, updateSlug } =
- useAgentShare(agentId);
- const { publishable } = useAgentShareSupported(agentId);
- const [tab, setTab] = useShareSettingsTab();
-
- const noticeDismissed = useGlobalStore(
- systemStatusSelectors.isBannerDismissed(NOTICE_DISMISS_ID),
- );
- const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
- const dismissNotice = useCallback(() => {
- const current = useGlobalStore.getState().status.dismissedBannerIds || [];
- if (current.includes(NOTICE_DISMISS_ID)) return;
- updateSystemStatus({ dismissedBannerIds: [...current, NOTICE_DISMISS_ID] });
- }, [updateSystemStatus]);
-
- const handleConfigChange = useCallback(
- async (patch: AgentShareConfigPatch) => {
- try {
- await updateConfig(patch);
- } catch {
- toast.error(t('share.settings.updateError'));
- }
- },
- [t, updateConfig],
- );
-
- // Same skeleton as the route-level one so the page does not reflow between
- // the chunk load and the share fetch.
- if (isLoading && !share && !error) return <AgentShareSettingsBodySkeleton />;
-
- return (
- <Flexbox gap={16} paddingBlock={16}>
- {/* Sharing grants real execution on the creator's account — say so plainly,
- once: the owner can dismiss it after reading. */}
- {!noticeDismissed && (
- <Alert
- showIcon
- closable={{ onClose: dismissNotice }}
- description={t('share.settings.notice.desc')}
- title={t('share.settings.notice.title')}
- type={'warning'}
- />
- )}
- {error && !share ? (
- <AsyncError error={error} variant={'block'} onRetry={() => void mutate()} />
- ) : (
- <>
- <LinkSection
- publishable={publishable}
- share={share}
- onDisable={disable}
- onEnable={enable}
- onUpdateSlug={updateSlug}
- />
- {/* Turning sharing off keeps the row (and its config) so the SAME link
- resumes on re-enable. The config stays editable while paused on
- purpose: re-enabling republishes whatever grants/limits are stored
- at that instant, so an owner must be able to tighten them BEFORE
- existing link holders regain access. */}
- {share && (
- <>
- <ShareTabs active={tab} onChange={setTab} />
- {tab === 'access' ? (
- <>
- <PermissionsSection
- shareConfig={share.shareConfig}
- onChange={handleConfigChange}
- />
- <ToolsSection
- agentId={agentId}
- shareConfig={share.shareConfig}
- onChange={handleConfigChange}
- />
- <LimitsSection
- agentId={agentId}
- shareConfig={share.shareConfig}
- onChange={handleConfigChange}
- />
- </>
- ) : (
- <>
- <UsageSection
- agentId={agentId}
- monthlySpendLimit={share.shareConfig.monthlySpendLimit}
- />
- {/* Business slot: the per-call spend table. Renders nothing on
- deployments that do not meter share spend. */}
- <AgentShareSpendDetail agentId={agentId} />
- </>
- )}
- </>
- )}
- </>
- )}
- </Flexbox>
- );
-});
-
-AgentShareSettingsContent.displayName = 'AgentShareSettingsContent';
-
-export default AgentShareSettingsContent;
diff --git a/src/features/AgentShareSettings/LimitsSection.tsx b/src/features/AgentShareSettings/LimitsSection.tsx
deleted file mode 100644
index bfc8bb67662..00000000000
--- a/src/features/AgentShareSettings/LimitsSection.tsx
+++ /dev/null
@@ -1,169 +0,0 @@
-'use client';
-
-import { AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT } from '@lobechat/const';
-import { Flexbox } from '@lobehub/ui';
-import { InputNumber } from '@lobehub/ui/base-ui';
-import { memo, useCallback, useRef, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { useSWRConfig } from 'swr';
-
-import { shareKeys } from '@/libs/swr/keys';
-import { agentShareService } from '@/services/agentShare';
-
-import { Section, SettingRow } from './SectionLayout';
-import type { AgentShareConfigPatch, AgentShareConfigState } from './useAgentShare';
-import {
- type AgentShareLimitPatch,
- resolveLimitCommitTarget,
- useDebouncedLimitPatch,
-} from './useDebouncedLimitPatch';
-
-type CountField = 'maxTopicsPerVisitor' | 'maxTurnsPerTopic';
-
-interface LimitsSectionProps {
- agentId: string;
- onChange: (patch: AgentShareConfigPatch) => void;
- shareConfig: AgentShareConfigState;
-}
-
-/**
- * Visitor throughput caps and the creator's monthly spend cap. Every visitor
- * run is billed to the creator, so these are the only things standing between
- * a shared link and an unbounded bill.
- */
-const LimitsSection = memo<LimitsSectionProps>(({ agentId, onChange, shareConfig }) => {
- const { t } = useTranslation('agent');
- const { mutate } = useSWRConfig();
- // Read at flush time, never closed over: `useDebouncedLimitPatch` keeps the
- // PREVIOUS render's `commit` in a ref while it drains the identity-change
- // flush, so that closure's captured `agentId` is still the old one. Only
- // this ref — assigned before the hook runs — knows which agent is current.
- const agentIdRef = useRef(agentId);
- agentIdRef.current = agentId;
-
- // Typing must not fire a request per keystroke: the drafts hold the raw
- // input and the debounced patch commits only valid values. A draft entry is
- // dropped once the write it belongs to has settled, so the field falls back
- // to the (now updated) server value.
- // Drafts may hold `null` (a cleared field): the input is controlled, so a
- // clear that is not mirrored locally snaps back to the saved value on blur
- // and a clear-then-type replacement gets swallowed.
- const [countDraft, setCountDraft] = useState<Partial<Record<CountField, number | null>>>({});
- const [spendDraft, setSpendDraft] = useState<number | null | undefined>();
-
- const settle = useCallback((patch: AgentShareLimitPatch) => {
- setCountDraft((prev) => {
- const next = { ...prev };
- for (const field of ['maxTopicsPerVisitor', 'maxTurnsPerTopic'] as CountField[]) {
- if (patch[field] !== undefined && next[field] === patch[field]) delete next[field];
- }
- return next;
- });
- if (patch.monthlySpendLimit !== undefined) {
- setSpendDraft((prev) => (prev === patch.monthlySpendLimit ? undefined : prev));
- }
- }, []);
-
- const commit = useCallback(
- async (patch: AgentShareLimitPatch, commitIdentity: string) => {
- // The debounced patch was scheduled for the agent this section still
- // renders: go through the shared queue so the optimistic projection and
- // the SWR cache entry stay in lockstep with every other control.
- if (resolveLimitCommitTarget(commitIdentity, agentIdRef.current) === 'current') {
- await onChange(patch);
- return;
- }
-
- // Flushed BECAUSE `agentId` just changed, so this patch belongs to the
- // agent that was navigated away from. `onChange` would drop it: the
- // parent `useAgentShare` already reset its refs for the new agent at
- // render time, and `updateConfig` bails out on a missing base config.
- // Send it straight to the service instead — this mirrors
- // `useAgentShare`'s existing rule that a write issued for an abandoned
- // identity is still SENT (the row it targets is unchanged), only its
- // local bookkeeping is skipped. Revalidate that agent's own status key
- // so its cached snapshot is not left behind the value just persisted.
- try {
- await agentShareService.updateShareConfig(commitIdentity, patch);
- } finally {
- void mutate(shareKeys.agentShareStatus(commitIdentity));
- }
- },
- [mutate, onChange],
- );
-
- const schedule = useDebouncedLimitPatch(agentId, commit, settle);
-
- const handleCountChange = (field: CountField, value: number | null) => {
- setCountDraft((prev) => ({ ...prev, [field]: value }));
- // The server schema only accepts positive integers; an empty or invalid
- // field just holds the draft until it becomes valid again.
- if (typeof value === 'number' && Number.isInteger(value) && value >= 1) {
- const patch: AgentShareLimitPatch = { [field]: value };
- schedule(patch);
- }
- };
-
- const handleSpendChange = (value: number | null) => {
- // `null` is an empty/half-typed field, NOT "no cap": the cap is mandatory,
- // so hold the (empty) draft and commit nothing until a number comes back.
- setSpendDraft(value);
- if (value !== null && value >= 0) schedule({ monthlySpendLimit: value });
- };
-
- return (
- <Section desc={t('share.settings.limits.desc')} title={t('share.settings.limits.title')}>
- <Flexbox gap={12}>
- <SettingRow
- desc={t('share.settings.limits.maxTopicsPerVisitorHint')}
- label={t('share.settings.limits.maxTopicsPerVisitor')}
- >
- <InputNumber
- max={AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT}
- min={1}
- step={1}
- style={{ width: 160 }}
- value={
- countDraft.maxTopicsPerVisitor !== undefined
- ? countDraft.maxTopicsPerVisitor
- : (shareConfig.maxTopicsPerVisitor ?? null)
- }
- onChange={(value) => handleCountChange('maxTopicsPerVisitor', value)}
- />
- </SettingRow>
- <SettingRow
- desc={t('share.settings.limits.maxTurnsPerTopicHint')}
- label={t('share.settings.limits.maxTurnsPerTopic')}
- >
- <InputNumber
- min={1}
- step={1}
- style={{ width: 160 }}
- value={
- countDraft.maxTurnsPerTopic !== undefined
- ? countDraft.maxTurnsPerTopic
- : (shareConfig.maxTurnsPerTopic ?? null)
- }
- onChange={(value) => handleCountChange('maxTurnsPerTopic', value)}
- />
- </SettingRow>
- <SettingRow
- desc={t('share.settings.limits.monthlySpendLimitHint')}
- label={t('share.settings.limits.monthlySpendLimit')}
- >
- <InputNumber
- min={0}
- step={1}
- style={{ width: 160 }}
- value={spendDraft !== undefined ? spendDraft : (shareConfig.monthlySpendLimit ?? null)}
- onChange={handleSpendChange}
- />
- </SettingRow>
- </Flexbox>
- </Section>
- );
-});
-
-LimitsSection.displayName = 'AgentShareLimitsSection';
-
-export default LimitsSection;
diff --git a/src/features/AgentShareSettings/LinkSection.tsx b/src/features/AgentShareSettings/LinkSection.tsx
deleted file mode 100644
index bc0e5293792..00000000000
--- a/src/features/AgentShareSettings/LinkSection.tsx
+++ /dev/null
@@ -1,232 +0,0 @@
-'use client';
-
-import { copyToClipboard, Flexbox, Input, Tooltip } from '@lobehub/ui';
-import { Button, confirmModal, Switch, Text, toast } from '@lobehub/ui/base-ui';
-import { CopyIcon } from 'lucide-react';
-import { memo, useCallback, useEffect, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { AGENT_SHARE_VISITOR_PATH } from '@/features/AgentShareVisitor/visitorPath';
-import { useAppOrigin } from '@/hooks/useAppOrigin';
-
-import { Section } from './SectionLayout';
-import {
- type AgentShareSlugError,
- buildAgentShareUrl,
- normalizeAgentShareSlug,
- validateAgentShareSlug,
-} from './shareLink';
-import type { AgentShareInfo } from './useAgentShare';
-import { resolveLinkToggleState } from './useAgentShareSupported';
-
-const SLUG_ERROR_KEY = {
- invalid: 'share.settings.link.slugError.invalid',
- reserved: 'share.settings.link.slugError.reserved',
- tooLong: 'share.settings.link.slugError.tooLong',
- tooShort: 'share.settings.link.slugError.tooShort',
-} as const satisfies Record<AgentShareSlugError, string>;
-
-interface LinkSectionProps {
- onDisable: () => Promise<void>;
- onEnable: () => Promise<void>;
- onUpdateSlug: (slug: string | null) => Promise<void>;
- /** Whether a new share may be published — see `useAgentShareSupported`. */
- publishable: boolean;
- share: AgentShareInfo | undefined;
-}
-
-/**
- * Sharing on/off, the visitor link, and the custom slug.
- *
- * Turning sharing off only PAUSES it: the share row keeps its id and custom
- * slug, so visitors are locked out while it is off and turning it back on
- * republishes the very same url — see `AgentShareModel.updateVisibility`.
- */
-const LinkSection = memo<LinkSectionProps>((props) => {
- const { onDisable, onEnable, onUpdateSlug, publishable, share } = props;
- const { t } = useTranslation('agent');
- const appOrigin = useAppOrigin();
-
- const isShared = share?.visibility === 'link';
- const savedSlug = share?.shareConfig?.slug ?? '';
- const {
- canPublish,
- disabled: toggleDisabled,
- offHintKey,
- } = resolveLinkToggleState({
- isShared,
- publishable,
- });
-
- const [toggling, setToggling] = useState(false);
- const [slugDraft, setSlugDraft] = useState(savedSlug);
- const [slugError, setSlugError] = useState<string>('');
- const [savingSlug, setSavingSlug] = useState(false);
-
- // Re-sync the draft whenever the server value changes — a save elsewhere, or
- // the row reloading after an enable/disable (which keeps the saved slug).
- useEffect(() => {
- setSlugDraft(savedSlug);
- setSlugError('');
- }, [savedSlug, share?.id]);
-
- const shareUrl =
- share && isShared
- ? buildAgentShareUrl({ origin: appOrigin, shareId: share.id, slug: savedSlug || undefined })
- : '';
-
- const handleCopy = useCallback(async () => {
- if (!shareUrl) return;
- try {
- await copyToClipboard(shareUrl);
- toast.success(t('share.settings.link.copied'));
- } catch {
- toast.error(t('copyFail', { ns: 'common' }));
- }
- }, [shareUrl, t]);
-
- const handleToggle = useCallback(
- async (checked: boolean) => {
- // Publishing is gated (rollout flag / plan); turning an existing share
- // OFF must always stay available, so only the `on` direction is blocked.
- if (checked && !canPublish) return;
-
- const apply = async () => {
- setToggling(true);
- try {
- await (checked ? onEnable() : onDisable());
- } catch {
- toast.error(t('share.settings.updateError'));
- } finally {
- setToggling(false);
- }
- };
-
- if (checked) {
- void apply();
- return;
- }
-
- confirmModal({
- cancelText: t('cancel', { ns: 'common' }),
- content: t('share.settings.link.disableConfirmContent'),
- okText: t('share.settings.link.disableConfirmOk'),
- onOk: apply,
- title: t('share.settings.link.disableConfirmTitle'),
- });
- },
- [canPublish, onDisable, onEnable, t],
- );
-
- const handleSaveSlug = useCallback(async () => {
- const next = normalizeAgentShareSlug(slugDraft);
- if (next === savedSlug) {
- setSlugDraft(next);
- setSlugError('');
- return;
- }
-
- if (next) {
- const error = validateAgentShareSlug(next);
- if (error) {
- setSlugError(t(SLUG_ERROR_KEY[error]));
- return;
- }
- }
-
- setSavingSlug(true);
- setSlugError('');
- try {
- // An emptied field clears the custom slug — the share then resolves by
- // its raw id again.
- await onUpdateSlug(next || null);
- toast.success(t('share.settings.link.slugSaved'));
- } catch (error: any) {
- setSlugError(
- error?.data?.code === 'CONFLICT'
- ? t('share.settings.link.slugError.taken')
- : t('share.settings.updateError'),
- );
- } finally {
- setSavingSlug(false);
- }
- }, [onUpdateSlug, savedSlug, slugDraft, t]);
-
- const slugDirty = normalizeAgentShareSlug(slugDraft) !== savedSlug;
-
- return (
- <Section
- desc={t('share.settings.link.desc')}
- title={t('share.settings.link.title')}
- extra={
- <Tooltip title={toggleDisabled ? t('share.settings.link.publishDisabled') : undefined}>
- {/* A disabled control fires no pointer events, so the wrapper carries the hover. */}
- <Flexbox>
- <Switch
- checked={isShared}
- disabled={toggleDisabled}
- loading={toggling}
- onChange={handleToggle}
- />
- </Flexbox>
- </Tooltip>
- }
- >
- {isShared ? (
- <Flexbox gap={12}>
- {/* ONE field is the link: the editable tail of the url, prefixed by
- the fixed origin. While the draft matches what is saved, the
- primary action copies the live url; the moment it differs, that
- slot becomes "save" — an unsaved slug has no url to copy yet. */}
- <Flexbox horizontal align={'center'} gap={8}>
- <Input
- disabled={savingSlug}
- // The raw share id is the fallback path, so the empty field shows
- // exactly where visitors would land.
- placeholder={share?.id}
- prefix={`${appOrigin}${AGENT_SHARE_VISITOR_PATH}/`}
- status={slugError ? 'error' : undefined}
- style={{ flex: 1 }}
- value={slugDraft}
- variant={'filled'}
- onPressEnter={handleSaveSlug}
- onChange={(e) => {
- setSlugDraft(e.target.value);
- setSlugError('');
- }}
- onKeyDown={(e) => {
- if (e.key !== 'Escape' || !slugDirty) return;
- setSlugDraft(savedSlug);
- setSlugError('');
- }}
- />
- {slugDirty ? (
- <Button loading={savingSlug} type={'primary'} onClick={handleSaveSlug}>
- {t('save', { ns: 'common' })}
- </Button>
- ) : (
- <Button icon={CopyIcon} type={'primary'} onClick={handleCopy}>
- {t('share.settings.link.copy')}
- </Button>
- )}
- </Flexbox>
- <Text fontSize={12} type={slugError ? 'danger' : 'secondary'}>
- {slugError || t('share.settings.link.slugHint')}
- </Text>
-
- <Text fontSize={12} type={'secondary'}>
- {t('share.settings.link.viewCount', { views: String(share?.userViewCount ?? 0) })}
- </Text>
- </Flexbox>
- ) : (
- <Text fontSize={12} type={'secondary'}>
- {t(offHintKey)}
- </Text>
- )}
- </Section>
- );
-});
-
-LinkSection.displayName = 'AgentShareLinkSection';
-
-export default LinkSection;
diff --git a/src/features/AgentShareSettings/Page.tsx b/src/features/AgentShareSettings/Page.tsx
deleted file mode 100644
index 7ca1705ac66..00000000000
--- a/src/features/AgentShareSettings/Page.tsx
+++ /dev/null
@@ -1,69 +0,0 @@
-'use client';
-
-import { Flexbox } from '@lobehub/ui';
-import { memo } from 'react';
-import { Navigate } from 'react-router';
-
-import AgentBreadcrumb from '@/features/AgentBreadcrumb';
-import AgentProfileTabs, { AGENT_PROFILE_TABS_CENTER_STYLE } from '@/features/AgentProfileTabs';
-import NavHeader from '@/features/NavHeader';
-import WideScreenContainer from '@/features/WideScreenContainer';
-import { useAgentStore } from '@/store/agent';
-import { StyleSheet } from '@/utils/styles';
-
-import Content from './Content';
-import { useAgentShareSupported } from './useAgentShareSupported';
-
-const styles = StyleSheet.create({
- body: {
- display: 'flex',
- overflowY: 'auto',
- position: 'relative',
- },
-});
-
-/**
- * Full-page share management for one agent, the fourth segment of the agent
- * profile group. Sharing grants visitors real execution on the creator's
- * account, so the flow gets a deliberate page (deep-linkable, back/forward
- * aware) rather than a modal that any stray click dismisses.
- */
-const AgentShareSettingsPage = memo(() => {
- const activeAgentId = useAgentStore((s) => s.activeAgentId);
- const { visible: shareVisible } = useAgentShareSupported(activeAgentId);
-
- // A deep link on an agent that can never be shared (workspace / builtin row),
- // or by an account outside the rollout allowlist with nothing live to revoke,
- // lands on the agent instead of a settings surface whose every control would
- // fail server-side. `undefined` (lookup still resolving) keeps the page so a
- // revocable share does not flash through a redirect.
- if (activeAgentId && shareVisible === false)
- return <Navigate replace to={`/agent/${activeAgentId}`} />;
-
- return (
- <Flexbox height={'100%'} width={'100%'}>
- <NavHeader
- // No section title — the Segmented beside it names the current tab.
- left={activeAgentId ? <AgentBreadcrumb agentId={activeAgentId} /> : null}
- // `relative` anchors the absolutely-centered switcher below.
- style={{ position: 'relative' }}
- styles={{
- // Center on the header midpoint (equal gaps), not the leftover track.
- center: AGENT_PROFILE_TABS_CENTER_STYLE,
- left: { minWidth: 0, paddingInlineStart: 8 },
- }}
- >
- {activeAgentId && <AgentProfileTabs active={'share'} agentId={activeAgentId} />}
- </NavHeader>
- <Flexbox flex={1} style={styles.body} width={'100%'}>
- <WideScreenContainer>
- {activeAgentId && <Content agentId={activeAgentId} />}
- </WideScreenContainer>
- </Flexbox>
- </Flexbox>
- );
-});
-
-AgentShareSettingsPage.displayName = 'AgentShareSettingsPage';
-
-export default AgentShareSettingsPage;
diff --git a/src/features/AgentShareSettings/PermissionsSection.tsx b/src/features/AgentShareSettings/PermissionsSection.tsx
deleted file mode 100644
index 0ef9526d3f5..00000000000
--- a/src/features/AgentShareSettings/PermissionsSection.tsx
+++ /dev/null
@@ -1,65 +0,0 @@
-'use client';
-
-import { Flexbox } from '@lobehub/ui';
-import { Switch } from '@lobehub/ui/base-ui';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { Section, SettingRow } from './SectionLayout';
-import type { AgentShareConfigPatch, AgentShareConfigState } from './useAgentShare';
-
-interface PermissionsSectionProps {
- onChange: (patch: AgentShareConfigPatch) => void;
- shareConfig: AgentShareConfigState;
-}
-
-/** What a visitor's run may read, and what the visitor is allowed to see back. */
-const PermissionsSection = memo<PermissionsSectionProps>(({ onChange, shareConfig }) => {
- const { t } = useTranslation('agent');
-
- return (
- <Section
- desc={t('share.settings.permissions.desc')}
- title={t('share.settings.permissions.title')}
- >
- <Flexbox gap={12}>
- <SettingRow
- desc={t('share.settings.permissions.allowReadMemoryHint')}
- label={t('share.settings.permissions.allowReadMemory')}
- >
- <Switch
- checked={shareConfig.allowReadMemory ?? false}
- onChange={(checked) => onChange({ allowReadMemory: checked })}
- />
- </SettingRow>
- {/* `allowCreatorViewSessions` is persisted (zod schema + DB default false)
- but no read path honors it yet — creator reads unconditionally
- exclude visitor rows (see packages/database/src/models/topic.ts).
- Hidden here until that read path exists, so the switch is not
- surfaced as a working control. */}
- <SettingRow
- desc={t('share.settings.permissions.showModelInfoHint')}
- label={t('share.settings.permissions.showModelInfo')}
- >
- <Switch
- checked={shareConfig.showModelInfo ?? false}
- onChange={(checked) => onChange({ showModelInfo: checked })}
- />
- </SettingRow>
- <SettingRow
- desc={t('share.settings.permissions.showErrorDetailsHint')}
- label={t('share.settings.permissions.showErrorDetails')}
- >
- <Switch
- checked={shareConfig.showErrorDetails ?? false}
- onChange={(checked) => onChange({ showErrorDetails: checked })}
- />
- </SettingRow>
- </Flexbox>
- </Section>
- );
-});
-
-PermissionsSection.displayName = 'AgentSharePermissionsSection';
-
-export default PermissionsSection;
diff --git a/src/features/AgentShareSettings/SectionLayout.tsx b/src/features/AgentShareSettings/SectionLayout.tsx
deleted file mode 100644
index 748343837c7..00000000000
--- a/src/features/AgentShareSettings/SectionLayout.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-'use client';
-
-import { Block, Flexbox } from '@lobehub/ui';
-import { Text } from '@lobehub/ui/base-ui';
-import type { ReactNode } from 'react';
-
-interface SettingRowProps {
- children: ReactNode;
- /** Secondary line under the label. */
- desc?: ReactNode;
- label: string;
-}
-
-export const SettingRow = ({ children, desc, label }: SettingRowProps) => (
- <Flexbox horizontal align={'center'} gap={16} justify={'space-between'}>
- <Flexbox gap={2}>
- <Text>{label}</Text>
- {desc && (
- <Text fontSize={12} type={'secondary'}>
- {desc}
- </Text>
- )}
- </Flexbox>
- {children}
- </Flexbox>
-);
-
-interface SectionProps {
- children: ReactNode;
- desc?: ReactNode;
- extra?: ReactNode;
- title: string;
-}
-
-export const Section = ({ children, desc, extra, title }: SectionProps) => (
- <Block gap={16} padding={20} variant={'outlined'}>
- <Flexbox horizontal align={'center'} gap={12} justify={'space-between'}>
- <Flexbox gap={2}>
- <Text fontSize={16} weight={500}>
- {title}
- </Text>
- {desc && (
- <Text fontSize={12} type={'secondary'}>
- {desc}
- </Text>
- )}
- </Flexbox>
- {extra}
- </Flexbox>
- {children}
- </Block>
-);
diff --git a/src/features/AgentShareSettings/ShareTabs.tsx b/src/features/AgentShareSettings/ShareTabs.tsx
deleted file mode 100644
index 388b56f1cae..00000000000
--- a/src/features/AgentShareSettings/ShareTabs.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-'use client';
-
-import { Flexbox, Icon } from '@lobehub/ui';
-import { Tabs } from '@lobehub/ui/base-ui';
-import { createStaticStyles } from 'antd-style';
-import { ChartColumnIcon, KeyRoundIcon } from 'lucide-react';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import type { ShareSettingsTab } from './useShareSettingsTab';
-
-const styles = createStaticStyles(({ css, cssVar }) => ({
- nav: css`
- border-block-end: 1px solid ${cssVar.colorBorder};
- `,
-}));
-
-interface ShareTabsProps {
- active: ShareSettingsTab;
- onChange: (tab: ShareSettingsTab) => void;
-}
-
-/**
- * Underline tab strip splitting the share page into what the owner grants
- * (access) and what the share has done (stats) — the same nav pattern as the
- * marketplace detail pages, so it reads as in-page navigation rather than
- * another Segmented control competing with the profile switcher in the header.
- */
-const ShareTabs = memo<ShareTabsProps>(({ active, onChange }) => {
- const { t } = useTranslation('agent');
-
- return (
- <Flexbox className={styles.nav}>
- <Tabs
- activeKey={active}
- variant={'square'}
- items={[
- {
- icon: <Icon icon={KeyRoundIcon} size={16} />,
- key: 'access',
- label: t('share.settings.tabs.access'),
- },
- {
- icon: <Icon icon={ChartColumnIcon} size={16} />,
- key: 'stats',
- label: t('share.settings.tabs.stats'),
- },
- ]}
- onChange={(key) => onChange(key as ShareSettingsTab)}
- />
- </Flexbox>
- );
-});
-
-ShareTabs.displayName = 'AgentShareTabs';
-
-export default ShareTabs;
diff --git a/src/features/AgentShareSettings/ToolRow.tsx b/src/features/AgentShareSettings/ToolRow.tsx
deleted file mode 100644
index cb902806df7..00000000000
--- a/src/features/AgentShareSettings/ToolRow.tsx
+++ /dev/null
@@ -1,265 +0,0 @@
-'use client';
-
-import { Flexbox, Tooltip } from '@lobehub/ui';
-import { ActionIcon, Checkbox, Popover, Text } from '@lobehub/ui/base-ui';
-import { createStaticStyles } from 'antd-style';
-import isEqual from 'fast-deep-equal';
-import { SlidersHorizontalIcon } from 'lucide-react';
-import { Fragment, memo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import PluginTag from '@/features/ProfileEditor/PluginTag';
-import { useToolStore } from '@/store/tool';
-import { pluginSelectors } from '@/store/tool/selectors';
-
-import {
- getShareApiAvailability,
- getShareToolAvailability,
- getShareToolGrantForIdentifier,
- sortBlockedLast,
- toggleShareToolApi,
- toggleShareToolsetGrant,
-} from './toolVisitorAvailability';
-import type { AgentShareConfigPatch, AgentShareConfigState } from './useAgentShare';
-
-const styles = createStaticStyles(({ css, cssVar }) => ({
- divider: css`
- margin-block: 6px;
- border-block-start: 1px solid ${cssVar.colorBorderSecondary};
- `,
- header: css`
- padding-block: 10px;
- padding-inline: 12px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
- `,
- list: css`
- overflow-y: auto;
- max-height: 320px;
- padding-block: 6px;
- padding-inline: 12px;
- `,
- popup: css`
- width: 360px;
- max-width: calc(100vw - 32px);
- `,
- row: css`
- padding-block: 6px;
- `,
-}));
-
-interface ToolRowProps {
- agentId: string;
- onChange: (patch: AgentShareConfigPatch) => void;
- selected: boolean;
- shareConfig: AgentShareConfigState;
- toolId: string;
-}
-
-/**
- * One toolset row in the visitor tool picker: the existing selectable
- * `PluginTag` chip — checked for a full grant, indeterminate (minus) for a
- * partial per-API one, and toggling between them via
- * {@link toggleShareToolsetGrant} — plus a small "fine-tune" button — shown
- * only when the tool has more than one visitor-grantable API — that opens the
- * per-API checkbox list in a popover.
- *
- * A popover rather than an inline expansion on purpose: the chips flow in a
- * wrapped row, so expanding one in place reflows every chip after it and the
- * whole page below. The popover keeps the chip grid still and shows the
- * granted/total count next to the button so a partial grant is legible
- * without opening it.
- *
- * The API list comes from the REAL manifest (builtin registry or an installed
- * plugin/MCP manifest), the same source the server gate reads, so a tool this
- * build does not yet know the APIs of simply never offers the button rather
- * than stale/guessed entries.
- *
- * Inside the popover the APIs are grouped rather than listed in plain manifest
- * order: everything the owner can actually grant comes first, then — below a
- * thin separator — the APIs the gate always strips, greyed out and disabled
- * with the reason in their tooltip (see {@link sortBlockedLast}).
- */
-const ToolRow = memo<ToolRowProps>(({ agentId, toolId, selected, shareConfig, onChange }) => {
- const { t } = useTranslation('agent');
- const [open, setOpen] = useState(false);
-
- const builtinManifest = useToolStore(
- (s) => s.builtinTools.find((tool) => tool.identifier === toolId)?.manifest,
- isEqual,
- );
- const pluginManifest = useToolStore(pluginSelectors.getToolManifestById(toolId), isEqual);
- const apis = (builtinManifest ?? pluginManifest)?.api ?? [];
- const toolTitle = (builtinManifest ?? pluginManifest)?.meta?.title ?? toolId;
-
- const availability = getShareToolAvailability(toolId, {
- allowReadMemory: shareConfig.allowReadMemory,
- });
- // Anything short of `available` is disabled: the gate would strip the
- // grant, so accepting the tick would only confirm a permission that never
- // takes effect. The tooltip carries the reason.
- const blocked = availability !== 'available';
-
- const grantableApiNames = apis
- .filter(
- (api) => getShareApiAvailability(toolId, api.name, api.humanIntervention) === 'available',
- )
- .map((api) => api.name);
- const canConfigure = !blocked && grantableApiNames.length > 1;
-
- // Grantable APIs first (manifest order preserved), then the ones the gate
- // always strips — see `sortBlockedLast` for why they trail instead of sitting
- // where the manifest put them.
- const orderedApis = sortBlockedLast(
- apis,
- (api) => getShareApiAvailability(toolId, api.name, api.humanIntervention) !== 'available',
- );
- // Where the blocked group starts, i.e. where the separator goes.
- // `grantableApiNames` is filtered with the same predicate, so its length IS
- // that boundary; when nothing is blocked it equals `orderedApis.length` and
- // no row ever matches it.
- const firstBlockedApiIndex = grantableApiNames.length;
-
- const grant = getShareToolGrantForIdentifier(shareConfig.toolGrants, toolId);
- const grantedCount =
- grant === 'all'
- ? grantableApiNames.length
- : grant instanceof Set
- ? grantableApiNames.filter((name) => grant.has(name)).length
- : 0;
-
- const toggleTool = () => {
- onChange((current) => ({
- toolGrants: toggleShareToolsetGrant(current.toolGrants, toolId),
- }));
- };
-
- const toggleApi = (apiName: string) => {
- onChange((current) => ({
- toolGrants: toggleShareToolApi(current.toolGrants, toolId, apiName, grantableApiNames),
- }));
- };
-
- const apiPicker = (
- <Flexbox className={styles.popup}>
- <Flexbox
- horizontal
- align={'center'}
- className={styles.header}
- gap={12}
- justify={'space-between'}
- >
- <Text ellipsis weight={500}>
- {toolTitle}
- </Text>
- <Text fontSize={12} style={{ flex: 'none' }} type={'secondary'}>
- {t('share.settings.tools.apiGrantedCount', {
- granted: String(grantedCount),
- total: String(grantableApiNames.length),
- })}
- </Text>
- </Flexbox>
- <Flexbox className={styles.list}>
- {orderedApis.map((api, index) => {
- const apiAvailability = getShareApiAvailability(toolId, api.name, api.humanIntervention);
- const apiBlocked = apiAvailability !== 'available';
- const apiSelected = grant === 'all' || (grant instanceof Set && grant.has(api.name));
-
- return (
- <Fragment key={api.name}>
- {/* Only when BOTH groups exist: a line above the very first row
- (everything blocked) would read as a clipped list. */}
- {index === firstBlockedApiIndex && index > 0 && <div className={styles.divider} />}
- <Tooltip
- placement={'left'}
- title={
- apiAvailability === 'writesOwnerData'
- ? t('share.settings.tools.apiWritesOwnerData')
- : apiBlocked
- ? t('share.settings.tools.apiNotAvailableToVisitors')
- : undefined
- }
- >
- <Flexbox className={styles.row}>
- <Checkbox
- checked={!apiBlocked && apiSelected}
- disabled={apiBlocked}
- onChange={() => toggleApi(api.name)}
- >
- <Flexbox gap={0} style={{ minWidth: 0 }}>
- {/* `disabled` dims the Checkbox's own label, but this
- nested Text re-asserts `colorText` — so grey it
- explicitly, or a blocked API reads as fully enabled. */}
- <Text fontSize={13} type={apiBlocked ? 'secondary' : undefined}>
- {api.name}
- </Text>
- {api.description && (
- <Text ellipsis={{ rows: 2 }} fontSize={12} type={'secondary'}>
- {api.description}
- </Text>
- )}
- </Flexbox>
- </Checkbox>
- </Flexbox>
- </Tooltip>
- </Fragment>
- );
- })}
- </Flexbox>
- </Flexbox>
- );
-
- return (
- <Flexbox horizontal align={'center'} gap={2}>
- <Tooltip
- title={
- availability === 'needsMemoryPermission'
- ? t('share.settings.tools.needsMemoryPermission')
- : blocked
- ? t('share.settings.tools.notAvailableToVisitors')
- : undefined
- }
- >
- <PluginTag
- selectable
- useAllMetaList
- agentId={agentId}
- disabled={blocked}
- indeterminate={grant instanceof Set}
- pluginId={toolId}
- selected={selected}
- onSelect={blocked ? undefined : toggleTool}
- />
- </Tooltip>
- {canConfigure && (
- <Popover
- content={apiPicker}
- open={open}
- placement={'bottomLeft'}
- styles={{ content: { padding: 0 } }}
- trigger={'click'}
- onOpenChange={setOpen}
- >
- <Flexbox horizontal align={'center'} gap={2}>
- <ActionIcon
- active={open}
- icon={SlidersHorizontalIcon}
- size={'small'}
- title={t('share.settings.tools.configureApis')}
- />
- {/* Only a PARTIAL grant needs the count: "all" and "none" already
- read from the chip's own checkbox state. */}
- {grant instanceof Set && (
- <Text fontSize={12} type={'secondary'}>
- {grantedCount}/{grantableApiNames.length}
- </Text>
- )}
- </Flexbox>
- </Popover>
- )}
- </Flexbox>
- );
-});
-
-ToolRow.displayName = 'AgentShareToolRow';
-
-export default ToolRow;
diff --git a/src/features/AgentShareSettings/ToolsSection.tsx b/src/features/AgentShareSettings/ToolsSection.tsx
deleted file mode 100644
index b1a94d5447b..00000000000
--- a/src/features/AgentShareSettings/ToolsSection.tsx
+++ /dev/null
@@ -1,109 +0,0 @@
-'use client';
-
-import { getActivePluginIds } from '@lobechat/types';
-import { Flexbox } from '@lobehub/ui';
-import { Text } from '@lobehub/ui/base-ui';
-import isEqual from 'fast-deep-equal';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { useAgentStore } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/selectors';
-
-import { Section } from './SectionLayout';
-import ToolRow from './ToolRow';
-import {
- getShareToolAvailability,
- getShareToolCandidateIds,
- getVisitorVisibleGrantedToolIds,
-} from './toolVisitorAvailability';
-import type { AgentShareConfigPatch, AgentShareConfigState } from './useAgentShare';
-
-interface ToolsSectionProps {
- agentId: string;
- onChange: (patch: AgentShareConfigPatch) => void;
- shareConfig: AgentShareConfigState;
-}
-
-/**
- * Whitelist of tools a visitor's run may call. Default-deny: an unchecked tool
- * is stripped by the server gate even if the agent itself has it enabled.
- * High-risk identifiers (device, local system, sandbox, ...) and tools the
- * gate refuses outright (knowledge base, agent documents) are never selectable
- * — see `toolVisitorAvailability`.
- */
-const ToolsSection = memo<ToolsSectionProps>(({ agentId, onChange, shareConfig }) => {
- const { t } = useTranslation('agent');
-
- const agentConfig = useAgentStore(agentSelectors.getAgentConfigById(agentId), isEqual);
- // Only tools the owner can actually tick right now. Tools the gate refuses
- // outright never appear (the section copy already says so), and Memory
- // stays hidden until "allow reading my memory" is on — a chip that cannot
- // be toggled is a dead control, not information.
- const candidateToolIds = getShareToolCandidateIds(
- getActivePluginIds(agentConfig?.plugins),
- ).filter(
- (toolId) =>
- getShareToolAvailability(toolId, { allowReadMemory: shareConfig.allowReadMemory }) ===
- 'available',
- );
- const selectedToolIds = getVisitorVisibleGrantedToolIds(shareConfig.toolGrants);
-
- // Two buckets, extension-manager style: what visitors already get, then what
- // else could be granted. Toggling moves a tool between them, so the owner
- // reads the effective grant at a glance instead of scanning checkboxes.
- const enabledIds = candidateToolIds.filter((toolId) => selectedToolIds.includes(toolId));
- const availableIds = candidateToolIds.filter((toolId) => !enabledIds.includes(toolId));
-
- const renderTool = (toolId: string, selected: boolean) => (
- <ToolRow
- agentId={agentId}
- key={toolId}
- selected={selected}
- shareConfig={shareConfig}
- toolId={toolId}
- onChange={onChange}
- />
- );
-
- return (
- <Section desc={t('share.settings.tools.desc')} title={t('share.settings.tools.title')}>
- {candidateToolIds.length === 0 ? (
- <Text fontSize={12} type={'secondary'}>
- {t('share.settings.tools.empty')}
- </Text>
- ) : (
- <Flexbox gap={16}>
- <Flexbox gap={8}>
- <Text fontSize={12} type={'secondary'}>
- {t('share.settings.tools.grantedGroup', { count: enabledIds.length })}
- </Text>
- {enabledIds.length === 0 ? (
- <Text fontSize={12} type={'secondary'}>
- {t('share.settings.tools.grantedEmpty')}
- </Text>
- ) : (
- <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>
- {enabledIds.map((toolId) => renderTool(toolId, true))}
- </Flexbox>
- )}
- </Flexbox>
- {availableIds.length > 0 && (
- <Flexbox gap={8}>
- <Text fontSize={12} type={'secondary'}>
- {t('share.settings.tools.availableGroup', { count: availableIds.length })}
- </Text>
- <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>
- {availableIds.map((toolId) => renderTool(toolId, false))}
- </Flexbox>
- </Flexbox>
- )}
- </Flexbox>
- )}
- </Section>
- );
-});
-
-ToolsSection.displayName = 'AgentShareToolsSection';
-
-export default ToolsSection;
diff --git a/src/features/AgentShareSettings/UsageSection.tsx b/src/features/AgentShareSettings/UsageSection.tsx
deleted file mode 100644
index c7f4d410e2d..00000000000
--- a/src/features/AgentShareSettings/UsageSection.tsx
+++ /dev/null
@@ -1,110 +0,0 @@
-'use client';
-
-import { Flexbox } from '@lobehub/ui';
-import { SkeletonText, Text } from '@lobehub/ui/base-ui';
-import { Progress } from 'antd';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import AsyncError from '@/components/AsyncError';
-import { formatPrice } from '@/utils/format';
-
-import { Section } from './SectionLayout';
-import { useShareUsage } from './useShareUsage';
-
-interface StatProps {
- label: string;
- value: number;
-}
-
-const Stat = memo<StatProps>(({ label, value }) => (
- <Flexbox flex={1} gap={2}>
- <Text fontSize={20} weight={600}>
- {value}
- </Text>
- <Text fontSize={12} type={'secondary'}>
- {label}
- </Text>
- </Flexbox>
-));
-
-Stat.displayName = 'AgentShareUsageStat';
-
-interface UsageSectionProps {
- agentId: string;
- /** Live configured cap from the share-status cache; see `useShareUsage`. */
- monthlySpendLimit?: number;
-}
-
-/**
- * Read-only roll-up of what a share has actually cost and attracted: page
- * views, distinct visitors, visitor conversations, and this month's spend
- * against the cap configured in `LimitsSection`.
- *
- * Aggregates only — the creator's visibility into individual visitor
- * CONVERSATIONS stays governed by `allowCreatorViewSessions`, which these
- * counts deliberately do not bypass.
- */
-const UsageSection = memo<UsageSectionProps>(({ agentId, monthlySpendLimit }) => {
- const { t } = useTranslation('agent');
-
- const { data, error, hasLoadError, isLoading, isValidating, limit, mutate, spend } =
- useShareUsage(agentId, monthlySpendLimit);
-
- return (
- <Section desc={t('share.settings.usage.desc')} title={t('share.settings.usage.title')}>
- {isLoading ? (
- <SkeletonText rows={2} />
- ) : hasLoadError ? (
- <AsyncError
- error={error}
- retrying={isValidating}
- title={t('share.settings.usage.loadFailed')}
- variant={'inline'}
- onRetry={() => void mutate()}
- />
- ) : (
- <Flexbox gap={16}>
- <Flexbox horizontal gap={16}>
- <Stat label={t('share.settings.usage.views')} value={data?.userViewCount ?? 0} />
- <Stat label={t('share.settings.usage.visitors')} value={data?.visitorCount ?? 0} />
- <Stat label={t('share.settings.usage.conversations')} value={data?.topicCount ?? 0} />
- </Flexbox>
- {/* `null` means this deployment does not meter share spend — show
- nothing rather than a misleading $0. */}
- {spend !== null && (
- <Flexbox gap={4}>
- <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>
- <Text fontSize={12} type={'secondary'}>
- {t('share.settings.usage.monthlySpend')}
- </Text>
- <Text fontSize={12}>
- {limit === undefined
- ? formatPrice(spend)
- : t('share.settings.usage.spendOfLimit', {
- limit: formatPrice(limit),
- spend: formatPrice(spend),
- })}
- </Text>
- </Flexbox>
- {limit !== undefined && (
- <Progress
- // A `0` cap ("stop all visitor runs") is special-cased so the
- // progress computation never divides by it.
- percent={limit === 0 ? 100 : Math.min(100, Math.round((spend / limit) * 100))}
- showInfo={false}
- size={'small'}
- status={spend >= limit ? 'exception' : 'normal'}
- />
- )}
- </Flexbox>
- )}
- </Flexbox>
- )}
- </Section>
- );
-});
-
-UsageSection.displayName = 'AgentShareUsageSection';
-
-export default UsageSection;
diff --git a/src/features/AgentShareSettings/shareConfigPatch.test.ts b/src/features/AgentShareSettings/shareConfigPatch.test.ts
deleted file mode 100644
index f575ee99239..00000000000
--- a/src/features/AgentShareSettings/shareConfigPatch.test.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import { mergeShareConfig } from './shareConfigPatch';
-
-describe('mergeShareConfig', () => {
- const base = {
- allowReadMemory: false,
- toolGrants: [{ identifier: 'a' }],
- maxTopicsPerVisitor: 5,
- maxTurnsPerTopic: 20,
- monthlySpendLimit: 10,
- };
-
- it('overwrites only the patched keys', () => {
- expect(mergeShareConfig(base, { maxTurnsPerTopic: 30 })).toEqual({
- ...base,
- maxTurnsPerTopic: 30,
- });
- });
-
- it('overwrites the spend cap with a zero cap, mirroring the server jsonb merge', () => {
- const merged = mergeShareConfig(base, { monthlySpendLimit: 0 });
-
- expect(merged.monthlySpendLimit).toBe(0);
- expect(merged.maxTopicsPerVisitor).toBe(5);
- });
-
- it('does not mutate the base', () => {
- mergeShareConfig(base, { toolGrants: [{ identifier: 'a' }, { identifier: 'b' }] });
-
- expect(base.toolGrants).toEqual([{ identifier: 'a' }]);
- });
-});
diff --git a/src/features/AgentShareSettings/shareConfigPatch.ts b/src/features/AgentShareSettings/shareConfigPatch.ts
deleted file mode 100644
index 7fa74abfcf1..00000000000
--- a/src/features/AgentShareSettings/shareConfigPatch.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import type { AgentShareConfigPatchInput } from '@/services/agentShare';
-
-import type { AgentShareConfigState } from './useAgentShare';
-
-/**
- * Client-side mirror of `AgentShareModel.updateConfig`'s jsonb merge: a key
- * present in the patch overwrites the base value, and an `undefined` value is
- * "not part of this patch" — the server skips it, so the base value stands.
- *
- * Used to keep a local copy of the config in step with writes that are still
- * in flight, so a second edit composes on top of the first instead of being
- * derived from a snapshot the server has already moved past.
- */
-export const mergeShareConfig = (
- base: AgentShareConfigState,
- patch: AgentShareConfigPatchInput,
-): AgentShareConfigState => {
- const patched = Object.entries(patch).filter(([, value]) => value !== undefined);
-
- return Object.assign({ ...base }, Object.fromEntries(patched));
-};
diff --git a/src/features/AgentShareSettings/shareLink.test.ts b/src/features/AgentShareSettings/shareLink.test.ts
deleted file mode 100644
index 1ff99eff3ec..00000000000
--- a/src/features/AgentShareSettings/shareLink.test.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
-import { describe, expect, it } from 'vitest';
-
-import { buildAgentShareUrl, normalizeAgentShareSlug, validateAgentShareSlug } from './shareLink';
-
-describe('normalizeAgentShareSlug', () => {
- it('trims and lowercases', () => {
- expect(normalizeAgentShareSlug(' My-Bot ')).toBe('my-bot');
- });
-});
-
-describe('validateAgentShareSlug', () => {
- it('accepts a well-formed slug', () => {
- expect(validateAgentShareSlug('my-cool-bot')).toBeNull();
- expect(validateAgentShareSlug('abc')).toBeNull();
- expect(validateAgentShareSlug('a1b')).toBeNull();
- });
-
- it('rejects slugs shorter than 3 or longer than 64 characters', () => {
- expect(validateAgentShareSlug('ab')).toBe('tooShort');
- expect(validateAgentShareSlug('a'.repeat(65))).toBe('tooLong');
- expect(validateAgentShareSlug('a'.repeat(64))).toBeNull();
- });
-
- it('rejects uppercase, underscores, spaces and edge hyphens', () => {
- expect(validateAgentShareSlug('My-Bot')).toBe('invalid');
- expect(validateAgentShareSlug('my_bot')).toBe('invalid');
- expect(validateAgentShareSlug('my bot')).toBe('invalid');
- expect(validateAgentShareSlug('-mybot')).toBe('invalid');
- expect(validateAgentShareSlug('mybot-')).toBe('invalid');
- });
-
- it('rejects UUID-shaped slugs, which would never resolve as a slug', () => {
- expect(validateAgentShareSlug('123e4567-e89b-12d3-a456-426614174000')).toBe('invalid');
- });
-
- it('rejects reserved words', () => {
- expect(validateAgentShareSlug('settings')).toBe('reserved');
- expect(validateAgentShareSlug('share')).toBe('reserved');
- });
-
- // Legacy `/agent/<slug>` share links are still resolved through the agent
- // route, where the creator's own agents win the lookup — so a share on a
- // builtin slug would be unreachable from such a link.
- it('rejects every builtin agent slug', () => {
- for (const slug of Object.values(BUILTIN_AGENT_SLUGS)) {
- expect([slug, validateAgentShareSlug(slug)]).toEqual([slug, 'reserved']);
- }
- });
-});
-
-describe('buildAgentShareUrl', () => {
- const origin = 'https://app.lobehub.com';
-
- it('prefers the custom slug', () => {
- expect(buildAgentShareUrl({ origin, shareId: 'share-id', slug: 'my-bot' })).toBe(
- 'https://app.lobehub.com/a/my-bot',
- );
- });
-
- it('falls back to the share id', () => {
- expect(buildAgentShareUrl({ origin, shareId: 'share-id' })).toBe(
- 'https://app.lobehub.com/a/share-id',
- );
- expect(buildAgentShareUrl({ origin, shareId: 'share-id', slug: '' })).toBe(
- 'https://app.lobehub.com/a/share-id',
- );
- });
-});
diff --git a/src/features/AgentShareSettings/shareLink.ts b/src/features/AgentShareSettings/shareLink.ts
deleted file mode 100644
index 54956f648b1..00000000000
--- a/src/features/AgentShareSettings/shareLink.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { AGENT_SHARE_SLUG_PATTERN, RESERVED_AGENT_SHARE_SLUGS } from '@lobechat/const';
-
-import { buildAgentShareVisitorPath } from '@/features/AgentShareVisitor/visitorPath';
-
-/**
- * Client mirror of `AgentShareModel.updateSlug`'s UUID rejection: a
- * UUID-shaped slug would be unreachable because `findBySlugOrId` resolves
- * UUID-shaped input as a share id before ever trying the slug lookup.
- */
-const UUID_PATTERN = /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i;
-
-export type AgentShareSlugError = 'invalid' | 'reserved' | 'tooLong' | 'tooShort';
-
-/** Slugs are stored lowercase; normalize before validating so the check matches the server's. */
-export const normalizeAgentShareSlug = (input: string): string => input.trim().toLowerCase();
-
-/**
- * Client-side mirror of the server's slug rules (`AGENT_SHARE_SLUG_PATTERN` +
- * `RESERVED_AGENT_SHARE_SLUGS` + the UUID guard). The server remains the real
- * gate — this only turns an obviously-invalid slug into inline feedback
- * instead of a round trip. Uniqueness cannot be checked here; a taken slug
- * still comes back as `CONFLICT`.
- *
- * Returns `null` when the normalized slug is acceptable.
- */
-export const validateAgentShareSlug = (slug: string): AgentShareSlugError | null => {
- if (slug.length < 3) return 'tooShort';
- if (slug.length > 64) return 'tooLong';
- if (!AGENT_SHARE_SLUG_PATTERN.test(slug) || UUID_PATTERN.test(slug)) return 'invalid';
- if (RESERVED_AGENT_SHARE_SLUGS.includes(slug)) return 'reserved';
-
- return null;
-};
-
-/**
- * Visitor URL for a share. The custom slug is preferred when set, but the raw
- * share id always resolves too — so a link handed out before a slug was chosen
- * keeps working.
- */
-export const buildAgentShareUrl = ({
- origin,
- shareId,
- slug,
-}: {
- origin: string;
- shareId: string;
- slug?: string;
-}): string => `${origin}${buildAgentShareVisitorPath(slug || shareId)}`;
diff --git a/src/features/AgentShareSettings/toolVisitorAvailability.test.ts b/src/features/AgentShareSettings/toolVisitorAvailability.test.ts
deleted file mode 100644
index fac3f768209..00000000000
--- a/src/features/AgentShareSettings/toolVisitorAvailability.test.ts
+++ /dev/null
@@ -1,265 +0,0 @@
-import { AgentDocumentsIdentifier } from '@lobechat/builtin-tool-agent-documents';
-import { KnowledgeBaseIdentifier } from '@lobechat/builtin-tool-knowledge-base';
-import { LobeAgentApiName, LobeAgentIdentifier } from '@lobechat/builtin-tool-lobe-agent';
-import { MemoryApiName, MemoryIdentifier } from '@lobechat/builtin-tool-memory';
-import { describe, expect, it } from 'vitest';
-
-import {
- getShareApiAvailability,
- getShareToolAvailability,
- getVisitorVisibleGrantedToolIds,
- runtimeManagedShareCandidateToolIds,
- setShareToolGrant,
- sortBlockedLast,
- toggleShareToolApi,
- toggleShareToolsetGrant,
-} from './toolVisitorAvailability';
-
-describe('getShareToolAvailability', () => {
- it('blocks builtins the server gate refuses outright', () => {
- // Both survive the master allowlist only to be blocked by
- // DATA_TOOL_ACCESS_RULES' unconditional `none` grant.
- expect(getShareToolAvailability(KnowledgeBaseIdentifier)).toBe('blocked');
- expect(getShareToolAvailability(AgentDocumentsIdentifier)).toBe('blocked');
- });
-
- it('blocks builtins outside the master allowlist', () => {
- expect(getShareToolAvailability('lobe-local-system')).toBe('blocked');
- // lobe-cloud-sandbox is now allowlisted: a share visitor's run gets its
- // own isolated per-topic sandbox session with no `lh` CLI JWT shim, so
- // it no longer belongs in the "blocked" bucket.
- expect(getShareToolAvailability('lobe-cloud-sandbox')).toBe('available');
- });
-
- it('leaves non-builtin identifiers to the owner picker', () => {
- expect(getShareToolAvailability('mcp-github')).toBe('available');
- });
-
- it('flags memory as inert until the read-memory permission is on', () => {
- expect(getShareToolAvailability(MemoryIdentifier)).toBe('needsMemoryPermission');
- expect(getShareToolAvailability(MemoryIdentifier, { allowReadMemory: true })).toBe('available');
- });
-});
-
-describe('runtimeManagedShareCandidateToolIds', () => {
- it('never suggests a tool the gate always blocks', () => {
- expect(runtimeManagedShareCandidateToolIds).not.toContain(KnowledgeBaseIdentifier);
- expect(runtimeManagedShareCandidateToolIds).not.toContain('lobe-local-system');
- });
-});
-
-describe('sortBlockedLast', () => {
- const isBlocked = (id: string) => id.startsWith('blocked-');
-
- // Stability matters: the grantable chips/APIs must stay in the order the
- // owner configured them (or the manifest declares them), not be reshuffled
- // just because a blocked one sat between them.
- it('moves blocked items last while keeping the order inside each group', () => {
- expect(sortBlockedLast(['a', 'blocked-1', 'b', 'blocked-2', 'c'], isBlocked)).toEqual([
- 'a',
- 'b',
- 'c',
- 'blocked-1',
- 'blocked-2',
- ]);
- });
-
- it('returns an empty list untouched', () => {
- expect(sortBlockedLast([], isBlocked)).toEqual([]);
- });
-
- it('keeps the original order when every item is blocked', () => {
- expect(sortBlockedLast(['blocked-1', 'blocked-2'], isBlocked)).toEqual([
- 'blocked-1',
- 'blocked-2',
- ]);
- });
-});
-
-describe('getVisitorVisibleGrantedToolIds', () => {
- it('hides persisted grants the gate can never honor', () => {
- expect(
- getVisitorVisibleGrantedToolIds([
- { identifier: 'mcp-github' },
- { identifier: KnowledgeBaseIdentifier },
- { identifier: 'lobe-local-system' },
- ]),
- ).toEqual(['mcp-github']);
- });
-
- it('tolerates an unset grant list', () => {
- expect(getVisitorVisibleGrantedToolIds(undefined)).toEqual([]);
- });
-
- it('renders one identifier for a toolset granted only per-API', () => {
- expect(
- getVisitorVisibleGrantedToolIds([
- {
- apis: [LobeAgentApiName.analyzeMedia, LobeAgentApiName.updatePlan],
- identifier: LobeAgentIdentifier,
- },
- ]),
- ).toEqual([LobeAgentIdentifier]);
- });
-});
-
-describe('setShareToolGrant', () => {
- it('writes an `apis`-less entry for "all"', () => {
- expect(setShareToolGrant([{ identifier: 'calculator' }], LobeAgentIdentifier, 'all')).toEqual([
- { identifier: 'calculator' },
- { identifier: LobeAgentIdentifier },
- ]);
- });
-
- it('writes one `apis`-scoped entry for an array grant', () => {
- expect(
- setShareToolGrant(undefined, LobeAgentIdentifier, [LobeAgentApiName.analyzeMedia]),
- ).toEqual([{ apis: [LobeAgentApiName.analyzeMedia], identifier: LobeAgentIdentifier }]);
- });
-
- it('drops the identifier entirely on "none"', () => {
- const stored = [
- { apis: [LobeAgentApiName.analyzeMedia], identifier: LobeAgentIdentifier },
- { identifier: 'calculator' },
- ];
-
- expect(setShareToolGrant(stored, LobeAgentIdentifier, 'none')).toEqual([
- { identifier: 'calculator' },
- ]);
- });
-
- it('replaces a prior grant for the same identifier rather than accumulating', () => {
- const stored = [{ apis: [LobeAgentApiName.analyzeMedia], identifier: LobeAgentIdentifier }];
-
- expect(setShareToolGrant(stored, LobeAgentIdentifier, 'all')).toEqual([
- { identifier: LobeAgentIdentifier },
- ]);
- });
-});
-
-describe('toggleShareToolsetGrant', () => {
- it('grants everything when the identifier has no grant yet', () => {
- expect(toggleShareToolsetGrant(undefined, LobeAgentIdentifier)).toEqual([
- { identifier: LobeAgentIdentifier },
- ]);
- });
-
- it('grants everything when only a partial per-API grant exists', () => {
- const stored = [{ apis: [LobeAgentApiName.analyzeMedia], identifier: LobeAgentIdentifier }];
-
- expect(toggleShareToolsetGrant(stored, LobeAgentIdentifier)).toEqual([
- { identifier: LobeAgentIdentifier },
- ]);
- });
-
- it('revokes entirely when every API is already granted', () => {
- expect(
- toggleShareToolsetGrant([{ identifier: LobeAgentIdentifier }], LobeAgentIdentifier),
- ).toEqual([]);
- });
-
- it('leaves grants for other identifiers untouched', () => {
- const stored = [
- { apis: [LobeAgentApiName.analyzeMedia], identifier: LobeAgentIdentifier },
- { identifier: 'calculator' },
- ];
-
- expect(toggleShareToolsetGrant(stored, LobeAgentIdentifier)).toEqual([
- { identifier: 'calculator' },
- { identifier: LobeAgentIdentifier },
- ]);
- });
-});
-
-describe('toggleShareToolApi', () => {
- const available = [LobeAgentApiName.analyzeMedia, LobeAgentApiName.updatePlan];
-
- it('adds the first per-API grant for an ungranted identifier', () => {
- expect(
- toggleShareToolApi(undefined, LobeAgentIdentifier, LobeAgentApiName.analyzeMedia, available),
- ).toEqual([{ apis: [LobeAgentApiName.analyzeMedia], identifier: LobeAgentIdentifier }]);
- });
-
- it('expands a toolset-level grant, then narrows it by the toggled API', () => {
- // Toggling one API off a toolset-level ("all") grant must narrow to the
- // REST of the available APIs, not wipe the whole grant.
- expect(
- toggleShareToolApi(
- [{ identifier: LobeAgentIdentifier }],
- LobeAgentIdentifier,
- LobeAgentApiName.analyzeMedia,
- available,
- ),
- ).toEqual([{ apis: [LobeAgentApiName.updatePlan], identifier: LobeAgentIdentifier }]);
- });
-
- it('stays an explicit `apis` list once every available API is individually selected, rather than collapsing to a toolset-level grant', () => {
- // Least privilege: an `apis`-less entry also grants any API added to this
- // tool LATER (e.g. a plugin update) that the owner never reviewed. Only
- // the toolset chip (`toggleShareToolsetGrant`) may write `'all'`.
- const stored = [{ apis: [LobeAgentApiName.analyzeMedia], identifier: LobeAgentIdentifier }];
-
- expect(
- toggleShareToolApi(stored, LobeAgentIdentifier, LobeAgentApiName.updatePlan, available),
- ).toEqual([
- {
- apis: expect.arrayContaining([LobeAgentApiName.analyzeMedia, LobeAgentApiName.updatePlan]),
- identifier: LobeAgentIdentifier,
- },
- ]);
- });
-
- it('removes the grant entirely once the last selected API is toggled off', () => {
- const stored = [{ apis: [LobeAgentApiName.analyzeMedia], identifier: LobeAgentIdentifier }];
-
- expect(
- toggleShareToolApi(stored, LobeAgentIdentifier, LobeAgentApiName.analyzeMedia, available),
- ).toEqual([]);
- });
-});
-
-describe('getShareApiAvailability', () => {
- it('blocks callSubAgent on lobe-agent unconditionally', () => {
- expect(getShareApiAvailability(LobeAgentIdentifier, LobeAgentApiName.callSubAgent)).toBe(
- 'blocked',
- );
- });
-
- it("blocks a 'required'/'always' humanIntervention API", () => {
- expect(
- getShareApiAvailability(LobeAgentIdentifier, LobeAgentApiName.createPlan, 'required'),
- ).toBe('blocked');
- expect(
- getShareApiAvailability(LobeAgentIdentifier, LobeAgentApiName.askUserQuestion, 'always'),
- ).toBe('blocked');
- });
-
- it('allows an API with no (or "never") humanIntervention', () => {
- expect(getShareApiAvailability(LobeAgentIdentifier, LobeAgentApiName.analyzeMedia)).toBe(
- 'available',
- );
- expect(getShareApiAvailability(LobeAgentIdentifier, LobeAgentApiName.updatePlan, 'never')).toBe(
- 'available',
- );
- });
-
- // A share grant is read-only at most: the server gate strips every memory
- // write API regardless of what the owner ticked, so the picker must not
- // offer them (regression: owners granted only write APIs and saw no memory
- // tool on the visitor side at all).
- it('reports memory write APIs as writesOwnerData, keeps read APIs available', () => {
- for (const apiName of [
- MemoryApiName.addPreferenceMemory,
- MemoryApiName.updateIdentityMemory,
- MemoryApiName.removeIdentityMemory,
- ]) {
- expect(getShareApiAvailability(MemoryIdentifier, apiName)).toBe('writesOwnerData');
- }
- expect(getShareApiAvailability(MemoryIdentifier, MemoryApiName.searchUserMemory)).toBe(
- 'available',
- );
- expect(getShareApiAvailability(MemoryIdentifier, MemoryApiName.queryTaxonomyOptions)).toBe(
- 'available',
- );
- });
-});
diff --git a/src/features/AgentShareSettings/toolVisitorAvailability.ts b/src/features/AgentShareSettings/toolVisitorAvailability.ts
deleted file mode 100644
index c1a3f9d0e5f..00000000000
--- a/src/features/AgentShareSettings/toolVisitorAvailability.ts
+++ /dev/null
@@ -1,259 +0,0 @@
-import { LobeAgentApiName, LobeAgentIdentifier } from '@lobechat/builtin-tool-lobe-agent';
-import { MEMORY_WRITE_API_NAMES, MemoryIdentifier } from '@lobechat/builtin-tool-memory';
-import {
- AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS,
- isAgentShareAllowedBuiltinIdentifier,
- runtimeManagedToolIds,
-} from '@lobechat/builtin-tools';
-import { resolveShareToolGrants, type ShareToolGrant } from '@lobechat/const';
-import type { AgentShareToolGrant, ExtendedHumanInterventionConfig } from '@lobechat/types';
-
-/**
- * How a tool the owner configured on the agent relates to a share visitor's run:
- *
- * - `available` — the owner can grant it and the server gate will honor it.
- * - `blocked` — the server refuses it for visitor runs no matter what is
- * stored, so the owner must not be offered the toggle at all.
- * - `needsMemoryPermission` — the server gate would strip it until the
- * separate "allow reading my memory" permission is on, so the picker keeps
- * the row disabled (with that explanation) rather than accepting a grant
- * that cannot take effect yet.
- */
-export type ShareToolAvailability = 'available' | 'blocked' | 'needsMemoryPermission';
-
-/**
- * Mirrors the two server-side gates a visitor tool call passes, in the same
- * order `isShareBlockedDataToolCall` applies them
- * (`apps/server/src/services/aiAgent/shareGate.ts`):
- *
- * 1. `isAgentShareAllowedBuiltinIdentifier` — the master default-deny
- * allowlist. Non-builtin identifiers (MCP servers, market plugins, custom
- * plugins) fall outside its jurisdiction entirely and are governed only by
- * the owner's `toolGrants` picker.
- * 2. `AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS` — tools that survive the
- * allowlist only to be blocked outright by `DATA_TOOL_ACCESS_RULES`, whose
- * grant is unconditionally `none` (knowledge base, agent documents: no such
- * grant exists in `AgentShareConfig` at all).
- *
- * Both sets are exported from `@lobechat/builtin-tools` precisely so this
- * picker reads the same source the gate enforces instead of hand-copying
- * identifiers that could drift.
- */
-export const getShareToolAvailability = (
- toolId: string,
- permissions: { allowReadMemory?: boolean } = {},
-): ShareToolAvailability => {
- if (!isAgentShareAllowedBuiltinIdentifier(toolId)) return 'blocked';
- if (AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS.has(toolId)) return 'blocked';
- if (toolId === MemoryIdentifier && !permissions.allowReadMemory) return 'needsMemoryPermission';
-
- return 'available';
-};
-
-/** Whether the owner may grant `toolId` to visitors at all (see {@link getShareToolAvailability}). */
-export const isToolAvailableToVisitors = (toolId: string): boolean =>
- getShareToolAvailability(toolId) !== 'blocked';
-
-/**
- * `shareConfig.toolGrants` reduced down to the toolset identifiers that should
- * render as an active visitor grant — one entry per identifier, whether it
- * grants every API or only some (see {@link resolveShareToolGrants}). A share
- * edited while a since-denied builtin was still allowed may keep a now-blocked
- * identifier persisted; rendering it as selected would confirm a grant no
- * visitor run can use.
- *
- * PRESENTATION ONLY. Never build a save payload from this — see
- * {@link toggleShareToolsetGrant} / {@link toggleShareToolApi}, which compose
- * over the FULL persisted list so grants this picker does not render survive
- * the write.
- */
-export const getVisitorVisibleGrantedToolIds = (
- toolGrants: AgentShareToolGrant[] | undefined,
-): string[] =>
- Array.from(resolveShareToolGrants(toolGrants).keys()).filter((identifier) =>
- isToolAvailableToVisitors(identifier),
- );
-
-/**
- * Replace `identifier`'s grant in the PERSISTED list with `grant`: `'all'`
- * writes an entry with no `apis`, an array of API names writes an entry
- * scoped to them, and `'none'` drops the identifier's entry entirely. Always
- * composes over the FULL stored list, same reasoning as
- * {@link toggleShareToolsetGrant} — grants for OTHER identifiers this picker
- * does not render must survive the write.
- */
-export const setShareToolGrant = (
- toolGrants: AgentShareToolGrant[] | undefined,
- identifier: string,
- grant: 'all' | 'none' | string[],
-): AgentShareToolGrant[] => {
- const withoutIdentifier = (toolGrants ?? []).filter((entry) => entry.identifier !== identifier);
-
- if (grant === 'none') return withoutIdentifier;
- if (grant === 'all') return [...withoutIdentifier, { identifier }];
-
- return [...withoutIdentifier, { apis: grant, identifier }];
-};
-
-/**
- * Toggle `identifier`'s TOOLSET-level chip. The click cycle is the mature
- * checkbox convention (antd `indeterminate`, Gmail's select-all): none -> all,
- * partial -> all, all -> none. A partial per-API grant therefore always widens
- * to the full toolset on the first click rather than clearing, so one click is
- * never silently destructive of an intent the owner has to rebuild per API.
- *
- * The chip renders the matching tri-state: no grant -> empty box, partial ->
- * indeterminate (minus) box, every API -> checked box.
- */
-export const toggleShareToolsetGrant = (
- toolGrants: AgentShareToolGrant[] | undefined,
- identifier: string,
-): AgentShareToolGrant[] =>
- resolveShareToolGrants(toolGrants).get(identifier) === 'all'
- ? setShareToolGrant(toolGrants, identifier, 'none')
- : setShareToolGrant(toolGrants, identifier, 'all');
-
-/**
- * Toggle a single `apiName` within `identifier`'s grant, expanding a
- * toolset-level `'all'` grant into its `availableApiNames` first so removing
- * one API narrows to the rest instead of wiping the whole grant.
- * `availableApiNames` must be the identifier's full set of visitor-grantable
- * API names (i.e. excluding ones {@link getShareApiAvailability} reports as
- * `blocked`) — the caller (which already has the manifest) is the only place
- * that set is known.
- *
- * Deliberately does NOT collapse back to a toolset-level `'all'` grant when
- * every currently-available API ends up individually ticked — least
- * privilege: a grant without `apis` also covers any API added to this tool
- * LATER (e.g. a plugin update), which the owner never explicitly reviewed.
- * Only the toolset chip / {@link toggleShareToolsetGrant} writes `'all'`.
- * Still collapses to `'none'` (dropping the identifier entirely) when no API
- * remains selected, so the toolset row's tri-state stays consistent with
- * per-API toggling.
- */
-export const toggleShareToolApi = (
- toolGrants: AgentShareToolGrant[] | undefined,
- identifier: string,
- apiName: string,
- availableApiNames: string[],
-): AgentShareToolGrant[] => {
- const grant = resolveShareToolGrants(toolGrants).get(identifier);
- const current = new Set(grant === 'all' ? availableApiNames : grant instanceof Set ? grant : []);
-
- if (current.has(apiName)) current.delete(apiName);
- else current.add(apiName);
-
- if (current.size === 0) return setShareToolGrant(toolGrants, identifier, 'none');
-
- return setShareToolGrant(toolGrants, identifier, Array.from(current));
-};
-
-/**
- * How one API of an ALREADY-visitor-available toolset relates to a share
- * visitor's run — the per-API counterpart of {@link getShareToolAvailability}.
- * Only meaningful for an identifier that is not itself `blocked` at the
- * toolset level; callers render every API of a blocked toolset as blocked
- * without consulting this.
- *
- * Mirrors two of the server's dispatch-time checks
- * (`isShareBlockedBuiltinDispatch` in `shareGate.ts`) cheaply enough to run in
- * the picker without duplicating server-only rules:
- *
- * 1. `humanIntervention` — every share run is forced onto headless approval,
- * so a `'required'`/`'always'` policy API can never honestly complete (see
- * `isApiUsableForShareVisitor`'s doc in `shareGate.ts`).
- * 2. `callSubAgent` on `lobe-agent` — sub-agent dispatch is unconditionally
- * stripped for share visitors regardless of any grant.
- *
- * 3. Memory write APIs — `DATA_TOOL_ACCESS_RULES` strips them from every
- * visitor run regardless of grant (a share grant is read-only at most).
- * Read from the same `MEMORY_WRITE_API_NAMES` the gate uses, so a new
- * write API cannot be added on one side without the other following.
- *
- * Returns `writesOwnerData` (rather than plain `blocked`) for that last case
- * so the picker can explain *why* instead of showing a generic refusal.
- */
-export type ShareApiAvailability = 'available' | 'blocked' | 'writesOwnerData';
-
-export const getShareApiAvailability = (
- identifier: string,
- apiName: string,
- humanIntervention?: ExtendedHumanInterventionConfig,
-): ShareApiAvailability => {
- if (identifier === LobeAgentIdentifier && apiName === LobeAgentApiName.callSubAgent) {
- return 'blocked';
- }
- if (identifier === MemoryIdentifier && MEMORY_WRITE_API_NAMES.has(apiName as never)) {
- return 'writesOwnerData';
- }
- if (humanIntervention !== undefined && humanIntervention !== 'never') return 'blocked';
-
- return 'available';
-};
-
-/** Re-exported so callers building a toolset's tri-state can type against it without importing `@lobechat/const` directly. */
-export type { ShareToolGrant };
-
-/**
- * `identifier`'s resolved grant from the PERSISTED list: `'all'` for a grant
- * without `apis`, a `Set` of API names for an `apis`-scoped grant, or
- * `undefined` when the identifier has no grant at all. Drives the toolset
- * row's tri-state checkbox and which per-API checkboxes render checked once
- * expanded.
- */
-export const getShareToolGrantForIdentifier = (
- toolGrants: AgentShareToolGrant[] | undefined,
- identifier: string,
-): ShareToolGrant | undefined => resolveShareToolGrants(toolGrants).get(identifier);
-
-/**
- * Runtime-managed builtin tool identifiers (Knowledge Base, Memory, Web
- * Browsing, ...) that the server's agent mode rules can enable on a run
- * independently of `agentConfig.plugins`. `getActivePluginIds` only reflects
- * the owner's plugin selection, so a picker built from that list alone could
- * never surface these ids — and `applyShareGateToToolSet` strips any tool id
- * absent from `toolGrants`, so e.g. the "allow reading memory" switch
- * would silently have no effect.
- *
- * Filtered through {@link isToolAvailableToVisitors} so tools the gate always
- * refuses (device, local system, sandbox, knowledge base, agent documents)
- * stay out of the picker instead of adding rows the owner cannot act on.
- */
-export const runtimeManagedShareCandidateToolIds: string[] = runtimeManagedToolIds.filter(
- (toolId) => isToolAvailableToVisitors(toolId),
-);
-
-/**
- * Full candidate set for the share tool picker: the owner's configured
- * plugins plus the runtime-managed builtin tools a share can ever grant.
- * Deduplicated because a runtime-managed tool id may already be pinned in
- * `pluginIds` (e.g. image generation).
- *
- * An always-blocked tool the owner explicitly configured on the agent is still
- * listed — rendered disabled with an explanation, so the owner learns why it
- * cannot be shared instead of wondering where it went. Blocked tools are only
- * omitted when they would have been added by
- * {@link runtimeManagedShareCandidateToolIds}, i.e. when the owner never
- * picked them in the first place.
- */
-export const getShareToolCandidateIds = (pluginIds: string[]): string[] =>
- Array.from(new Set([...pluginIds, ...runtimeManagedShareCandidateToolIds]));
-
-/**
- * Stable partition that moves every item `isBlocked` accepts to the END of the
- * list, keeping the original (manifest / configuration) order inside each
- * group.
- *
- * Presentation only, and the reason is UX rather than logic: a control the
- * owner can never tick is information, not an action. Interleaved with the
- * grantable ones it reads as a broken checkbox and forces the owner to re-check
- * every row before trusting the list; collected at the end — still rendered,
- * greyed out, with the refusal explained in its tooltip — the actionable set
- * stays scannable while the "why is this missing?" answer remains one hover
- * away. Used at both levels of the picker (toolset chips and the per-API
- * popover) so the two behave identically.
- */
-export const sortBlockedLast = <T>(items: T[], isBlocked: (item: T) => boolean): T[] => [
- ...items.filter((item) => !isBlocked(item)),
- ...items.filter((item) => isBlocked(item)),
-];
diff --git a/src/features/AgentShareSettings/useAgentShare.test.ts b/src/features/AgentShareSettings/useAgentShare.test.ts
deleted file mode 100644
index bf93fe13477..00000000000
--- a/src/features/AgentShareSettings/useAgentShare.test.ts
+++ /dev/null
@@ -1,642 +0,0 @@
-/**
- * @vitest-environment happy-dom
- */
-import { act, renderHook, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { useAgentShare } from './useAgentShare';
-
-const swr = vi.hoisted(() => {
- const listeners = new Set<() => void>();
- const state = { data: undefined as any, error: undefined as any };
-
- return {
- listeners,
- seed(data: any) {
- state.data = data;
- state.error = undefined;
- },
- seedError(error: any) {
- state.data = undefined;
- state.error = error;
- },
- set(data: any) {
- state.data = data;
- state.error = undefined;
- for (const listener of listeners) listener();
- },
- state,
- };
-});
-
-// Stand-in for `useSWR` that keeps the cached row in module scope and
-// re-renders subscribers on `mutate`, so the hook's optimistic writes and the
-// idle re-sync effect behave as they do in the app.
-vi.mock('swr', async () => {
- const React = await import('react');
-
- return {
- default: () => {
- const [, force] = React.useState(0);
-
- React.useEffect(() => {
- const listener = () => force((version) => version + 1);
- swr.listeners.add(listener);
- return () => {
- swr.listeners.delete(listener);
- };
- }, []);
-
- return {
- data: swr.state.data,
- error: swr.state.error,
- isLoading: false,
- mutate: async (input?: any) => {
- // Bare `mutate()` revalidates: re-read through the (mocked) fetcher.
- if (input === undefined) {
- const fresh = await service.getShareStatus();
- if (fresh !== undefined) swr.set(fresh);
- return swr.state.data;
- }
- swr.set(typeof input === 'function' ? input(swr.state.data) : input);
- return swr.state.data;
- },
- };
- },
- };
-});
-
-const service = vi.hoisted(() => ({
- disableShare: vi.fn(),
- enableShare: vi.fn(),
- getShareStatus: vi.fn(),
- updateShareConfig: vi.fn(),
- updateSlug: vi.fn(),
- updateVisibility: vi.fn(),
-}));
-
-vi.mock('@/services/agentShare', () => ({ agentShareService: service }));
-
-const buildShare = (config: Record<string, unknown> = {}) => ({
- id: 'share-1',
- shareConfig: {
- allowReadMemory: false,
- toolGrants: [],
- maxTopicsPerVisitor: 5,
- maxTurnsPerTopic: 20,
- ...config,
- },
- userViewCount: 0,
- visibility: 'link',
-});
-
-beforeEach(() => {
- vi.clearAllMocks();
- swr.seed(buildShare());
- service.updateShareConfig.mockImplementation(async (_agentId: string, patch: any) => ({
- ...buildShare(),
- shareConfig: { ...swr.state.data?.shareConfig, ...patch },
- }));
-});
-
-describe('useAgentShare · updateConfig', () => {
- it('composes consecutive functional patches instead of losing the first', async () => {
- // The first write stays in flight while the second is issued — the exact
- // window in which a payload built from the last rendered config would
- // overwrite the earlier toggle.
- let releaseFirst: (value: any) => void = () => {};
- service.updateShareConfig.mockImplementationOnce(
- (_agentId: string, patch: any) =>
- new Promise((resolve) => {
- releaseFirst = () =>
- resolve({ ...buildShare(), shareConfig: { ...buildShare().shareConfig, ...patch } });
- }),
- );
-
- const { result } = renderHook(() => useAgentShare('agent-1'));
-
- await act(async () => {
- void result.current.updateConfig((current) => ({
- toolGrants: [...(current.toolGrants ?? []), { identifier: 'tool-a' }],
- }));
- void result.current.updateConfig((current) => ({
- toolGrants: [...(current.toolGrants ?? []), { identifier: 'tool-b' }],
- }));
- });
-
- // Only the first request has been issued; the second is queued behind it.
- await waitFor(() => expect(service.updateShareConfig).toHaveBeenCalledTimes(1));
-
- await act(async () => {
- releaseFirst(undefined);
- });
-
- await waitFor(() => expect(service.updateShareConfig).toHaveBeenCalledTimes(2));
-
- expect(service.updateShareConfig.mock.calls[0][1]).toEqual({
- toolGrants: [{ identifier: 'tool-a' }],
- });
- expect(service.updateShareConfig.mock.calls[1][1]).toEqual({
- toolGrants: [{ identifier: 'tool-a' }, { identifier: 'tool-b' }],
- });
- });
-
- it('does not resend a failed write when a later queued write lands (happy-path contrast)', async () => {
- // Paired with the failure regression below: on the happy path, B's
- // outgoing payload still composes on top of A once A is confirmed to
- // have succeeded — the fix must not turn this into a diff-only send.
- let releaseFirst: (value: any) => void = () => {};
- service.updateShareConfig.mockImplementationOnce(
- (_agentId: string, patch: any) =>
- new Promise((resolve) => {
- releaseFirst = () =>
- resolve({ ...buildShare(), shareConfig: { ...buildShare().shareConfig, ...patch } });
- }),
- );
-
- const { result } = renderHook(() => useAgentShare('agent-1'));
-
- await act(async () => {
- void result.current.updateConfig((current) => ({
- toolGrants: [...(current.toolGrants ?? []), { identifier: 'tool-a' }],
- }));
- void result.current.updateConfig((current) => ({
- toolGrants: [...(current.toolGrants ?? []), { identifier: 'tool-b' }],
- }));
- });
-
- await waitFor(() => expect(service.updateShareConfig).toHaveBeenCalledTimes(1));
-
- await act(async () => {
- releaseFirst(undefined);
- });
-
- await waitFor(() => expect(service.updateShareConfig).toHaveBeenCalledTimes(2));
-
- expect(service.updateShareConfig.mock.calls[1][1]).toEqual({
- toolGrants: [{ identifier: 'tool-a' }, { identifier: 'tool-b' }],
- });
- });
-
- it("does not let A's failed write leak into B's outgoing payload", async () => {
- // A fails outright while B is already queued behind it. Pre-fix, B's
- // payload was baked at CALL time from the optimistic `[A, B]`
- // projection, so it silently re-persisted A's edit server-side even
- // though A's own write was reported failed — because `updateShareConfig`
- // overwrites the whole `toolGrants` array rather than diffing it.
- let rejectFirst: (reason: unknown) => void = () => {};
- service.updateShareConfig.mockImplementationOnce(
- () =>
- new Promise((_resolve, reject) => {
- rejectFirst = reject;
- }),
- );
- service.updateShareConfig.mockImplementationOnce(async (_agentId: string, patch: any) => ({
- ...buildShare(),
- shareConfig: { ...buildShare().shareConfig, ...patch },
- }));
-
- const { result } = renderHook(() => useAgentShare('agent-1'));
-
- let editingA: Promise<unknown> = Promise.resolve();
- await act(async () => {
- editingA = result.current.updateConfig((current) => ({
- toolGrants: [...(current.toolGrants ?? []), { identifier: 'tool-a' }],
- }));
- void result.current.updateConfig((current) => ({
- toolGrants: [...(current.toolGrants ?? []), { identifier: 'tool-b' }],
- }));
- });
- // The queue must not stall on A's eventual rejection.
- editingA.catch(() => undefined);
-
- await waitFor(() => expect(service.updateShareConfig).toHaveBeenCalledTimes(1));
-
- await act(async () => {
- rejectFirst(new Error('write A failed'));
- });
-
- await waitFor(() => expect(service.updateShareConfig).toHaveBeenCalledTimes(2));
-
- // B's outgoing payload must be resolved as if A never happened, not
- // against the optimistic `[A, B]` UI projection A was already baked into.
- expect(service.updateShareConfig.mock.calls[1][1]).toEqual({
- toolGrants: [{ identifier: 'tool-b' }],
- });
- });
-
- it('does not let an earlier response revert a later queued write before it lands (A/B/C interleaving)', async () => {
- // Reproduces the lost-update window exactly: A is in flight, B is toggled
- // while A is still pending (queued behind it), and A's response lands
- // BEFORE B's request is even sent. Pre-fix, `commitIfCurrent` would
- // unconditionally adopt A's response into `latestConfigRef`, regressing
- // the local projection from [A, B] back to just [A] — so when C is then
- // toggled off that regressed snapshot, C's whole-array write silently
- // drops B server-side once it lands, even though B's own write already
- // succeeded. With the fix, an intermediate response is only adopted once
- // it is the LAST pending write, so the projection (and what the UI reads
- // off SWR) never regresses mid-flight.
- let releaseA: (value: any) => void = () => {};
- let releaseB: (value: any) => void = () => {};
- let releaseC: (value: any) => void = () => {};
-
- service.updateShareConfig
- .mockImplementationOnce(
- (_agentId: string, patch: any) =>
- new Promise((resolve) => {
- releaseA = () =>
- resolve({ ...buildShare(), shareConfig: { ...buildShare().shareConfig, ...patch } });
- }),
- )
- .mockImplementationOnce(
- (_agentId: string, patch: any) =>
- new Promise((resolve) => {
- releaseB = () =>
- resolve({ ...buildShare(), shareConfig: { ...buildShare().shareConfig, ...patch } });
- }),
- )
- .mockImplementationOnce(
- (_agentId: string, patch: any) =>
- new Promise((resolve) => {
- releaseC = () =>
- resolve({ ...buildShare(), shareConfig: { ...buildShare().shareConfig, ...patch } });
- }),
- );
-
- const { result } = renderHook(() => useAgentShare('agent-1'));
-
- await act(async () => {
- void result.current.updateConfig((current) => ({
- toolGrants: [...(current.toolGrants ?? []), { identifier: 'tool-a' }],
- }));
- void result.current.updateConfig((current) => ({
- toolGrants: [...(current.toolGrants ?? []), { identifier: 'tool-b' }],
- }));
- });
-
- await waitFor(() => expect(service.updateShareConfig).toHaveBeenCalledTimes(1));
-
- await act(async () => {
- releaseA(undefined);
- });
- await waitFor(() => expect(service.updateShareConfig).toHaveBeenCalledTimes(2));
-
- // A's response landed while B was still queued — the projection (and the
- // SWR cache the UI reads) must not have regressed back to just A.
- expect(result.current.share?.shareConfig.toolGrants).toEqual([
- { identifier: 'tool-a' },
- { identifier: 'tool-b' },
- ]);
-
- await act(async () => {
- void result.current.updateConfig((current) => ({
- toolGrants: [...(current.toolGrants ?? []), { identifier: 'tool-c' }],
- }));
- });
-
- await act(async () => {
- releaseB(undefined);
- });
- await waitFor(() => expect(service.updateShareConfig).toHaveBeenCalledTimes(3));
-
- await act(async () => {
- releaseC(undefined);
- });
-
- expect(service.updateShareConfig.mock.calls[0][1]).toEqual({
- toolGrants: [{ identifier: 'tool-a' }],
- });
- expect(service.updateShareConfig.mock.calls[1][1]).toEqual({
- toolGrants: [{ identifier: 'tool-a' }, { identifier: 'tool-b' }],
- });
- // The final persisted patch for C must still contain B — it was never
- // reverted by A's earlier, now-stale response.
- expect(service.updateShareConfig.mock.calls[2][1]).toEqual({
- toolGrants: [{ identifier: 'tool-a' }, { identifier: 'tool-b' }, { identifier: 'tool-c' }],
- });
- expect(result.current.share?.shareConfig.toolGrants).toEqual([
- { identifier: 'tool-a' },
- { identifier: 'tool-b' },
- { identifier: 'tool-c' },
- ]);
- });
-
- it('keeps granted tools the picker never renders', async () => {
- swr.seed(
- buildShare({
- toolGrants: [{ identifier: 'lobe-local-system' }, { identifier: 'mcp-github' }],
- }),
- );
-
- const { result } = renderHook(() => useAgentShare('agent-1'));
-
- await act(async () => {
- await result.current.updateConfig((current) => ({
- toolGrants: [...(current.toolGrants ?? []), { identifier: 'calculator' }],
- }));
- });
-
- expect(service.updateShareConfig.mock.calls[0][1]).toEqual({
- toolGrants: [
- { identifier: 'lobe-local-system' },
- { identifier: 'mcp-github' },
- { identifier: 'calculator' },
- ],
- });
- });
-
- it('projects the patch into the cache immediately', async () => {
- const { result } = renderHook(() => useAgentShare('agent-1'));
-
- await act(async () => {
- await result.current.updateConfig({ maxTurnsPerTopic: 30 });
- });
-
- expect(result.current.share?.shareConfig.maxTurnsPerTopic).toBe(30);
- });
-
- it('keeps the paused row in the cache instead of dropping it', async () => {
- service.disableShare.mockResolvedValue({ ...buildShare(), visibility: 'private' });
-
- const { result } = renderHook(() => useAgentShare('agent-1'));
-
- await act(async () => {
- await result.current.disable();
- });
-
- // Disabling only pauses the share: the row (hence its id and slug) stays,
- // so the same link resumes on the next enable.
- expect(result.current.share?.id).toBe('share-1');
- expect(result.current.share?.visibility).toBe('private');
- });
-
- it('still lands an edit made while a disable is in flight', async () => {
- let completeDisable: () => void = () => {};
- service.disableShare.mockImplementationOnce(
- () =>
- new Promise((resolve) => {
- completeDisable = () => resolve({ ...buildShare(), visibility: 'private' });
- }),
- );
-
- const { result } = renderHook(() => useAgentShare('agent-1'));
-
- let disabling: Promise<unknown> = Promise.resolve();
- await act(async () => {
- disabling = result.current.disable();
- });
- await waitFor(() => expect(service.disableShare).toHaveBeenCalledTimes(1));
-
- // A debounced limit patch flushing on unmount races the disable. The row
- // survives the disable, so the edit must be written, not dropped.
- let editing: Promise<unknown> = Promise.resolve();
- await act(async () => {
- editing = result.current.updateConfig({ maxTurnsPerTopic: 30 });
- });
-
- await act(async () => {
- completeDisable();
- await disabling;
- await editing;
- });
-
- expect(service.updateShareConfig).toHaveBeenCalledTimes(1);
- expect(service.updateShareConfig.mock.calls[0][1]).toEqual({ maxTurnsPerTopic: 30 });
- });
-
- it('re-reads the server after a later queued write fails so a discarded earlier response is not lost', async () => {
- // Disable succeeds but its response is discarded because a slug write is
- // already queued behind it; the slug write then fails. The cache must end
- // up showing the server truth (disabled), not the pre-disable row.
- let completeDisable: () => void = () => {};
- service.disableShare.mockImplementationOnce(
- () =>
- new Promise((resolve) => {
- completeDisable = () => resolve({ ...buildShare(), visibility: 'private' });
- }),
- );
- service.updateSlug.mockRejectedValueOnce(new Error('slug taken'));
- service.getShareStatus.mockResolvedValue({ ...buildShare(), visibility: 'private' });
-
- const { result } = renderHook(() => useAgentShare('agent-1'));
-
- let disabling: Promise<unknown> = Promise.resolve();
- await act(async () => {
- disabling = result.current.disable();
- });
- await waitFor(() => expect(service.disableShare).toHaveBeenCalledTimes(1));
-
- let saving: Promise<unknown> = Promise.resolve();
- await act(async () => {
- saving = result.current.updateSlug('new-slug').catch(() => undefined);
- });
-
- await act(async () => {
- completeDisable();
- await disabling;
- await saving;
- });
-
- await waitFor(() => expect(result.current.share?.visibility).toBe('private'));
- });
-
- it('still writes when a disable failed outright', async () => {
- service.disableShare.mockRejectedValue(new Error('nope'));
-
- const { result } = renderHook(() => useAgentShare('agent-1'));
-
- await act(async () => {
- await result.current.disable().catch(() => undefined);
- });
- await act(async () => {
- await result.current.updateConfig({ maxTurnsPerTopic: 30 });
- });
-
- expect(service.updateShareConfig).toHaveBeenCalledTimes(1);
- });
-});
-
-describe('useAgentShare · agent identity change', () => {
- // The settings page component is not remounted when navigating between two
- // agents' share pages — it just receives a new `agentId` prop (mirrors
- // `useDebouncedLimitPatch`'s doc). Without the identity guard, a write still
- // in flight for agent A would land its response in the SAME shared
- // `latestConfigRef` agent B's edits derive from.
- it("does not let agent A's in-flight write pollute agent B's config after navigating without unmount", async () => {
- const shareA = buildShare({ maxTurnsPerTopic: 20 });
- const shareB = buildShare({ maxTurnsPerTopic: 99 });
- swr.seed(shareA);
-
- let releaseA: () => void = () => {};
- service.updateShareConfig.mockImplementationOnce(
- (_agentId: string, patch: any) =>
- new Promise((resolve) => {
- releaseA = () => resolve({ ...shareA, shareConfig: { ...shareA.shareConfig, ...patch } });
- }),
- );
-
- const { result, rerender } = renderHook(({ agentId }) => useAgentShare(agentId), {
- initialProps: { agentId: 'agent-A' },
- });
-
- // Kick off an edit on A that stays in flight (server hasn't responded yet).
- let editingA: Promise<unknown> = Promise.resolve();
- await act(async () => {
- editingA = result.current.updateConfig({ maxTurnsPerTopic: 5 });
- });
- await waitFor(() => expect(service.updateShareConfig).toHaveBeenCalledTimes(1));
- expect(service.updateShareConfig).toHaveBeenNthCalledWith(1, 'agent-A', {
- maxTurnsPerTopic: 5,
- });
-
- // Navigate to agent B without unmounting. Simulate SWR's own key switch
- // resolving to B's row (a real key change would trigger a fresh fetch).
- act(() => {
- rerender({ agentId: 'agent-B' });
- });
- act(() => {
- swr.set(shareB);
- });
-
- // B's server snapshot must be adopted — not blocked behind A's pending
- // write count, which belongs to a hook instance the component reused.
- expect(result.current.share?.shareConfig.maxTurnsPerTopic).toBe(99);
-
- // The next edit on B must derive its patch from B's config (99), not from
- // whatever `latestConfigRef` held for A.
- service.updateShareConfig.mockImplementationOnce(async (_agentId: string, patch: any) => ({
- ...shareB,
- shareConfig: { ...shareB.shareConfig, ...patch },
- }));
- await act(async () => {
- await result.current.updateConfig((current) => ({
- maxTurnsPerTopic: (current.maxTurnsPerTopic ?? 0) + 1,
- }));
- });
- expect(service.updateShareConfig).toHaveBeenNthCalledWith(2, 'agent-B', {
- maxTurnsPerTopic: 100,
- });
- expect(result.current.share?.shareConfig.maxTurnsPerTopic).toBe(100);
-
- // A's stale write finally resolves — its response must be dropped rather
- // than clobbering the config B's edits now derive from.
- await act(async () => {
- releaseA();
- await editingA;
- });
- expect(result.current.share?.shareConfig.maxTurnsPerTopic).toBe(100);
- });
-
- // Comparing the bare `agentId` string is not enough: after an A → B → A
- // round trip the hook tracks `agent-A` again, so a write issued under the
- // FIRST visit would pass an id-only check, decrement the second visit's
- // pending-write counter, and adopt its stale response over edits issued
- // after the return. Each write must be pinned to an identity generation.
- it("drops agent A's write from a previous visit after navigating A → B → A", async () => {
- const shareA = buildShare({ maxTurnsPerTopic: 20 });
- const shareB = buildShare({ maxTurnsPerTopic: 99 });
- swr.seed(shareA);
-
- let releaseFirst: () => void = () => {};
- service.updateShareConfig.mockImplementationOnce(
- (_agentId: string, patch: any) =>
- new Promise((resolve) => {
- releaseFirst = () =>
- resolve({ ...shareA, shareConfig: { ...shareA.shareConfig, ...patch } });
- }),
- );
-
- const { result, rerender } = renderHook(({ agentId }) => useAgentShare(agentId), {
- initialProps: { agentId: 'agent-A' },
- });
-
- // First visit to A: an edit that stays in flight across the round trip.
- let firstEdit: Promise<unknown> = Promise.resolve();
- await act(async () => {
- firstEdit = result.current.updateConfig({ maxTurnsPerTopic: 5 });
- });
- await waitFor(() => expect(service.updateShareConfig).toHaveBeenCalledTimes(1));
-
- // A → B → A without unmount; SWR resolves each key switch to its row.
- act(() => {
- rerender({ agentId: 'agent-B' });
- });
- act(() => {
- swr.set(shareB);
- });
- act(() => {
- rerender({ agentId: 'agent-A' });
- });
- act(() => {
- swr.set(shareA);
- });
- expect(result.current.share?.shareConfig.maxTurnsPerTopic).toBe(20);
-
- // Second visit to A: a new edit whose request also stays in flight, so the
- // first visit's late response has a pending write to race against.
- let releaseSecond: () => void = () => {};
- service.updateShareConfig.mockImplementationOnce(
- (_agentId: string, patch: any) =>
- new Promise((resolve) => {
- releaseSecond = () =>
- resolve({ ...shareA, shareConfig: { ...shareA.shareConfig, ...patch } });
- }),
- );
- let secondEdit: Promise<unknown> = Promise.resolve();
- await act(async () => {
- secondEdit = result.current.updateConfig({ maxTurnsPerTopic: 8 });
- });
- await waitFor(() => expect(service.updateShareConfig).toHaveBeenCalledTimes(2));
- expect(service.updateShareConfig).toHaveBeenNthCalledWith(2, 'agent-A', {
- maxTurnsPerTopic: 8,
- });
- expect(result.current.share?.shareConfig.maxTurnsPerTopic).toBe(8);
-
- // The FIRST visit's response lands while the second edit is still
- // pending. It must be dropped: the optimistic 8 stays, not the stale 5.
- await act(async () => {
- releaseFirst();
- await firstEdit;
- });
- expect(result.current.share?.shareConfig.maxTurnsPerTopic).toBe(8);
-
- // The second edit's own response is still adopted normally — proving the
- // pending-write counter was not corrupted by the late first response.
- await act(async () => {
- releaseSecond();
- await secondEdit;
- });
- expect(result.current.share?.shareConfig.maxTurnsPerTopic).toBe(8);
-
- // With the queue drained, a server re-seed is adopted again (idle path):
- // the counter is back at zero rather than negative or stuck.
- act(() => {
- swr.set(buildShare({ maxTurnsPerTopic: 42 }));
- });
- expect(result.current.share?.shareConfig.maxTurnsPerTopic).toBe(42);
- service.updateShareConfig.mockImplementationOnce(async (_agentId: string, patch: any) => ({
- ...shareA,
- shareConfig: { ...shareA.shareConfig, ...patch },
- }));
- await act(async () => {
- await result.current.updateConfig((current) => ({
- maxTurnsPerTopic: (current.maxTurnsPerTopic ?? 0) + 1,
- }));
- });
- expect(service.updateShareConfig).toHaveBeenNthCalledWith(3, 'agent-A', {
- maxTurnsPerTopic: 43,
- });
- });
-});
-
-describe('useAgentShare · getShareStatus failure', () => {
- it('exposes the fetch error instead of swallowing it', () => {
- const fetchError = new Error('network down');
- swr.seedError(fetchError);
-
- const { result } = renderHook(() => useAgentShare('agent-1'));
-
- expect(result.current.error).toBe(fetchError);
- expect(result.current.share).toBeUndefined();
- });
-});
diff --git a/src/features/AgentShareSettings/useAgentShare.ts b/src/features/AgentShareSettings/useAgentShare.ts
deleted file mode 100644
index 26c7f3be512..00000000000
--- a/src/features/AgentShareSettings/useAgentShare.ts
+++ /dev/null
@@ -1,338 +0,0 @@
-import { useCallback, useEffect, useRef } from 'react';
-import useSWR from 'swr';
-
-import { shareKeys } from '@/libs/swr/keys';
-import type { AgentShareConfigPatchInput } from '@/services/agentShare';
-import { agentShareService } from '@/services/agentShare';
-
-import { mergeShareConfig } from './shareConfigPatch';
-
-export type AgentShareInfo = Awaited<ReturnType<typeof agentShareService.getShareStatus>>;
-/** Server-normalized share config (every optional field already defaulted). */
-export type AgentShareConfigState = NonNullable<AgentShareInfo>['shareConfig'];
-
-/**
- * A config patch, or a function producing one from the LATEST known config.
- * Use the function form for any edit derived from the current value (toggling
- * a tool in `toolGrants`, say) — a plain object captures whatever the
- * component rendered with, which is stale the moment a previous write is
- * still in flight.
- */
-export type AgentShareConfigPatch =
- AgentShareConfigPatchInput | ((current: AgentShareConfigState) => AgentShareConfigPatchInput);
-
-/**
- * Creator-side share state for one agent.
- *
- * Unlike a topic share, sharing an agent lets link holders RUN it on the
- * creator's account, so nothing is created until the owner explicitly turns
- * sharing on. `enable` mints (or republishes) the row with `link` visibility;
- * `disable` only flips it back to `private`, keeping the share id and slug so
- * the same url resumes on the next enable (see `AgentShareModel`).
- */
-export const useAgentShare = (agentId: string) => {
- const {
- data: share,
- error,
- isLoading,
- mutate,
- } = useSWR(shareKeys.agentShareStatus(agentId), () => agentShareService.getShareStatus(agentId), {
- revalidateOnFocus: false,
- });
-
- /**
- * The config as it will be once every write issued so far has landed —
- * `undefined` while unknown, `null` once the share row is known to be gone.
- * A functional patch's UI-facing preview resolves against THIS at CALL
- * time, so two edits fired before the first response composes visually
- * rather than the second overwriting the first. It does NOT drive the
- * network payload any more — see `sendConfigRef` for why the two had to
- * split.
- */
- const latestConfigRef = useRef<AgentShareConfigState | null | undefined>(undefined);
- /**
- * Mirrors `latestConfigRef`, but only ever advances/rolls back at SEND
- * time, inside a queued `updateConfig` task — never at call time. This is
- * what a functional patch's OUTGOING payload resolves against.
- *
- * Why call-time resolution isn't enough: say two functional edits are
- * queued back to back — toggle tool A (sends `toolGrants: [A]`), then
- * toggle tool B. If B's payload were baked at call time from
- * `latestConfigRef` (which already includes A's optimistic projection),
- * it would resolve to `[A, B]` regardless of what happens to A's write.
- * If A's request then FAILS, the server never persisted A — but the queue
- * still sends B's already-baked `[A, B]`, silently re-persisting A anyway.
- * `mergeShareConfig` / `AgentShareModel.updateConfig` overwrite whole
- * jsonb keys rather than diffing them, so B's write can't just apply a
- * delta on top of whatever the server actually has; it sends the full
- * array it was told to send.
- *
- * Resolving each patch against `sendConfigRef` at SEND time instead fixes
- * this: `enqueue` serializes writes strictly (a queued task's body does
- * not start until every earlier task has fully settled), so by the time
- * B's task runs, A's outcome is already known. A success advances
- * `sendConfigRef` to include A; a failure rolls it back to exclude A
- * (see the `catch` branch in `updateConfig`) — either way B resolves its
- * patch against the config the server will actually see, so a failed A
- * never leaks into B's request.
- */
- const sendConfigRef = useRef<AgentShareConfigState | null | undefined>(undefined);
- const pendingWritesRef = useRef(0);
-
- /**
- * `agentId` identity this hook instance is currently tracking. The owning
- * settings page component is NOT remounted when navigating between two
- * agents' share pages (it just receives a new `agentId` prop), so every ref
- * above survives the switch unless reset here — mirrors the pattern in
- * `useDebouncedLimitPatch`.
- */
- const identityRef = useRef(agentId);
- /**
- * Monotonic counter bumped on every `agentId` change. Comparing the bare
- * `agentId` string is not enough to tell a stale write from a current one:
- * after an A → B → A round trip `identityRef` reads `A` again, so a write
- * issued under the FIRST A (still in flight, its counter already zeroed by
- * the reset below) would pass an id-only check and decrement the second
- * A's `pendingWritesRef` — possibly below zero — and `commitIfCurrent`
- * would adopt its stale response over edits issued after the return. Each
- * write captures the generation it was issued under and compares against
- * this instead, so the two A's are distinct.
- */
- const generationRef = useRef(0);
- /**
- * Every mutation replaces the whole row in the SWR cache, so two writes that
- * resolve out of order would let the older response win — see `enqueue`
- * below. Declared here (rather than next to `enqueue`) so the identity-change
- * reset can null it out too.
- */
- const queueRef = useRef<Promise<unknown> | null>(null);
-
- // `agentId` changed since the last render: reset adoption state right away
- // (render-time, not in an effect) so the idle-adoption effect below picks
- // up the NEW agent's server snapshot on its very next run instead of
- // staying blocked behind the OLD agent's still-in-flight write count.
- // Comparing against `identityRef` (rather than unconditionally resetting
- // every render) makes this idempotent under StrictMode's render
- // double-invocation, same as `useDebouncedLimitPatch`.
- //
- // `queueRef` is also cut loose (set to `null`, not awaited/drained): the
- // NEXT write — now for the new agent — must not queue behind whatever A
- // still has in flight, since that write targets an entirely different SWR
- // key/resource and there is no ordering to preserve across the two. A's own
- // promise chain keeps running independently; its resolution is simply
- // ignored by `commitIfCurrent` once `identityRef` no longer matches (see
- // below), so nothing is lost — the request already landed server-side.
- if (identityRef.current !== agentId) {
- identityRef.current = agentId;
- generationRef.current += 1;
- latestConfigRef.current = undefined;
- sendConfigRef.current = undefined;
- pendingWritesRef.current = 0;
- queueRef.current = null;
- }
-
- // Only adopt a server snapshot while idle: mid-flight it would be older than
- // the local projection above. Keep both refs in lockstep — an idle re-seed
- // is a fresh confirmed baseline, so there is no pending edit for
- // `sendConfigRef` to preserve over it either.
- useEffect(() => {
- if (pendingWritesRef.current > 0) return;
- const next = share === undefined ? undefined : (share?.shareConfig ?? null);
- latestConfigRef.current = next;
- sendConfigRef.current = next;
- }, [share]);
-
- /**
- * Apply a write's server response to the shared refs only if the identity
- * generation hasn't moved since the write was issued. A write started for agent A
- * can still resolve after navigating to agent B (this hook instance is
- * reused, not remounted) — its resolved value must be dropped instead of
- * clobbering `latestConfigRef`/the SWR cache entry B's edits now derive
- * from. The network write itself is never cancelled: A's request already
- * landed server-side by the time this runs; only the LOCAL bookkeeping is
- * skipped.
- *
- * Also skipped while a LATER write is still queued or in flight
- * (`pendingWritesRef.current > 1`, this write itself included). Every
- * write — from `updateConfig` to `enable`/`disable`/`updateSlug` — is
- * serialized through the same `queueRef` chain, but each one's outgoing
- * patch is computed synchronously at call time from `latestConfigRef`, not
- * re-derived when it actually sends. If an EARLIER write's response were
- * adopted here while a later write is still pending, it would regress
- * `latestConfigRef` back to a snapshot older than what the later write's
- * patch was already built from — and because `mergeShareConfig` /
- * `AgentShareModel.updateConfig` overwrite whole jsonb keys rather than
- * diffing them, the later write's request would then silently REVERT the
- * edit this response is trying to confirm once it lands. Only the LAST
- * pending write's response is guaranteed to reflect every earlier write's
- * effect (the server processes them in the same serial order they were
- * sent), so only it is allowed to update the shared refs / SWR cache.
- */
- const commitIfCurrent = useCallback(
- async (writeGeneration: number, updated: AgentShareInfo) => {
- if (generationRef.current !== writeGeneration) return;
- if (pendingWritesRef.current > 1) return;
- latestConfigRef.current = updated?.shareConfig ?? null;
- // The server response reflects every write processed so far, so it is
- // also a fresh confirmed baseline for `sendConfigRef` — any patch still
- // resolving against it from here composes on top of a value the server
- // agrees with, not a locally-mirrored guess.
- sendConfigRef.current = latestConfigRef.current;
- await mutate(updated, { revalidate: false });
- },
- [mutate],
- );
-
- const enqueue = useCallback(<T>(task: () => Promise<T>): Promise<T> => {
- const tail = queueRef.current ?? Promise.resolve();
- // Both handlers run `task`: a failed write must reject its own caller
- // without stalling the writes queued behind it.
- const result = tail.then(task, task);
- queueRef.current = result.catch(() => undefined);
- return result;
- }, []);
-
- /**
- * Wrap a queued write with pending-write accounting, shared by every write
- * (`enable`/`disable`/`updateConfig`/`updateSlug`) so `commitIfCurrent` can
- * tell whether its own response is the last one outstanding — see its
- * comment above. Increments as soon as the write is issued (covers time
- * spent queued behind an earlier write, not just its own network round
- * trip) and decrements once it settles either way.
- *
- * The task receives the identity generation it was issued under, so it can
- * hand that to `commitIfCurrent` / its own late identity checks.
- */
- const runWrite = useCallback(
- <T>(task: (generation: number) => Promise<T>): Promise<T> => {
- const generation = generationRef.current;
- pendingWritesRef.current += 1;
- return enqueue(() => task(generation))
- .finally(() => {
- // The reset on identity change already zeroed this counter for the
- // NEW generation; a write issued under an OLD one must not decrement
- // it again once it settles late.
- if (generationRef.current === generation) pendingWritesRef.current -= 1;
- })
- .catch((error) => {
- // A failed write may have been the LAST one queued, in which case
- // `commitIfCurrent` already discarded every earlier write's response
- // on the assumption that this one would carry their combined effect.
- // Nothing else will refresh the cache (focus revalidation is off), so
- // re-read the server truth here; the idle re-sync effect re-seeds
- // `latestConfigRef` once the queue drains. Skipped once the identity
- // generation has moved on — that `mutate` belongs to another agent
- // (or an earlier visit to this one).
- if (generationRef.current === generation) void mutate();
- throw error;
- });
- },
- [enqueue, mutate],
- );
-
- const enable = useCallback(
- () =>
- runWrite(async (generation) => {
- // `create` returns any pre-existing row untouched, so a legacy
- // `private` row still needs the explicit flip to `link`.
- const created = await agentShareService.enableShare(agentId, 'link');
- const updated =
- created.visibility === 'link'
- ? created
- : await agentShareService.updateVisibility(agentId, 'link');
- await commitIfCurrent(generation, updated);
- }),
- [agentId, commitIfCurrent, runWrite],
- );
-
- const updateConfig = useCallback(
- (patch: AgentShareConfigPatch) => {
- const base = latestConfigRef.current;
- // Nothing loaded yet, or this agent has no share row at all — there is
- // nothing to write against. (Turning sharing OFF does not land here: the
- // row survives as `private`, so its config stays editable.)
- if (!base) return Promise.resolve();
-
- const uiPatch = typeof patch === 'function' ? patch(base) : patch;
- // Project the patch locally right away, so the control reflects the edit
- // immediately AND the next patch composes on top of this one. This is a
- // UI-only preview — the outgoing network payload is resolved separately
- // below, at send time, against `sendConfigRef` (see its doc comment).
- latestConfigRef.current = mergeShareConfig(base, uiPatch);
- const optimisticConfig = latestConfigRef.current;
- void mutate(
- (current) => (current ? { ...current, shareConfig: optimisticConfig } : current),
- {
- revalidate: false,
- },
- );
-
- return runWrite(async (generation) => {
- // Resolve the OUTGOING payload now, not at call time: `enqueue`
- // guarantees no earlier queued write's task body is still running by
- // the time this one starts, so `sendConfigRef` already reflects every
- // earlier write's real outcome (advanced on success, rolled back on
- // failure) instead of the optimistic UI projection above, which
- // cannot un-bake a since-failed edit once composed into it.
- //
- // Skip touching the shared ref once the identity generation has moved
- // on (this task belongs to an abandoned identity, per
- // `commitIfCurrent`'s doc): fall
- // back to the call-time `base` this closure already captured, which
- // reproduces the pre-fix behavior for that edge case instead of
- // reading/mutating a ref that now belongs to a different agent.
- const forCurrentIdentity = generationRef.current === generation;
- // `sendConfigRef.current` is only ever `null`/`undefined` in lockstep
- // with `latestConfigRef` (see both refs' reset points above), and
- // `base` already proved non-null via the guard at the top of this
- // callback — so falling back to `base` here also keeps `sendBase`
- // non-null for `patch`'s functional form.
- const sendBase = forCurrentIdentity ? (sendConfigRef.current ?? base) : base;
- const resolved = typeof patch === 'function' ? patch(sendBase) : patch;
- if (forCurrentIdentity) sendConfigRef.current = mergeShareConfig(sendBase, resolved);
-
- try {
- const updated = await agentShareService.updateShareConfig(agentId, resolved);
- await commitIfCurrent(generation, updated);
- } catch (error) {
- // Roll back this write's contribution so the NEXT queued write's
- // send-time resolution does not see it. Re-check identity rather
- // than reusing `forCurrentIdentity`: it may have changed while the
- // request was in flight, in which case `sendConfigRef` now belongs
- // to a different agent and must be left alone.
- if (generationRef.current === generation) sendConfigRef.current = sendBase;
- // The optimistic projection is dropped by the server re-read that
- // `runWrite` issues for every failed write.
- throw error;
- }
- });
- },
- [agentId, commitIfCurrent, runWrite],
- );
-
- /**
- * Pause sharing. The row survives as `private`, so nothing local needs
- * invalidating: an edit issued in the same tick (a debounced limit patch
- * flushed on unmount, say) simply queues behind this write and lands on the
- * row it was always meant for.
- */
- const disable = useCallback(
- () =>
- runWrite(async (generation) => {
- const disabled = await agentShareService.disableShare(agentId);
- await commitIfCurrent(generation, disabled);
- }),
- [agentId, commitIfCurrent, runWrite],
- );
-
- const updateSlug = useCallback(
- (slug: string | null) =>
- runWrite(async (generation) => {
- const updated = await agentShareService.updateSlug(agentId, slug);
- await commitIfCurrent(generation, updated);
- }),
- [agentId, commitIfCurrent, runWrite],
- );
-
- return { disable, enable, error, isLoading, mutate, share, updateConfig, updateSlug };
-};
diff --git a/src/features/AgentShareSettings/useAgentShareSupported.test.ts b/src/features/AgentShareSettings/useAgentShareSupported.test.ts
deleted file mode 100644
index b2c4f4f81c8..00000000000
--- a/src/features/AgentShareSettings/useAgentShareSupported.test.ts
+++ /dev/null
@@ -1,172 +0,0 @@
-import { renderHook } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { resolveLinkToggleState, useAgentShareSupported } from './useAgentShareSupported';
-
-const testState = vi.hoisted(() => ({
- /** What `getShareStatus` resolves to for the non-publishable lookup. */
- shareStatus: null as { visibility: 'link' | 'private' } | null,
- enableAgentShare: undefined as boolean | undefined,
- enableBusinessFeatures: true,
- hasActiveWorkspace: false,
- isBuiltinAgent: false,
-}));
-
-vi.mock('swr', () => ({
- default: (key: unknown, fetcher: () => unknown) => ({
- data: key ? fetcher() : undefined,
- }),
-}));
-
-vi.mock('@/libs/swr/keys', () => ({
- shareKeys: { agentShareStatus: (agentId: string) => ['share:agentShareStatus', agentId] },
-}));
-
-vi.mock('@/services/agentShare', () => ({
- agentShareService: { getShareStatus: () => testState.shareStatus },
-}));
-
-vi.mock('@/business/client/hooks/useHasActiveWorkspace', () => ({
- useHasActiveWorkspace: () => testState.hasActiveWorkspace,
-}));
-
-vi.mock('@/store/agent', () => ({
- useAgentStore: (selector: (state: unknown) => unknown) => selector(undefined),
-}));
-
-vi.mock('@/store/agent/selectors', () => ({
- builtinAgentSelectors: {
- isBuiltinAgent: () => () => testState.isBuiltinAgent,
- },
-}));
-
-vi.mock('@/store/serverConfig', () => ({
- useServerConfigStore: (selector: (state: typeof testState) => unknown) => selector(testState),
-}));
-
-vi.mock('@/store/serverConfig/selectors', () => ({
- featureFlagsSelectors: (state: typeof testState) => ({
- enableAgentShare: state.enableAgentShare,
- }),
- serverConfigSelectors: {
- enableBusinessFeatures: (state: typeof testState) => state.enableBusinessFeatures,
- },
-}));
-
-describe('useAgentShareSupported', () => {
- beforeEach(() => {
- testState.enableAgentShare = undefined;
- testState.enableBusinessFeatures = true;
- testState.hasActiveWorkspace = false;
- testState.isBuiltinAgent = false;
- testState.shareStatus = null;
- });
-
- it('is unsupported without an agentId', () => {
- const { result } = renderHook(() => useAgentShareSupported(undefined));
-
- expect(result.current).toEqual({ publishable: false, supported: false, visible: false });
- });
-
- it('is unsupported for a workspace agent, regardless of the flags', () => {
- testState.hasActiveWorkspace = true;
-
- const { result } = renderHook(() => useAgentShareSupported('agent-1'));
-
- expect(result.current).toEqual({ publishable: false, supported: false, visible: false });
- });
-
- it('is unsupported for a builtin agent', () => {
- testState.isBuiltinAgent = true;
-
- const { result } = renderHook(() => useAgentShareSupported('agent-1'));
-
- expect(result.current.supported).toBe(false);
- });
-
- // Structural: an OSS deployment has no Agent Share surface at all,
- // server-enforced by `ENABLE_BUSINESS_FEATURES` — unlike `enableAgentShare`
- // below, this must hide the whole surface, not just block publishing.
- it('is unsupported on a deployment without business features, even with the rollout flag on', () => {
- testState.enableBusinessFeatures = false;
- testState.enableAgentShare = true;
-
- const { result } = renderHook(() => useAgentShareSupported('agent-1'));
-
- expect(result.current).toEqual({ publishable: false, supported: false, visible: false });
- });
-
- it('is supported but not publishable while the rollout flag is unresolved', () => {
- testState.enableAgentShare = undefined;
-
- const { result } = renderHook(() => useAgentShareSupported('agent-1'));
-
- expect(result.current).toEqual({ publishable: false, supported: true, visible: false });
- });
-
- // Outside the allowlist with nothing live: no entry at all — the tab, the
- // header action and the settings deep link all key off `visible`.
- it('hides the entry when the rollout flag is off and no share exists', () => {
- testState.enableAgentShare = false;
-
- const { result } = renderHook(() => useAgentShareSupported('agent-1'));
-
- expect(result.current).toEqual({ publishable: false, supported: true, visible: false });
- });
-
- it('hides the entry when the rollout flag is off and the share is already revoked', () => {
- testState.enableAgentShare = false;
- testState.shareStatus = { visibility: 'private' };
-
- const { result } = renderHook(() => useAgentShareSupported('agent-1'));
-
- expect(result.current).toEqual({ publishable: false, supported: true, visible: false });
- });
-
- // An owner rolled back out of the allowlist keeps the entry for a live share
- // so it stays revocable (the server keeps `disable` open for this case).
- it('keeps the entry for a live share when the rollout flag is off', () => {
- testState.enableAgentShare = false;
- testState.shareStatus = { visibility: 'link' };
-
- const { result } = renderHook(() => useAgentShareSupported('agent-1'));
-
- expect(result.current).toEqual({ publishable: false, supported: true, visible: true });
- });
-
- it('is publishable and visible when every gate passes', () => {
- testState.enableAgentShare = true;
-
- const { result } = renderHook(() => useAgentShareSupported('agent-1'));
-
- expect(result.current).toEqual({ publishable: true, supported: true, visible: true });
- });
-});
-
-describe('resolveLinkToggleState', () => {
- it('allows publishing when the account has the capability', () => {
- expect(resolveLinkToggleState({ isShared: false, publishable: true })).toEqual({
- canPublish: true,
- disabled: false,
- offHintKey: 'share.settings.link.offHint',
- });
- });
-
- it('blocks publishing and explains why when the account may not publish', () => {
- expect(resolveLinkToggleState({ isShared: false, publishable: false })).toEqual({
- canPublish: false,
- disabled: true,
- offHintKey: 'share.settings.link.publishDisabled',
- });
- });
-
- // The regression this gate exists for: an owner rolled back out of the
- // rollout must still be able to revoke a share they already published, which
- // is why the server keeps `agentShare.disable` open while the flag is off.
- it('keeps an already published share togglable when publishing is blocked', () => {
- const state = resolveLinkToggleState({ isShared: true, publishable: false });
-
- expect(state.disabled).toBe(false);
- expect(state.canPublish).toBe(true);
- });
-});
diff --git a/src/features/AgentShareSettings/useAgentShareSupported.ts b/src/features/AgentShareSettings/useAgentShareSupported.ts
deleted file mode 100644
index 0611168009e..00000000000
--- a/src/features/AgentShareSettings/useAgentShareSupported.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-'use client';
-
-import useSWR from 'swr';
-
-import { useHasActiveWorkspace } from '@/business/client/hooks/useHasActiveWorkspace';
-import { shareKeys } from '@/libs/swr/keys';
-import { agentShareService } from '@/services/agentShare';
-import { useAgentStore } from '@/store/agent';
-import { builtinAgentSelectors } from '@/store/agent/selectors';
-import { useServerConfigStore } from '@/store/serverConfig';
-import { featureFlagsSelectors, serverConfigSelectors } from '@/store/serverConfig/selectors';
-
-export interface AgentShareSupport {
- /**
- * Whether a *new* share may be published right now. Mirrors the server gate
- * on `agentShare.enableShare` / `updateVisibility → 'link'`; every other
- * mutation (disable, config, slug) stays open server-side on purpose.
- */
- publishable: boolean;
- /** Whether the share management surface applies to this agent at all. */
- supported: boolean;
- /**
- * Whether the share entry (profile tab, header action, settings page) should
- * be shown to this account: `true` when it may publish OR already has a live
- * share to revoke, `false` when neither, `undefined` while the live-share
- * lookup for a non-publishable account is still resolving.
- */
- visible: boolean | undefined;
-}
-
-/**
- * Whether this agent can be shared as a public link at all — the capability
- * half of the gate only, deliberately excluding the caller's edit permission so
- * every entry point (header action, tab switcher, the page itself) can combine
- * it with the `canConfigure` check it already computes.
- *
- * Agent sharing is personal-only — `agentShares` rows can never exist for a
- * workspace agent (see `AgentShareModel`'s ownership check) — and a builtin row
- * (Inbox, the builders) is not the owner's to hand out.
- *
- * `supported` additionally requires `enableBusinessFeatures`: a self-hosted
- * (OSS) deployment has no Agent Share surface at all — it is structurally
- * blocked server-side by `ENABLE_BUSINESS_FEATURES`
- * (`_helpers/agentShareFeatureGate.ts`).
- *
- * `enableAgentShare` (the CLOUD grayscale rollout flag) does NOT narrow
- * `supported` either: the server keeps disable / updateConfig / updateSlug /
- * getShareStatus open when that flag is off, so an owner rolled back out of
- * the allowlist with a live share must still be able to revoke it. Instead the
- * flag drives two derived values — `publishable` (fails closed on anything
- * other than `true`, mirroring the server's `assertAgentShareCreationEnabled`)
- * and `visible` (publishable, or a live share to revoke) — so an account
- * outside the allowlist with nothing live sees no share entry at all.
- */
-export const useAgentShareSupported = (agentId?: string | null): AgentShareSupport => {
- const hasActiveWorkspace = useHasActiveWorkspace();
- const isBuiltinAgent = useAgentStore(builtinAgentSelectors.isBuiltinAgent(agentId ?? undefined));
- const enableAgentShare = useServerConfigStore(featureFlagsSelectors).enableAgentShare;
- const enableBusinessFeatures = useServerConfigStore(serverConfigSelectors.enableBusinessFeatures);
-
- const supported = !!agentId && !hasActiveWorkspace && !isBuiltinAgent && enableBusinessFeatures;
- const publishable = supported && enableAgentShare === true;
-
- // Outside the rollout allowlist the entry is hidden entirely — unless a live
- // share already exists, which the owner must still be able to reach and
- // revoke. The status lookup only runs for that non-publishable case, so the
- // allowlisted majority pays nothing extra here.
- const { data: share } = useSWR(
- supported && !publishable && agentId ? shareKeys.agentShareStatus(agentId) : null,
- () => agentShareService.getShareStatus(agentId!),
- { revalidateOnFocus: false },
- );
-
- let visible: boolean | undefined;
- if (!supported) visible = false;
- else if (publishable) visible = true;
- else if (share !== undefined) visible = share?.visibility === 'link';
-
- return { publishable, supported, visible };
-};
-
-/**
- * How the link on/off switch behaves under the publish gate.
- *
- * Only *publishing* is blocked: a share that is already live must stay
- * togglable so its owner can revoke it after losing the capability (the server
- * keeps `agentShare.disable` open for exactly that case).
- */
-export const resolveLinkToggleState = ({
- isShared,
- publishable,
-}: {
- isShared: boolean;
- publishable: boolean;
-}) => {
- const publishBlocked = !publishable && !isShared;
-
- return {
- /** Blocks the `off → on` direction, never `on → off`. */
- canPublish: !publishBlocked,
- disabled: publishBlocked,
- offHintKey: publishBlocked
- ? ('share.settings.link.publishDisabled' as const)
- : ('share.settings.link.offHint' as const),
- };
-};
diff --git a/src/features/AgentShareSettings/useDebouncedLimitPatch.test.ts b/src/features/AgentShareSettings/useDebouncedLimitPatch.test.ts
deleted file mode 100644
index f3708c34e9b..00000000000
--- a/src/features/AgentShareSettings/useDebouncedLimitPatch.test.ts
+++ /dev/null
@@ -1,191 +0,0 @@
-/**
- * @vitest-environment happy-dom
- */
-import { act, renderHook } from '@testing-library/react';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { resolveLimitCommitTarget, useDebouncedLimitPatch } from './useDebouncedLimitPatch';
-
-beforeEach(() => {
- vi.useFakeTimers();
-});
-
-afterEach(() => {
- vi.useRealTimers();
-});
-
-describe('useDebouncedLimitPatch', () => {
- it('merges both fields into one patch after the delay', () => {
- const commit = vi.fn();
- const { result } = renderHook(() => useDebouncedLimitPatch('agent-1', commit));
-
- act(() => {
- result.current({ maxTopicsPerVisitor: 3 });
- result.current({ maxTurnsPerTopic: 9 });
- vi.advanceTimersByTime(500);
- });
-
- expect(commit).toHaveBeenCalledTimes(1);
- expect(commit).toHaveBeenCalledWith({ maxTopicsPerVisitor: 3, maxTurnsPerTopic: 9 }, 'agent-1');
- });
-
- it('keeps the newest value for a field edited twice', () => {
- const commit = vi.fn();
- const { result } = renderHook(() => useDebouncedLimitPatch('agent-1', commit));
-
- act(() => {
- result.current({ maxTurnsPerTopic: 9 });
- result.current({ maxTurnsPerTopic: 11 });
- vi.advanceTimersByTime(500);
- });
-
- expect(commit).toHaveBeenCalledWith({ maxTurnsPerTopic: 11 }, 'agent-1');
- });
-
- it('flushes a pending patch on unmount so a fast close does not lose the edit', () => {
- const commit = vi.fn();
- const { result, unmount } = renderHook(() => useDebouncedLimitPatch('agent-1', commit));
-
- act(() => {
- result.current({ maxTopicsPerVisitor: 4 });
- });
- expect(commit).not.toHaveBeenCalled();
-
- act(() => {
- unmount();
- });
-
- expect(commit).toHaveBeenCalledWith({ maxTopicsPerVisitor: 4 }, 'agent-1');
- });
-
- it('does not commit again on unmount once the timer already fired', () => {
- const commit = vi.fn();
- const { result, unmount } = renderHook(() => useDebouncedLimitPatch('agent-1', commit));
-
- act(() => {
- result.current({ maxTopicsPerVisitor: 4 });
- vi.advanceTimersByTime(500);
- });
- act(() => {
- unmount();
- });
-
- expect(commit).toHaveBeenCalledTimes(1);
- });
-
- it('settles the caller even when the commit rejects', async () => {
- const commit = vi.fn().mockRejectedValue(new Error('save failed'));
- const settled = vi.fn();
- const { result } = renderHook(() => useDebouncedLimitPatch('agent-1', commit, settled));
-
- act(() => {
- result.current({ maxTurnsPerTopic: 7 });
- vi.advanceTimersByTime(500);
- });
- await act(async () => {
- await vi.runAllTimersAsync();
- });
-
- expect(settled).toHaveBeenCalledWith({ maxTurnsPerTopic: 7 });
- });
-
- it('flushes a pending patch through the previous identity onCommit when the identity changes, never through the new one', () => {
- // Regression: the share settings page is not remounted when navigating
- // agent A's share page -> agent B's, so without identity scoping A's
- // still-pending edit would flush through B's onCommit within the debounce
- // window instead of A's.
- const commitA = vi.fn();
- const commitB = vi.fn();
-
- const { result, rerender } = renderHook(
- ({ agentId, commit }) => useDebouncedLimitPatch(agentId, commit),
- { initialProps: { agentId: 'agent-a', commit: commitA } },
- );
-
- act(() => {
- result.current({ maxTopicsPerVisitor: 4 });
- });
- expect(commitA).not.toHaveBeenCalled();
-
- act(() => {
- rerender({ agentId: 'agent-b', commit: commitB });
- });
-
- expect(commitA).toHaveBeenCalledWith({ maxTopicsPerVisitor: 4 }, 'agent-a');
- expect(commitB).not.toHaveBeenCalled();
-
- // Nothing pending should carry over: advancing time after the identity
- // switch must not trigger anything for either agent.
- act(() => {
- vi.advanceTimersByTime(500);
- });
- expect(commitA).toHaveBeenCalledTimes(1);
- expect(commitB).not.toHaveBeenCalled();
- });
-
- it('reports the PREVIOUS identity to onCommit when the identity change triggers the flush', () => {
- // The caller needs the owning identity to route the write: agent A's patch
- // must not go through the shared queue that has already re-scoped to B.
- const commit = vi.fn();
- const { result, rerender } = renderHook(
- ({ agentId }) => useDebouncedLimitPatch(agentId, commit),
- {
- initialProps: { agentId: 'agent-a' },
- },
- );
-
- act(() => {
- result.current({ maxTurnsPerTopic: 6 });
- });
- act(() => {
- rerender({ agentId: 'agent-b' });
- });
-
- expect(commit).toHaveBeenCalledWith({ maxTurnsPerTopic: 6 }, 'agent-a');
- });
-
- it('reports the current identity for a patch scheduled after the switch', () => {
- const commit = vi.fn();
- const { result, rerender } = renderHook(
- ({ agentId }) => useDebouncedLimitPatch(agentId, commit),
- {
- initialProps: { agentId: 'agent-a' },
- },
- );
-
- act(() => {
- rerender({ agentId: 'agent-b' });
- });
- act(() => {
- result.current({ maxTurnsPerTopic: 8 });
- vi.advanceTimersByTime(500);
- });
-
- expect(commit).toHaveBeenCalledTimes(1);
- expect(commit).toHaveBeenCalledWith({ maxTurnsPerTopic: 8 }, 'agent-b');
- });
-
- it('reports the current identity on the unmount flush', () => {
- const commit = vi.fn();
- const { result, unmount } = renderHook(() => useDebouncedLimitPatch('agent-1', commit));
-
- act(() => {
- result.current({ maxTopicsPerVisitor: 2 });
- });
- act(() => {
- unmount();
- });
-
- expect(commit).toHaveBeenCalledWith({ maxTopicsPerVisitor: 2 }, 'agent-1');
- });
-});
-
-describe('resolveLimitCommitTarget', () => {
- it('routes a patch owned by the rendered agent through the shared queue', () => {
- expect(resolveLimitCommitTarget('agent-a', 'agent-a')).toBe('current');
- });
-
- it('routes a patch owned by an abandoned agent to its own write path', () => {
- expect(resolveLimitCommitTarget('agent-a', 'agent-b')).toBe('previous');
- });
-});
diff --git a/src/features/AgentShareSettings/useDebouncedLimitPatch.ts b/src/features/AgentShareSettings/useDebouncedLimitPatch.ts
deleted file mode 100644
index ac84aae86c0..00000000000
--- a/src/features/AgentShareSettings/useDebouncedLimitPatch.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-import { useCallback, useEffect, useRef } from 'react';
-
-import type { AgentShareConfigPatchInput } from '@/services/agentShare';
-
-export type AgentShareLimitField = 'maxTopicsPerVisitor' | 'maxTurnsPerTopic' | 'monthlySpendLimit';
-export type AgentShareLimitPatch = Pick<AgentShareConfigPatchInput, AgentShareLimitField>;
-
-const LIMIT_COMMIT_DELAY = 500;
-
-/**
- * Which write path a flushed patch belongs to, given the identity the patch was
- * scheduled under and the identity the component currently renders.
- *
- * `'previous'` means the flush was triggered BY the identity change itself, so
- * the patch belongs to the agent that was just navigated away from and must not
- * go through the (already re-scoped) shared write queue.
- */
-export const resolveLimitCommitTarget = (
- commitIdentity: string,
- currentIdentity: string,
-): 'current' | 'previous' => (commitIdentity === currentIdentity ? 'current' : 'previous');
-
-/**
- * Debounces the numeric limit inputs into a single patch and flushes it on
- * unmount. One shared pending patch keeps one field from cancelling another,
- * and the unmount flush keeps closing the modal right after typing from
- * discarding the last valid edit.
- *
- * `identityKey` scopes the pending patch to whatever it was created for
- * (typically the agent id). The settings page component is not remounted when
- * navigating between two agents' share pages — it just receives new props, so
- * without this the refs below would carry agent A's still-pending edit into
- * agent B's `onCommit`. See {@link flush}'s call from the identity-change
- * check for how the previous identity's edit is drained before that happens.
- *
- * `onCommit` therefore receives the identity the patch was scheduled under as
- * its second argument — the PREVIOUS one when the flush was triggered by an
- * identity change. Callers must route such a patch to that identity's own
- * write path instead of the (already re-scoped) shared one; see
- * {@link resolveLimitCommitTarget}.
- */
-export const useDebouncedLimitPatch = (
- identityKey: string,
- onCommit: (patch: AgentShareLimitPatch, commitIdentity: string) => Promise<void> | void,
- onSettled?: (patch: AgentShareLimitPatch) => void,
-) => {
- const onCommitRef = useRef(onCommit);
- const onSettledRef = useRef(onSettled);
- const pendingRef = useRef<AgentShareLimitPatch>({});
- const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- const identityRef = useRef(identityKey);
-
- const flush = useCallback(() => {
- if (timerRef.current) clearTimeout(timerRef.current);
- timerRef.current = null;
-
- const patch = pendingRef.current;
- pendingRef.current = {};
- if (Object.keys(patch).length === 0) return;
-
- const settle = onSettledRef.current;
- // Not `identityKey`: `flush` is called from the identity-change check
- // BEFORE `identityRef` is advanced, so this is exactly the identity the
- // pending patch was scheduled under in every call path.
- const commitIdentity = identityRef.current;
- void Promise.resolve(onCommitRef.current(patch, commitIdentity))
- .catch(() => undefined)
- .finally(() => settle?.(patch));
- }, []);
-
- // `identityKey` changed since the last render (e.g. navigating agent A's
- // share page -> agent B's without this component unmounting): drain
- // whatever is pending through the PREVIOUS identity's `onCommit`/`onSettled`
- // — both refs below still hold them here, since they are not reassigned
- // until right after. Comparing against `identityRef` (rather than
- // unconditionally flushing every render) makes this idempotent under
- // StrictMode's render double-invocation — the refs persist across the two
- // calls, so the second sees `identityRef.current === identityKey` already
- // and is a no-op.
- if (identityRef.current !== identityKey) {
- flush();
- identityRef.current = identityKey;
- }
-
- onCommitRef.current = onCommit;
- onSettledRef.current = onSettled;
-
- useEffect(() => flush, [flush]);
-
- const schedule = useCallback(
- (patch: AgentShareLimitPatch) => {
- pendingRef.current = { ...pendingRef.current, ...patch };
- if (timerRef.current) clearTimeout(timerRef.current);
- timerRef.current = setTimeout(flush, LIMIT_COMMIT_DELAY);
- },
- [flush],
- );
-
- return schedule;
-};
diff --git a/src/features/AgentShareSettings/useShareSettingsTab.test.ts b/src/features/AgentShareSettings/useShareSettingsTab.test.ts
deleted file mode 100644
index 827ad37cbf0..00000000000
--- a/src/features/AgentShareSettings/useShareSettingsTab.test.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import { parseShareSettingsTab } from './useShareSettingsTab';
-
-describe('parseShareSettingsTab', () => {
- it('resolves the stats tab', () => {
- expect(parseShareSettingsTab('stats')).toBe('stats');
- });
-
- it.each([null, undefined, '', 'access', 'unknown', 'STATS'])(
- 'falls back to access for %p',
- (value) => {
- expect(parseShareSettingsTab(value)).toBe('access');
- },
- );
-});
diff --git a/src/features/AgentShareSettings/useShareSettingsTab.ts b/src/features/AgentShareSettings/useShareSettingsTab.ts
deleted file mode 100644
index a983cafb1e3..00000000000
--- a/src/features/AgentShareSettings/useShareSettingsTab.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { useCallback } from 'react';
-import { useSearchParams } from 'react-router';
-
-export type ShareSettingsTab = 'access' | 'stats';
-
-export const SHARE_SETTINGS_TAB_PARAM = 'tab';
-
-const DEFAULT_TAB: ShareSettingsTab = 'access';
-
-/** Anything but the one non-default value falls back, so a mistyped url never renders an empty page. */
-export const parseShareSettingsTab = (value: string | null | undefined): ShareSettingsTab =>
- value === 'stats' ? 'stats' : DEFAULT_TAB;
-
-/**
- * Active tab of the share settings page, kept in the `?tab=` search param so
- * the stats view is deep-linkable (e.g. from a spend-cap notification) and
- * survives a reload. The default tab is stored as the ABSENCE of the param to
- * keep the canonical url clean; switching uses `replace` so the tabs do not
- * pile up in browser history.
- */
-export const useShareSettingsTab = (): [ShareSettingsTab, (tab: ShareSettingsTab) => void] => {
- const [searchParams, setSearchParams] = useSearchParams();
- const active = parseShareSettingsTab(searchParams.get(SHARE_SETTINGS_TAB_PARAM));
-
- const setActive = useCallback(
- (tab: ShareSettingsTab) => {
- setSearchParams(
- (prev) => {
- const next = new URLSearchParams(prev);
- if (tab === DEFAULT_TAB) next.delete(SHARE_SETTINGS_TAB_PARAM);
- else next.set(SHARE_SETTINGS_TAB_PARAM, tab);
- return next;
- },
- { replace: true },
- );
- },
- [setSearchParams],
- );
-
- return [active, setActive];
-};
diff --git a/src/features/AgentShareSettings/useShareUsage.test.ts b/src/features/AgentShareSettings/useShareUsage.test.ts
deleted file mode 100644
index e0bfe5b08ba..00000000000
--- a/src/features/AgentShareSettings/useShareUsage.test.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-/**
- * @vitest-environment happy-dom
- */
-import { renderHook } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { useShareUsage } from './useShareUsage';
-
-const swrState = vi.hoisted(() => ({
- data: undefined as any,
- error: undefined as unknown,
- isLoading: false,
- isValidating: false,
- mutate: vi.fn(),
-}));
-
-vi.mock('swr', () => ({ default: () => swrState }));
-vi.mock('@/services/agentShare', () => ({ agentShareService: { getShareStats: vi.fn() } }));
-vi.mock('@/libs/swr/keys', () => ({
- shareKeys: { agentShareStats: (agentId: string) => ['share:agentShareStats', agentId] },
-}));
-
-const stats = {
- monthlySpend: 4,
- monthlySpendLimit: 10,
- topicCount: 1,
- userViewCount: 2,
- visitorCount: 1,
-};
-
-describe('useShareUsage', () => {
- beforeEach(() => {
- swrState.data = undefined;
- swrState.error = undefined;
- swrState.isLoading = false;
- });
-
- // A failed roll-up used to fall through to `0 / 0 / 0`, which reads as a
- // genuine "nobody used it, nothing was spent" claim.
- it('surfaces a load error instead of zero usage when the stats request fails', () => {
- swrState.error = new Error('boom');
-
- const { result } = renderHook(() => useShareUsage('agent-1'));
-
- expect(result.current.hasLoadError).toBe(true);
- expect(result.current.data).toBeUndefined();
- });
-
- it('keeps showing stale stats while a revalidation fails', () => {
- swrState.data = stats;
- swrState.error = new Error('boom');
-
- const { result } = renderHook(() => useShareUsage('agent-1'));
-
- expect(result.current.hasLoadError).toBe(false);
- expect(result.current.spend).toBe(4);
- });
-
- // The stats payload carries its own copy of the cap under a different SWR
- // key that the owner's edits never invalidate; the live configured value
- // from the share-status cache must win so the label tracks the edit.
- it('prefers the live configured cap over the copy in the stats payload', () => {
- swrState.data = stats;
-
- const { result } = renderHook(() => useShareUsage('agent-1', 25));
-
- expect(result.current.limit).toBe(25);
- });
-
- it('falls back to the cap reported by the stats payload', () => {
- swrState.data = stats;
-
- const { result } = renderHook(() => useShareUsage('agent-1'));
-
- expect(result.current.limit).toBe(10);
- });
-});
diff --git a/src/features/AgentShareSettings/useShareUsage.ts b/src/features/AgentShareSettings/useShareUsage.ts
deleted file mode 100644
index df5f526fdb9..00000000000
--- a/src/features/AgentShareSettings/useShareUsage.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import useSWR from 'swr';
-
-import { shareKeys } from '@/libs/swr/keys';
-import { agentShareService } from '@/services/agentShare';
-
-/**
- * Loads the share usage roll-up and resolves which spend cap to display.
- *
- * @param monthlySpendLimit The cap as currently configured in `LimitsSection`,
- * from the share-status cache the owner's edits write to. The stats payload
- * carries its own copy, but that lives under a different SWR key that no
- * edit invalidates, so the label and bar would keep the OLD cap until a
- * reload without it.
- */
-export const useShareUsage = (agentId: string, monthlySpendLimit?: number) => {
- const { data, error, isLoading, isValidating, mutate } = useSWR(
- shareKeys.agentShareStats(agentId),
- () => agentShareService.getShareStats(agentId),
- { revalidateOnFocus: false },
- );
-
- return {
- data,
- error,
- // A failed roll-up must not read as "no traffic, nothing spent": zeros
- // there are a money claim, so the failure has to stay visible.
- hasLoadError: !!error && !data,
- isLoading: isLoading && !data,
- isValidating,
- // Every share carries a cap, so this is only ever absent while the stats
- // request is still in flight.
- limit: monthlySpendLimit ?? data?.monthlySpendLimit,
- mutate,
- // `null` means this deployment does not meter share spend.
- spend: data?.monthlySpend ?? null,
- };
-};
diff --git a/src/features/AgentShareVisitor/Page.tsx b/src/features/AgentShareVisitor/Page.tsx
deleted file mode 100644
index 066c94f450b..00000000000
--- a/src/features/AgentShareVisitor/Page.tsx
+++ /dev/null
@@ -1,218 +0,0 @@
-'use client';
-
-import { DEFAULT_AVATAR } from '@lobechat/const';
-import { agentDisplayName } from '@lobechat/types';
-import { Center, Flexbox } from '@lobehub/ui';
-import { ActionIcon, Avatar, Button, Drawer, Text } from '@lobehub/ui/base-ui';
-import { cssVar } from 'antd-style';
-import { PanelLeftOpen } from 'lucide-react';
-import { memo, type PropsWithChildren, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Navigate, useNavigate, useParams } from 'react-router';
-
-import AsyncError from '@/components/AsyncError';
-import { RouteMetaBridge } from '@/features/RouteMeta';
-import { useIsMobile } from '@/hooks/useIsMobile';
-import { useRouteSkeleton } from '@/spa/router/useRouteSkeleton';
-
-import { resolveShareAccessState, SHARE_ACCESS_ERROR_KEYS } from './resolveShareAccessState';
-import { isShareInteractive } from './shareInteractivity';
-import TopicPanel from './TopicPanel';
-import { useSharedAgent } from './useSharedAgent';
-import VisitorConversation from './VisitorConversation';
-import { buildAgentShareOwnerPath, buildAgentShareSignInUrl } from './visitorPath';
-import VisitorTopBar from './VisitorTopBar';
-
-const SIDEBAR_WIDTH = 260;
-
-/**
- * Product bar plus the page body below it. Every state of the page — the
- * conversation, the sign-in prompt, the dead-link card — sits inside the same
- * frame, so the bar never appears or disappears as the share resolves.
- */
-const VisitorShell = ({
- children,
- horizontal,
- slugOrId,
-}: PropsWithChildren<{ horizontal?: boolean; slugOrId?: string }>) => (
- <Flexbox height={'100%'} style={{ overflow: 'hidden' }} width={'100%'}>
- <RouteMetaBridge />
- <VisitorTopBar slugOrId={slugOrId} />
- <Flexbox
- flex={1}
- horizontal={horizontal}
- style={{ minHeight: 0, overflow: 'hidden' }}
- width={'100%'}
- >
- {children}
- </Flexbox>
- </Flexbox>
-);
-
-/**
- * Visitor landing page of an agent share (`/a/:slugOrId`): the product bar on
- * top, topic list on the left (a drawer on mobile), the shared agent's
- * conversation on the right. Deliberately a trimmed shell — no agent switcher,
- * task list, working sidebar, terminal, or model picker.
- *
- * Registered as a sibling of the main layout, so nothing of the creator-side
- * chrome (nav rail, workspace scope, command palette) is mounted around it;
- * the route-meta bridge that layout would normally provide is mounted here.
- */
-const AgentShareVisitorPage = memo(() => {
- const { t } = useTranslation('agent');
- const { slugOrId, topicId } = useParams<{ slugOrId: string; topicId: string }>();
- const navigate = useNavigate();
- const isMobile = useIsMobile();
- const RouteSkeleton = useRouteSkeleton();
- const [drawerOpen, setDrawerOpen] = useState(false);
-
- const { data, error, isLoading, mutate } = useSharedAgent(slugOrId);
-
- /**
- * Reuse the route-owned fallback while data loads. Importing that skeleton
- * back into this lazy page changes the initial shell's shared chunk graph.
- */
- if (isLoading && !data) return RouteSkeleton ? <RouteSkeleton /> : null;
-
- if (error || !data) {
- const state = resolveShareAccessState(error);
-
- if (state === 'signIn') {
- const signInUrl = buildAgentShareSignInUrl(slugOrId ?? '', topicId);
-
- return (
- <VisitorShell slugOrId={slugOrId}>
- <Center gap={16} height={'100%'} padding={24}>
- <Text fontSize={16} weight={600}>
- {t('share.visitor.access.signInTitle')}
- </Text>
- <Text style={{ maxWidth: 360, textAlign: 'center' }} type={'secondary'}>
- {t('share.visitor.access.signInDesc')}
- </Text>
- <Button href={signInUrl} size={'large'} type={'primary'}>
- {t('share.visitor.access.signInCta')}
- </Button>
- </Center>
- </VisitorShell>
- );
- }
-
- const title =
- state === 'generic'
- ? undefined
- : t(SHARE_ACCESS_ERROR_KEYS[state] as 'share.visitor.access.notFound');
-
- return (
- <VisitorShell slugOrId={slugOrId}>
- <Center height={'100%'} padding={24}>
- <AsyncError
- error={error}
- title={title}
- variant={'page'}
- // A missing / forbidden share never becomes available by retrying,
- // so there is no `onRetry` for those states — the `action` button
- // below is the visitor's only way out of the dead end.
- action={
- state === 'generic' ? undefined : (
- <Button size={'small'} onClick={() => navigate('/')}>
- {t('share.visitor.access.backHome')}
- </Button>
- )
- }
- onRetry={state === 'generic' ? () => void mutate() : undefined}
- />
- </Center>
- </VisitorShell>
- );
- }
-
- // The creator is never a visitor of their own share: the visitor chrome
- // (empty topic list, "runs on the creator's account" notice) is meaningless
- // to them, so send them to the share settings instead.
- if (data.isOwner)
- return <Navigate replace to={buildAgentShareOwnerPath(data.agentId, { mobile: isMobile })} />;
-
- const interactive = isShareInteractive(data.visibility);
-
- return (
- <VisitorShell horizontal slugOrId={slugOrId}>
- {!isMobile && (
- <Flexbox
- style={{ borderInlineEnd: `1px solid ${cssVar.colorBorderSecondary}` }}
- width={SIDEBAR_WIDTH}
- >
- <TopicPanel enabled={interactive} shareId={data.shareId} />
- </Flexbox>
- )}
- <Flexbox flex={1} style={{ overflow: 'hidden' }}>
- <Flexbox
- horizontal
- align={'center'}
- gap={8}
- padding={12}
- style={{ borderBlockEnd: `1px solid ${cssVar.colorBorderSecondary}` }}
- >
- {isMobile && (
- <ActionIcon
- icon={PanelLeftOpen}
- title={t('share.visitor.topics.title')}
- onClick={() => setDrawerOpen(true)}
- />
- )}
- <Avatar
- // Same fallback the conversation's welcome block uses, so an agent
- // without a custom avatar does not degrade to "UN" initials here.
- avatar={data.agentMeta.avatar ?? DEFAULT_AVATAR}
- background={data.agentMeta.backgroundColor ?? undefined}
- size={28}
- />
- <Flexbox flex={1} style={{ overflow: 'hidden' }}>
- <Text ellipsis weight={500}>
- {agentDisplayName(data.agentMeta)}
- </Text>
- {data.agentMeta.description && (
- <Text ellipsis fontSize={12} type={'secondary'}>
- {data.agentMeta.description}
- </Text>
- )}
- </Flexbox>
- </Flexbox>
- {/* Always shown, never dismissible: the visitor is chatting inside the
- creator's account, so "the creator may be able to read this" is a
- standing fact about the surface, not a one-time tip. */}
- <Flexbox
- paddingBlock={6}
- paddingInline={12}
- style={{ background: cssVar.colorFillQuaternary }}
- >
- <Text fontSize={12} type={'secondary'}>
- {t('share.visitor.privacyNotice')}
- </Text>
- </Flexbox>
- <VisitorConversation data={data} />
- </Flexbox>
- {isMobile && (
- <Drawer
- open={drawerOpen}
- placement={'left'}
- title={t('share.visitor.topics.title')}
- width={280}
- onClose={() => setDrawerOpen(false)}
- >
- {/* The Drawer already renders the title bar — skip the panel's own. */}
- <TopicPanel
- enabled={interactive}
- shareId={data.shareId}
- showTitle={false}
- onSelect={() => setDrawerOpen(false)}
- />
- </Drawer>
- )}
- </VisitorShell>
- );
-});
-
-AgentShareVisitorPage.displayName = 'AgentShareVisitorPage';
-
-export default AgentShareVisitorPage;
diff --git a/src/features/AgentShareVisitor/ReadOnlyConversationArea.tsx b/src/features/AgentShareVisitor/ReadOnlyConversationArea.tsx
deleted file mode 100644
index fa674410570..00000000000
--- a/src/features/AgentShareVisitor/ReadOnlyConversationArea.tsx
+++ /dev/null
@@ -1,67 +0,0 @@
-'use client';
-
-import { Flexbox } from '@lobehub/ui';
-import { memo, useMemo } from 'react';
-
-import ReadOnlyAgentHome from '@/features/AgentHome/ReadOnly';
-import { ChatList, ConversationProvider } from '@/features/Conversation';
-import { useOperationState } from '@/hooks/useOperationState';
-import { useChatStore } from '@/store/chat';
-import { messageMapKey } from '@/store/chat/utils/messageMapKey';
-
-interface ReadOnlyConversationAreaProps {
- agentId: string;
- agentShareId: string;
- /** The visitor's currently opened share topic; absent on the new-topic surface. */
- topicId?: string | null;
-}
-
-/**
- * Read-only shared-agent message surface.
- *
- * This intentionally does not import the owner's ConversationArea: that surface
- * statically owns the composer, dispatchers, and runtime watchers. Keeping the
- * visitor path separate prevents those owner-scoped side effects (agent
- * switching, tasks, working sidebar, terminal) from mounting on a share page.
- */
-const ReadOnlyConversationArea = memo<ReadOnlyConversationAreaProps>(
- ({ agentId, agentShareId, topicId }) => {
- const context = useMemo(
- () => ({ agentId, agentShareId, scope: 'main' as const, topicId: topicId ?? undefined }),
- [agentId, agentShareId, topicId],
- );
- const chatKey = useMemo(() => messageMapKey(context), [context]);
- const replaceMessages = useChatStore((state) => state.replaceMessages);
- const messages = useChatStore((state) => state.dbMessagesMap[chatKey]);
- // Same feed the owner surface uses (`ConversationArea.tsx`). Without it the
- // per-conversation store stays on the all-false default, so the list never
- // sees "generating": the assistant placeholder renders nothing and the
- // streaming fade-in (`useChatMarkdown`'s `animated`) is permanently off,
- // which is what made visitor output look choppy.
- const operationState = useOperationState(context);
-
- return (
- <ConversationProvider
- context={context}
- hasInitMessages={!!messages}
- messages={messages}
- operationState={operationState}
- onMessagesChange={(nextMessages, nextContext, meta) => {
- replaceMessages(nextMessages, { context: nextContext, source: meta?.source });
- }}
- >
- <Flexbox
- flex={1}
- style={{ overflowX: 'hidden', overflowY: 'auto', position: 'relative' }}
- width={'100%'}
- >
- <ChatList disableActionsBar welcome={<ReadOnlyAgentHome />} />
- </Flexbox>
- </ConversationProvider>
- );
- },
-);
-
-ReadOnlyConversationArea.displayName = 'ReadOnlyConversationArea';
-
-export default ReadOnlyConversationArea;
diff --git a/src/features/AgentShareVisitor/TopicPanel.tsx b/src/features/AgentShareVisitor/TopicPanel.tsx
deleted file mode 100644
index 7b6c5d334e6..00000000000
--- a/src/features/AgentShareVisitor/TopicPanel.tsx
+++ /dev/null
@@ -1,125 +0,0 @@
-'use client';
-
-import { Center, Flexbox } from '@lobehub/ui';
-import { ActionIcon, SkeletonText, Text } from '@lobehub/ui/base-ui';
-import { createStaticStyles, cssVar, cx } from 'antd-style';
-import { MessageSquarePlus } from 'lucide-react';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import AsyncError from '@/components/AsyncError';
-
-import { getTopicPanelViewState } from './topicPanelViewState';
-import { isTopicRowActivationKey } from './topicRowActivation';
-import { useVisitorTopicRoute } from './useVisitorTopicRoute';
-import { useVisitorTopics } from './useVisitorTopics';
-
-/** Placeholder rows shown while the visitor's topic list is loading, sized like a typical topic title. */
-const LOADING_ROW_WIDTHS = ['80%', '55%', '68%'];
-
-const styles = createStaticStyles(({ css }) => ({
- row: css`
- cursor: pointer;
- border-radius: 6px;
-
- &:focus-visible {
- outline: 2px solid ${cssVar.colorPrimary};
- outline-offset: -1px;
- }
- `,
- rowActive: css`
- background: ${cssVar.colorFillSecondary};
- `,
-}));
-
-/**
- * The visitor's topic list under the current share (server-scoped by
- * senderId). Selection follows the URL so bookmarks, refreshes, and browser
- * history open the same conversation as the highlighted row.
- */
-const TopicPanel = memo<{
- /** Off for a non-interactive share (owner preview): skips the fetch that would only 403. */
- enabled?: boolean;
- onSelect?: () => void;
- shareId: string;
- showTitle?: boolean;
-}>(({ enabled = true, onSelect, shareId, showTitle = true }) => {
- const { t } = useTranslation('agent');
- const { topicId: activeTopicId, selectTopic: navigateToTopic } = useVisitorTopicRoute();
- const { data: topics, error, isLoading, mutate } = useVisitorTopics(shareId, enabled);
- const viewState = getTopicPanelViewState(topics, error, isLoading);
-
- const selectTopic = (topicId?: string) => {
- navigateToTopic(topicId);
- onSelect?.();
- };
-
- return (
- <Flexbox gap={8} height={'100%'} padding={12} style={{ overflowY: 'auto' }}>
- <Flexbox horizontal align={'center'} justify={'space-between'}>
- {showTitle && (
- <Text fontSize={12} type={'secondary'} weight={500}>
- {t('share.visitor.topics.title')}
- </Text>
- )}
- <ActionIcon
- icon={MessageSquarePlus}
- size={'small'}
- title={t('share.visitor.topics.new')}
- onClick={() => selectTopic(undefined)}
- />
- </Flexbox>
- {viewState === 'error' ? (
- <Center flex={1}>
- <AsyncError error={error} variant={'inline'} onRetry={() => mutate()} />
- </Center>
- ) : viewState === 'loading' ? (
- <Flexbox gap={4}>
- {LOADING_ROW_WIDTHS.map((width, index) => (
- <Flexbox key={index} paddingBlock={6} paddingInline={8}>
- <SkeletonText style={{ marginBottom: 0, width }} />
- </Flexbox>
- ))}
- </Flexbox>
- ) : viewState === 'empty' ? (
- <Center flex={1}>
- <Text fontSize={12} type={'secondary'}>
- {t('share.visitor.topics.empty')}
- </Text>
- </Center>
- ) : (
- (topics ?? []).map((topic) => {
- const active = topic.id === activeTopicId;
- return (
- <Flexbox
- aria-current={active || undefined}
- className={cx(styles.row, active && styles.rowActive)}
- key={topic.id}
- paddingBlock={6}
- paddingInline={8}
- role={'button'}
- tabIndex={0}
- onClick={() => selectTopic(topic.id)}
- onKeyDown={(e) => {
- // Mirror native button keyboard semantics for the div-as-button row.
- if (!isTopicRowActivationKey(e.key)) return;
- // Space's default action scrolls the page; Enter has no default
- // action on a non-form div, so only Space needs suppressing.
- if (e.key === ' ') e.preventDefault();
- selectTopic(topic.id);
- }}
- >
- <Text ellipsis fontSize={13}>
- {topic.title || t('share.visitor.topics.untitled')}
- </Text>
- </Flexbox>
- );
- })
- )}
- </Flexbox>
- );
-});
-
-TopicPanel.displayName = 'ShareVisitorTopicPanel';
-
-export default TopicPanel;
diff --git a/src/features/AgentShareVisitor/VisitorComposer.tsx b/src/features/AgentShareVisitor/VisitorComposer.tsx
deleted file mode 100644
index 05c070cc753..00000000000
--- a/src/features/AgentShareVisitor/VisitorComposer.tsx
+++ /dev/null
@@ -1,259 +0,0 @@
-'use client';
-
-import { SHARE_VISITOR_PROMPT_MAX_LENGTH } from '@lobechat/const';
-import { Flexbox } from '@lobehub/ui';
-import { Text } from '@lobehub/ui/base-ui';
-import { createStaticStyles, cssVar } from 'antd-style';
-import { memo, useCallback, useEffect, useRef, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import AsyncError from '@/components/AsyncError';
-import {
- type ActionKeys,
- type ChatInputFeature,
- ChatInputProvider,
- DesktopChatInput,
- type SendButtonHandler,
-} from '@/features/ChatInput';
-import WideScreenContainer from '@/features/WideScreenContainer';
-import { useChatStore } from '@/store/chat';
-import { operationSelectors } from '@/store/chat/selectors';
-
-import { isTerminalVisitorError, resolveVisitorErrorKey } from './resolveVisitorErrorKey';
-import { sendVisitorMessage } from './sendVisitorMessage';
-import { useShareRunStop } from './useShareRunStop';
-
-const styles = createStaticStyles(({ css }) => ({
- blocked: css`
- cursor: not-allowed;
-
- padding-block: 10px;
- padding-inline: 14px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: ${cssVar.borderRadiusLG};
-
- background: ${cssVar.colorFillQuaternary};
- `,
-}));
-
-/** Stable empty arrays: a fresh `[]` per render would re-sync the input store every time. */
-const NO_ACTIONS: ActionKeys[] = [];
-
-/**
- * Every editor feature the visitor must NOT get. All four keys are listed on
- * purpose: an omitted key defaults to ON inside `InputEditor`.
- *
- * - slash / mention: both resolve against the OWNER's skills, documents and
- * group members, none of which a visitor can see or call.
- * - inputCompletion: an extra model call on the visitor's own account for a
- * surface that is supposed to bill the creator only.
- * - inputHistory: with the blank agent id (see below) history would land in
- * the visitor's shared "global" bucket and leak into their other composers.
- */
-const VISITOR_FEATURE: ChatInputFeature = {
- inputCompletion: false,
- inputHistory: false,
- mention: false,
- slash: false,
-};
-
-const noop = () => {};
-
-interface VisitorComposerProps {
- agentId: string;
- /**
- * Copy key of a standing block (e.g. the share is no longer link-visible).
- * When set the composer is disabled and the reason is shown persistently —
- * sending would only fail server-side anyway.
- */
- blockedKey?: string;
- /** Refresh the visitor topic list after a send created a new topic. */
- onTopicCreated?: (topicId: string) => void;
- shareId: string;
- topicId?: string | null;
-}
-
-/**
- * Lean visitor composer for shared agents: the product's rich editor
- * (markdown, Enter/Shift+Enter, IME, the user's own Enter-vs-Cmd+Enter
- * preference) without the owner composer graph — no uploads (v1 rejects them
- * server-side anyway), no mentions, no slash actions, no model switcher, no
- * device targets. Just text in, gateway-streamed answer out.
- *
- * The provider is mounted with `agentId=""` rather than the shared agent's id.
- * Several editor hooks treat a non-empty id as "an agent of mine" and fetch its
- * permissions, documents and agency config, which for a foreign agent is a
- * string of rejected requests. The blank id (not `undefined`, which falls back
- * to the visitor's active agent) turns every one of those lookups off; the
- * actual target of a send is the `agentId` prop, passed to
- * {@link sendVisitorMessage} directly.
- */
-const VisitorComposer = memo<VisitorComposerProps>(
- ({ agentId, blockedKey, onTopicCreated, shareId, topicId }) => {
- const { t } = useTranslation('agent');
- const [errorKey, setErrorKey] = useState<string>();
- const [sending, setSending] = useState(false);
- const { stopError, stopping, stopSharedRun } = useShareRunStop(shareId, agentId, topicId);
-
- const isStreaming = useChatStore(
- // messageMapKey ignores agentShareId — the running check keys off the
- // same main_<agentId>_<topicId> bucket the share run registers under.
- operationSelectors.isAgentRuntimeRunningByContext({
- agentId,
- scope: 'main',
- topicId,
- }),
- );
- // A per-attempt failure belongs to the topic it happened in — the turn-limit
- // copy even tells the visitor to start a new conversation, so it must not
- // follow them there. Share-level failures (paused / deleted) do survive:
- // they are true for every topic.
- useEffect(() => {
- setErrorKey((prev) => (prev && isTerminalVisitorError(prev) ? prev : undefined));
- }, [topicId]);
-
- const busy = sending || isStreaming;
- // A share that stopped accepting traffic mid-session blocks the composer the
- // same way an up-front `blockedKey` does, instead of letting the visitor
- // resend into a guaranteed rejection.
- const blocked =
- blockedKey ?? (errorKey && isTerminalVisitorError(errorKey) ? errorKey : undefined);
- const displayedErrorKey = blocked ?? errorKey;
-
- // `sendButtonProps.disabled` is read from the store, which lags a keystroke
- // behind the editor; the Enter handler asks this ref instead so a fast
- // "type → Enter" during a run cannot slip a second send through.
- const busyRef = useRef(busy);
- busyRef.current = busy;
-
- // The editor has no "text only" switch: a pasted image is uploaded to the
- // visitor's own storage and shown as an attachment chip that the share
- // transport would then silently drop. Swallow file pastes before the
- // editor's own paste plugin sees them — a NATIVE capture listener on the
- // wrapper, because Lexical listens natively on the contenteditable and
- // React's delegated `onPasteCapture` would run after it. Text pastes are
- // untouched. A callback ref (not an effect) because the wrapper only
- // exists while the composer is not blocked.
- const attachPasteGuard = useCallback((wrapper: HTMLDivElement | null) => {
- if (!wrapper) return;
- const swallowFilePaste = (event: ClipboardEvent) => {
- if (!event.clipboardData?.files.length) return;
- event.preventDefault();
- event.stopPropagation();
- };
- wrapper.addEventListener('paste', swallowFilePaste, true);
- return () => wrapper.removeEventListener('paste', swallowFilePaste, true);
- }, []);
-
- const send: SendButtonHandler = async ({ clearContent, editor, getMarkdownContent }) => {
- const message = getMarkdownContent().trim();
- if (!message || busyRef.current) return;
-
- // Mirrors `SHARE_VISITOR_PROMPT_MAX_LENGTH` (the server-side gate in
- // `apps/server/src/routers/lambda/shareChat.ts`) so a long paste is
- // rejected up front, with the text kept, instead of round-tripping.
- if (message.length > SHARE_VISITOR_PROMPT_MAX_LENGTH) {
- setErrorKey('share.visitor.errors.promptTooLong');
- return;
- }
-
- setErrorKey(undefined);
- setSending(true);
- clearContent();
- try {
- const result = await sendVisitorMessage({ agentId, message, shareId, topicId });
- if (result.topicId && !topicId) onTopicCreated?.(result.topicId);
- } catch (error) {
- console.error('[AgentShareVisitor] send failed:', error);
- setErrorKey(resolveVisitorErrorKey(error));
- // Give the rejected input back so the visitor can retry / edit.
- editor.setDocument('markdown', message);
- } finally {
- setSending(false);
- }
- };
-
- return (
- // Same centered column as `ChatList` (via `WideScreenContainer`), so the
- // composer's edges line up with the messages above it instead of
- // spanning the full pane on a wide window.
- <WideScreenContainer gap={4} paddingBlock={8}>
- {displayedErrorKey && (
- <Text fontSize={12} type={'danger'}>
- {t(displayedErrorKey as any, {
- // i18next's generated interpolation types default `{{max}}` to
- // `string` (no `{{max, number}}` format specifier), so pass a
- // string even though the source constant is numeric. Ignored by
- // every other error key (i18next drops unused options).
- max: String(SHARE_VISITOR_PROMPT_MAX_LENGTH),
- })}
- </Text>
- )}
- {!!stopError && (
- <AsyncError
- error={stopError}
- retrying={stopping}
- title={t('share.visitor.errors.stopFailed')}
- variant="inline"
- onRetry={() => void stopSharedRun()}
- />
- )}
- {blocked ? (
- // The editor cannot be made read-only from the outside, and a live
- // editor under a "sharing paused" line invites typing into a dead
- // end — so the blocked state is a plain strip, not a disabled input.
- <Flexbox className={styles.blocked}>
- <Text type={'secondary'}>{t('share.visitor.input.placeholder')}</Text>
- </Flexbox>
- ) : (
- <div ref={attachPasteGuard}>
- <ChatInputProvider
- agentId=""
- allowExpand={false}
- feature={VISITOR_FEATURE}
- leftActions={NO_ACTIONS}
- resolveSendBlocked={() => busyRef.current}
- rightActions={NO_ACTIONS}
- sendButtonProps={{
- disabled: busy,
- // A run is actually streaming (as opposed to `sending`, the brief
- // window before the server has even created the operation) — show
- // Stop so a long or unwanted run can be cut off before it keeps
- // burning the creator's share budget. `stopSharedRun` flips the
- // operation's `isAborting` flag as soon as the request goes out,
- // which makes `isStreaming` go false before the interrupt has
- // resolved — keep Stop through `stopping` so it doesn't flicker.
- generating: isStreaming || stopping,
- onStop: () => void stopSharedRun(),
- shape: 'round',
- }}
- onSend={send}
- >
- <DesktopChatInput
- // `false`, not `undefined`: the slot falls back to the owner
- // action bar on `??`.
- leftContent={false}
- // A custom placeholder also skips the default one's
- // workspace-preference fetch.
- placeholder={t('share.visitor.input.placeholder')}
- showControlBar={false}
- inputContainerProps={{
- minHeight: 36,
- // The default handler stores the composer height in the global
- // status the OWNER's composer reads back; a share page must
- // not resize somebody else's input.
- onSizeChange: noop,
- resize: false,
- }}
- />
- </ChatInputProvider>
- </div>
- )}
- </WideScreenContainer>
- );
- },
-);
-
-VisitorComposer.displayName = 'ShareVisitorComposer';
-
-export default VisitorComposer;
diff --git a/src/features/AgentShareVisitor/VisitorConversation.tsx b/src/features/AgentShareVisitor/VisitorConversation.tsx
deleted file mode 100644
index 847afbf298e..00000000000
--- a/src/features/AgentShareVisitor/VisitorConversation.tsx
+++ /dev/null
@@ -1,65 +0,0 @@
-'use client';
-
-import type { SharedAgentData } from '@lobechat/types';
-import { memo } from 'react';
-
-import { useGatewayReconnect } from '@/hooks/useGatewayReconnect';
-
-import ReadOnlyConversationArea from './ReadOnlyConversationArea';
-import { resolveVisitorRunningOperation } from './resolveVisitorRunningOperation';
-import { isShareInteractive } from './shareInteractivity';
-import { useVisitorConversationSeed } from './useVisitorConversationSeed';
-import { useVisitorTopicRoute } from './useVisitorTopicRoute';
-import { useVisitorTopics } from './useVisitorTopics';
-import VisitorComposer from './VisitorComposer';
-
-/**
- * The visitor-facing conversation column: mounts the lean message surface
- * after hand-seeding the stores, plus the share composer wired to the gateway
- * transport via `agentShareId`.
- */
-const VisitorConversation = memo<{ data: SharedAgentData }>(({ data }) => {
- const { agentId, shareId } = data;
- const { topicId: activeTopicId, onTopicCreated } = useVisitorTopicRoute();
- const seeded = useVisitorConversationSeed(data, activeTopicId);
- const interactive = isShareInteractive(data.visibility);
- const { data: topics, mutate: refreshVisitorTopics } = useVisitorTopics(shareId, interactive);
-
- // Reconnects a still-running Gateway stream after a page reload. A
- // non-interactive share (owner preview) never has a live run and its
- // `getTopics` fetch is skipped (see `useVisitorTopics`), so both args are
- // withheld rather than resolved against stale/empty data.
- useGatewayReconnect(
- interactive ? activeTopicId : undefined,
- interactive ? resolveVisitorRunningOperation(topics, activeTopicId) : undefined,
- agentId,
- shareId,
- );
-
- // The message surface reads the active ids on first render — mounting it
- // before the seed lands would fetch against a stale topic left by the main app.
- if (!seeded) return null;
-
- return (
- <>
- <ReadOnlyConversationArea agentId={agentId} agentShareId={shareId} topicId={activeTopicId} />
- <VisitorComposer
- agentId={agentId}
- // An owner previewing their own private share can view it but not chat.
- blockedKey={interactive ? undefined : 'share.visitor.errors.sharingPaused'}
- shareId={shareId}
- // The gateway transport already switched the store to the new topic
- // (`switchTopic`); refreshing the list makes it show up in the panel.
- topicId={activeTopicId}
- onTopicCreated={(createdTopicId) => {
- onTopicCreated(createdTopicId);
- void refreshVisitorTopics();
- }}
- />
- </>
- );
-});
-
-VisitorConversation.displayName = 'ShareVisitorConversation';
-
-export default VisitorConversation;
diff --git a/src/features/AgentShareVisitor/VisitorTopBar.tsx b/src/features/AgentShareVisitor/VisitorTopBar.tsx
deleted file mode 100644
index e8b327ed771..00000000000
--- a/src/features/AgentShareVisitor/VisitorTopBar.tsx
+++ /dev/null
@@ -1,101 +0,0 @@
-'use client';
-
-import { Flexbox } from '@lobehub/ui';
-import { createStaticStyles, cssVar } from 'antd-style';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Link, useParams } from 'react-router';
-
-import { ProductLogo } from '@/components/Branding';
-import UserAvatar from '@/features/User/UserAvatar';
-import { useUserStore } from '@/store/user';
-import { authSelectors } from '@/store/user/selectors';
-
-import { buildAgentShareSignInUrl } from './visitorPath';
-
-const styles = createStaticStyles(({ css }) => ({
- brand: css`
- cursor: pointer;
-
- display: grid;
- place-items: center;
-
- inline-size: 26px;
- block-size: 26px;
- border-radius: ${cssVar.borderRadius};
-
- &:focus-visible {
- outline: 2px solid ${cssVar.colorPrimary};
- outline-offset: 3px;
- }
- `,
- root: css`
- flex: none;
-
- block-size: 48px;
- padding-inline: 12px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
-
- background: ${cssVar.colorBgLayout};
- `,
-}));
-
-interface VisitorTopBarProps {
- /**
- * The share the visitor is looking at, used as the sign-in return target so
- * an anonymous visitor lands back on the same link after signing in.
- */
- slugOrId?: string;
-}
-
-/**
- * Product bar of the agent-share visitor page: the logo on the left, the
- * visitor's own avatar on the right — the same frame the topic share page
- * uses, so a shared agent reads as "a LobeHub page I was linked to", not as an
- * inner pane of someone else's console.
- *
- * The visitor page has its own layout without the main navigation rail, so
- * this bar lets visitors get back to their own LobeHub:
- * both the logo and the avatar go home, or to sign-in when there is no
- * session yet.
- */
-const VisitorTopBar = memo<VisitorTopBarProps>(({ slugOrId }) => {
- const { t } = useTranslation('agent');
- const isSignedIn = useUserStore(authSelectors.isLogin);
- const { topicId } = useParams<{ topicId: string }>();
- const homePath = isSignedIn ? '/' : buildAgentShareSignInUrl(slugOrId ?? '', topicId);
-
- return (
- <Flexbox
- horizontal
- align={'center'}
- className={styles.root}
- gap={8}
- justify={'space-between'}
- width={'100%'}
- >
- <Link
- aria-label={t('share.visitor.topBar.home')}
- className={styles.brand}
- reloadDocument={!isSignedIn}
- to={homePath}
- >
- <ProductLogo size={22} />
- </Link>
- <Link
- className={styles.brand}
- reloadDocument={!isSignedIn}
- to={homePath}
- aria-label={
- isSignedIn ? t('share.visitor.topBar.home') : t('share.visitor.access.signInCta')
- }
- >
- <UserAvatar size={26} />
- </Link>
- </Flexbox>
- );
-});
-
-VisitorTopBar.displayName = 'ShareVisitorTopBar';
-
-export default VisitorTopBar;
diff --git a/src/features/AgentShareVisitor/index.ts b/src/features/AgentShareVisitor/index.ts
deleted file mode 100644
index 8c62be55bf1..00000000000
--- a/src/features/AgentShareVisitor/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export { default as AgentShareVisitorPage } from './Page';
-export { useSharedAgent } from './useSharedAgent';
diff --git a/src/features/AgentShareVisitor/resolveShareAccessState.test.ts b/src/features/AgentShareVisitor/resolveShareAccessState.test.ts
deleted file mode 100644
index d95ab3d774e..00000000000
--- a/src/features/AgentShareVisitor/resolveShareAccessState.test.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { TRPCClientError } from '@trpc/client';
-import { describe, expect, it } from 'vitest';
-
-import { resolveShareAccessState } from './resolveShareAccessState';
-
-const trpcError = (code: string) =>
- new TRPCClientError(code, {
- result: { error: { code: -32_600, data: { code }, message: code } },
- });
-
-describe('resolveShareAccessState', () => {
- it('routes an anonymous visitor to the sign-in prompt rather than an error page', () => {
- expect(resolveShareAccessState(trpcError('UNAUTHORIZED'))).toBe('signIn');
- });
-
- it('maps a missing or disabled share to notFound', () => {
- expect(resolveShareAccessState(trpcError('NOT_FOUND'))).toBe('notFound');
- });
-
- it('maps an access rejection to forbidden', () => {
- expect(resolveShareAccessState(trpcError('FORBIDDEN'))).toBe('forbidden');
- });
-
- it('treats anything else as a retryable generic failure', () => {
- expect(resolveShareAccessState(trpcError('INTERNAL_SERVER_ERROR'))).toBe('generic');
- expect(resolveShareAccessState(new Error('network down'))).toBe('generic');
- expect(resolveShareAccessState(undefined)).toBe('generic');
- });
-});
diff --git a/src/features/AgentShareVisitor/resolveShareAccessState.ts b/src/features/AgentShareVisitor/resolveShareAccessState.ts
deleted file mode 100644
index f66d6316173..00000000000
--- a/src/features/AgentShareVisitor/resolveShareAccessState.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { isTrpcErrorCode } from '@/utils/trpcError';
-
-/**
- * How a failed `share.getSharedAgent` should be presented to the visitor.
- *
- * - `signIn` — the procedure is authed; an anonymous visitor gets
- * `UNAUTHORIZED` and needs a sign-in CTA rather than an error page. The
- * service opts out of the global 401 redirect precisely so this branch can
- * render (see `agentShareService.getSharedAgent`).
- * - `notFound` — no share resolves for this slug/id, or the creator turned
- * sharing off (`assertShareAccess` answers `NOT_FOUND` for a stranger on a
- * private share so a link cannot be used to probe for its existence).
- * - `forbidden` — the share exists but this account may not open it.
- * - `generic` — anything else (network / server fault): retryable.
- */
-export type ShareAccessState = 'forbidden' | 'generic' | 'notFound' | 'signIn';
-
-export const resolveShareAccessState = (error: unknown): ShareAccessState => {
- if (isTrpcErrorCode(error, 'UNAUTHORIZED')) return 'signIn';
- if (isTrpcErrorCode(error, 'NOT_FOUND')) return 'notFound';
- if (isTrpcErrorCode(error, 'FORBIDDEN')) return 'forbidden';
- return 'generic';
-};
-
-/** Visitor-facing copy key for a non-retryable access state. */
-export const SHARE_ACCESS_ERROR_KEYS: Record<
- Exclude<ShareAccessState, 'generic' | 'signIn'>,
- string
-> = {
- forbidden: 'share.visitor.access.forbidden',
- notFound: 'share.visitor.access.notFound',
-};
diff --git a/src/features/AgentShareVisitor/resolveVisitorErrorKey.test.ts b/src/features/AgentShareVisitor/resolveVisitorErrorKey.test.ts
deleted file mode 100644
index e76c0e33100..00000000000
--- a/src/features/AgentShareVisitor/resolveVisitorErrorKey.test.ts
+++ /dev/null
@@ -1,123 +0,0 @@
-import { ChatErrorType } from '@lobechat/types';
-import { TRPCClientError } from '@trpc/client';
-import { describe, expect, it } from 'vitest';
-import { z } from 'zod';
-
-import { isTerminalVisitorError, resolveVisitorErrorKey } from './resolveVisitorErrorKey';
-
-describe('resolveVisitorErrorKey', () => {
- /**
- * The lambda router installs no `zodError` formatter, so tRPC surfaces the
- * ZodError's own `message` — `JSON.stringify(issues, null, 2)`. Build the
- * fixtures from a real schema rejection so the mapping is tested against the
- * shape production actually produces, not a hand-written string.
- */
- const badRequest = (message: string) =>
- new TRPCClientError(message, {
- result: { error: { code: -32_600, data: { code: 'BAD_REQUEST' }, message: 'Bad Request' } },
- });
-
- const zodMessage = (schema: z.ZodTypeAny, value: unknown) => {
- const parsed = z.object({ payload: schema }).safeParse({ payload: value });
- if (parsed.success) throw new Error('fixture should have failed validation');
- return parsed.error.message;
- };
-
- it('maps a BAD_REQUEST TRPCClientError (over-long prompt) to actionable copy', () => {
- const message = zodMessage(z.string().max(3), 'way too long').replace('payload', 'prompt');
-
- expect(resolveVisitorErrorKey(badRequest(message))).toBe('share.visitor.errors.promptTooLong');
- });
-
- it('does not blame prompt length for an unrelated BAD_REQUEST on another field', () => {
- // A malformed `clientIds.topicId` also fails the schema — telling the
- // visitor to shorten their message would be actively misleading.
- const message = zodMessage(z.string().regex(/^topic_/), 'nope').replace('payload', 'topicId');
-
- expect(resolveVisitorErrorKey(badRequest(message))).toBe('share.visitor.errors.generic');
- });
-
- const trpcError = (code: string, message = code) =>
- new TRPCClientError(message, {
- result: { error: { code: -32_600, data: { code }, message } },
- });
-
- it('maps a FORBIDDEN send to the paused-share copy instead of a retryable failure', () => {
- // The creator flipped visibility away from `link` mid-session:
- // `resolveLinkShareOrThrow` rejects every further send, so retrying is futile.
- expect(resolveVisitorErrorKey(trpcError('FORBIDDEN', 'This share is private'))).toBe(
- 'share.visitor.errors.sharingPaused',
- );
- });
-
- it('maps a topic-level NOT_FOUND send to the recoverable unavailable copy', () => {
- expect(resolveVisitorErrorKey(trpcError('NOT_FOUND', 'Topic not found'))).toBe(
- 'share.visitor.errors.unavailable',
- );
- });
-
- it('maps a share-level NOT_FOUND send to the paused-share copy', () => {
- // A paused share answers NOT_FOUND to a stranger (no existence probing),
- // which for a visitor mid-session means the same as "sharing paused".
- expect(resolveVisitorErrorKey(trpcError('NOT_FOUND', 'Share not found'))).toBe(
- 'share.visitor.errors.sharingPaused',
- );
- });
-
- it('treats share-level failures as terminal and per-attempt ones as retryable', () => {
- expect(isTerminalVisitorError('share.visitor.errors.sharingPaused')).toBe(true);
- // NOT_FOUND may describe only the current topic (deleted topic), which a
- // topic switch / new conversation recovers from — locking the composer on
- // it would strand the visitor with no way out but a reload.
- expect(isTerminalVisitorError('share.visitor.errors.unavailable')).toBe(false);
- // The turn limit is scoped to one topic — a new conversation clears it.
- expect(isTerminalVisitorError('share.visitor.errors.turnLimit')).toBe(false);
- expect(isTerminalVisitorError('share.visitor.errors.generic')).toBe(false);
- });
-
- it('maps ShareTurnLimitExceeded', () => {
- expect(resolveVisitorErrorKey(new Error(ChatErrorType.ShareTurnLimitExceeded))).toBe(
- 'share.visitor.errors.turnLimit',
- );
- });
-
- it('maps ShareTopicLimitExceeded', () => {
- expect(resolveVisitorErrorKey(new Error(ChatErrorType.ShareTopicLimitExceeded))).toBe(
- 'share.visitor.errors.topicLimit',
- );
- });
-
- it('maps ShareSpendLimitExceeded to non-terminal "monthly limit reached" copy', () => {
- expect(resolveVisitorErrorKey(new Error(ChatErrorType.ShareSpendLimitExceeded))).toBe(
- 'share.visitor.errors.spendLimit',
- );
- // The cap resets next month and the owner can raise it — keep the composer usable.
- expect(isTerminalVisitorError('share.visitor.errors.spendLimit')).toBe(false);
- });
-
- it('maps InsufficientBudgetForModel', () => {
- expect(resolveVisitorErrorKey(new Error(ChatErrorType.InsufficientBudgetForModel))).toBe(
- 'share.visitor.errors.insufficientBudget',
- );
- });
-
- it('maps AgentShareProviderNotSupported', () => {
- expect(resolveVisitorErrorKey(new Error(ChatErrorType.AgentShareProviderNotSupported))).toBe(
- 'share.visitor.errors.providerNotSupported',
- );
- });
-
- it('maps ShareHeterogeneousAgentUnsupported', () => {
- expect(
- resolveVisitorErrorKey(new Error(ChatErrorType.ShareHeterogeneousAgentUnsupported)),
- ).toBe('share.visitor.errors.heterogeneousUnsupported');
- });
-
- it('falls back to the generic copy for an unrecognized error', () => {
- expect(resolveVisitorErrorKey(new Error('boom'))).toBe('share.visitor.errors.generic');
- });
-
- it('falls back to the generic copy for a non-Error thrown value', () => {
- expect(resolveVisitorErrorKey('boom')).toBe('share.visitor.errors.generic');
- });
-});
diff --git a/src/features/AgentShareVisitor/resolveVisitorErrorKey.ts b/src/features/AgentShareVisitor/resolveVisitorErrorKey.ts
deleted file mode 100644
index 7793e9df4b1..00000000000
--- a/src/features/AgentShareVisitor/resolveVisitorErrorKey.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-import { ChatErrorType } from '@lobechat/types';
-import { TRPCClientError } from '@trpc/client';
-
-/**
- * Map a share-run failure to the visitor-facing copy key.
- *
- * Extracted so the mapping (including the tRPC `BAD_REQUEST` branch) is
- * unit-testable without rendering `VisitorComposer` — see
- * `resolveVisitorErrorKey.test.ts`.
- */
-export const resolveVisitorErrorKey = (error: unknown): string => {
- const message = error instanceof Error ? error.message : String(error);
-
- // The server rejects an over-long `prompt` with a Zod-driven `BAD_REQUEST`
- // (see `SHARE_VISITOR_PROMPT_MAX_LENGTH` in `@lobechat/const`), not one of
- // the `ChatErrorType` values matched below — those are only embedded in
- // errors raised from inside the agent run itself. The client-side
- // `maxLength` mirror on the composer's `TextArea` should catch this before
- // the request goes out, but a direct RPC caller (or any future desync
- // between the two bounds) still needs actionable copy.
- //
- // Narrowed to the `prompt`/`too_big` issue rather than any `BAD_REQUEST`:
- // this procedure's schema can also reject a malformed `clientIds`/`topicId`,
- // and telling a visitor to shorten their message when the real fault is a
- // malformed id would be actively misleading. The lambda router installs no
- // `zodError` formatter, so the issue list only survives as tRPC's default
- // JSON-stringified `message`; anything that does not clearly match falls
- // through to the generic copy.
- if (
- error instanceof TRPCClientError &&
- error.data?.code === 'BAD_REQUEST' &&
- message.includes('too_big') &&
- message.includes('prompt')
- )
- return 'share.visitor.errors.promptTooLong';
-
- // The share itself stopped accepting traffic mid-session: the creator
- // paused it (a stranger on a private share gets NOT_FOUND 'Share not found'
- // from `assertShareAccess`, deliberately indistinguishable from a deleted
- // one), flipped it off `link` while previewing as owner
- // (`resolveLinkShareOrThrow` → FORBIDDEN), or deleted the topic
- // (NOT_FOUND 'Topic not found'). `useSharedAgent` never revalidates, so the
- // page keeps rendering the stale "everything is fine" shell — without this
- // branch the visitor only sees the generic copy and retries forever.
- if (error instanceof TRPCClientError) {
- if (error.data?.code === 'FORBIDDEN') return 'share.visitor.errors.sharingPaused';
- if (error.data?.code === 'NOT_FOUND') {
- // Share-level vs topic-level NOT_FOUND can only be told apart by the
- // server message (`shareChat.ts` / `AgentShareModel`): the share one is
- // terminal, the topic one must stay recoverable by switching / starting
- // a new topic (see `TERMINAL_VISITOR_ERROR_KEYS`).
- if (message === 'Share not found') return 'share.visitor.errors.sharingPaused';
- return 'share.visitor.errors.unavailable';
- }
- }
-
- if (message.includes(ChatErrorType.ShareTurnLimitExceeded))
- return 'share.visitor.errors.turnLimit';
- if (message.includes(ChatErrorType.ShareTopicLimitExceeded))
- return 'share.visitor.errors.topicLimit';
- // Deliberately NOT terminal: the cap is per calendar month and the owner can
- // raise it at any time, so the composer stays usable for a retry.
- if (message.includes(ChatErrorType.ShareSpendLimitExceeded))
- return 'share.visitor.errors.spendLimit';
- if (message.includes(ChatErrorType.InsufficientBudgetForModel))
- return 'share.visitor.errors.insufficientBudget';
- if (message.includes(ChatErrorType.AgentShareProviderNotSupported))
- return 'share.visitor.errors.providerNotSupported';
- if (message.includes(ChatErrorType.ShareHeterogeneousAgentUnsupported))
- return 'share.visitor.errors.heterogeneousUnsupported';
-
- return 'share.visitor.errors.generic';
-};
-
-/**
- * Failures that describe the share itself rather than one attempt, so retrying
- * (or switching topic) cannot clear them — the composer stays disabled and the
- * message survives a topic switch.
- */
-const TERMINAL_VISITOR_ERROR_KEYS = new Set([
- // `unavailable` (NOT_FOUND) is intentionally absent: it may describe only the
- // current topic, so locking the composer for it would strand the visitor —
- // worst case a truly deleted share just fails again on the next send.
- 'share.visitor.errors.sharingPaused',
-]);
-
-export const isTerminalVisitorError = (errorKey: string): boolean =>
- TERMINAL_VISITOR_ERROR_KEYS.has(errorKey);
diff --git a/src/features/AgentShareVisitor/resolveVisitorRunningOperation.test.ts b/src/features/AgentShareVisitor/resolveVisitorRunningOperation.test.ts
deleted file mode 100644
index c4f3fedcb90..00000000000
--- a/src/features/AgentShareVisitor/resolveVisitorRunningOperation.test.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import { resolveVisitorRunningOperation } from './resolveVisitorRunningOperation';
-
-describe('resolveVisitorRunningOperation', () => {
- it('returns undefined when there is no active topic', () => {
- expect(
- resolveVisitorRunningOperation(
- [{ id: 't-1', runningOperation: { assistantMessageId: 'a', operationId: 'op' } }],
- undefined,
- ),
- ).toBeUndefined();
- });
-
- it('returns undefined when the topic list has not loaded yet', () => {
- expect(resolveVisitorRunningOperation(undefined, 't-1')).toBeUndefined();
- });
-
- it('returns undefined when the active topic has no running operation', () => {
- expect(
- resolveVisitorRunningOperation([{ id: 't-1', runningOperation: null }], 't-1'),
- ).toBeUndefined();
- });
-
- it('returns undefined when the active topic is not in the list', () => {
- expect(
- resolveVisitorRunningOperation(
- [{ id: 't-other', runningOperation: { assistantMessageId: 'a', operationId: 'op' } }],
- 't-1',
- ),
- ).toBeUndefined();
- });
-
- it('returns the matching topic runningOperation', () => {
- const runningOperation = {
- assistantMessageId: 'ast-1',
- heteroType: 'claude-code',
- operationId: 'op-1',
- scope: 'main',
- threadId: 'thd-1',
- };
-
- expect(
- resolveVisitorRunningOperation(
- [
- { id: 't-other', runningOperation: null },
- { id: 't-1', runningOperation },
- ],
- 't-1',
- ),
- ).toEqual(runningOperation);
- });
-});
diff --git a/src/features/AgentShareVisitor/resolveVisitorRunningOperation.ts b/src/features/AgentShareVisitor/resolveVisitorRunningOperation.ts
deleted file mode 100644
index 3a3d6a99901..00000000000
--- a/src/features/AgentShareVisitor/resolveVisitorRunningOperation.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-/** Sanitized `runningOperation` marker the visitor topic list carries — mirrors `VisitorRunningOperation` in `packages/database/src/models/topic.ts` (server projection) and the shape `useGatewayReconnect`'s `RunningOperation` needs. */
-export interface VisitorTopicRunningOperation {
- assistantMessageId: string;
- heteroType?: string | null;
- operationId: string;
- scope?: string;
- threadId?: string | null;
-}
-
-interface VisitorTopicWithRunningOperation {
- id: string;
- runningOperation?: VisitorTopicRunningOperation | null;
-}
-
-/**
- * Finds the active topic in the visitor's topic list (from `useVisitorTopics`)
- * and returns its sanitized `runningOperation` marker, if any — what
- * `useGatewayReconnect` needs to resume a Gateway stream after a page reload.
- *
- * A pure lookup, kept separate from `VisitorConversation` so it can be
- * unit-tested without mounting the SWR-backed hook — same split as
- * `topicPanelViewState.ts`.
- */
-export const resolveVisitorRunningOperation = (
- topics: VisitorTopicWithRunningOperation[] | undefined,
- topicId: string | null | undefined,
-): VisitorTopicRunningOperation | undefined => {
- if (!topicId) return undefined;
-
- return topics?.find((topic) => topic.id === topicId)?.runningOperation ?? undefined;
-};
diff --git a/src/features/AgentShareVisitor/routeMeta.ts b/src/features/AgentShareVisitor/routeMeta.ts
deleted file mode 100644
index 826a1f68d24..00000000000
--- a/src/features/AgentShareVisitor/routeMeta.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { MessageSquareShareIcon } from 'lucide-react';
-import { lazy } from 'react';
-
-import AgentShareVisitorSkeleton from '@/components/Skeleton/AgentShareVisitor';
-import { routeMeta } from '@/spa/router/routeMeta';
-
-/**
- * Keep visitor data fetching out of the initial router chunk. The static share
- * label remains the fallback until the visitor-facing metadata is available.
- */
-export const agentShareVisitorRouteMeta = routeMeta({
- DynamicMeta: lazy(() => import('./useAgentShareVisitorRouteMeta')),
- icon: MessageSquareShareIcon,
- Skeleton: AgentShareVisitorSkeleton,
- titleKey: 'navigation.sharedAgent',
-});
diff --git a/src/features/AgentShareVisitor/sendVisitorMessage.test.ts b/src/features/AgentShareVisitor/sendVisitorMessage.test.ts
deleted file mode 100644
index b13c17b46e1..00000000000
--- a/src/features/AgentShareVisitor/sendVisitorMessage.test.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-import { LOADING_FLAT } from '@lobechat/const';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-const store = vi.hoisted(() => ({
- associateMessageWithOperation: vi.fn(),
- executeGatewayAgent: vi.fn(),
- failOperation: vi.fn(),
- internal_dispatchMessage: vi.fn(),
- operations: {} as Record<string, { status: string }>,
- optimisticCreateTmpMessage: vi.fn(),
- startOperation: vi.fn(() => ({ abortController: new AbortController(), operationId: 'op-1' })),
-}));
-
-vi.mock('@/store/chat', () => ({
- useChatStore: { getState: () => store },
-}));
-
-const { sendVisitorMessage } = await import('./sendVisitorMessage');
-
-const params = { agentId: 'agent-1', message: 'hello', shareId: 'share-1', topicId: 'topic-1' };
-
-describe('sendVisitorMessage', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- store.operations = {};
- store.executeGatewayAgent.mockResolvedValue({
- assistantMessageId: 'a',
- operationId: 'srv-op',
- topicId: 'topic-1',
- userMessageId: 'u',
- });
- });
-
- // Regression: the composer used to call `executeGatewayAgent` bare, so the
- // list stayed empty until the first gateway event and nothing carried the
- // generating state.
- it('echoes the user bubble and an assistant placeholder before the gateway call, under a sendMessage op', async () => {
- await sendVisitorMessage(params);
-
- expect(store.startOperation).toHaveBeenCalledWith(
- expect.objectContaining({ type: 'sendMessage' }),
- );
- const [userCall, assistantCall] = store.optimisticCreateTmpMessage.mock.calls;
- expect(userCall[0]).toMatchObject({ content: 'hello', role: 'user', topicId: 'topic-1' });
- expect(assistantCall[0]).toMatchObject({ content: LOADING_FLAT, role: 'assistant' });
- const userMessageId = userCall[1].tempMessageId;
- const assistantMessageId = assistantCall[1].tempMessageId;
- expect(store.associateMessageWithOperation).toHaveBeenCalledWith(userMessageId, 'op-1');
- expect(store.associateMessageWithOperation).toHaveBeenCalledWith(assistantMessageId, 'op-1');
-
- // Same ids handed to the server so the optimistic rows never re-key.
- expect(store.executeGatewayAgent).toHaveBeenCalledWith(
- expect.objectContaining({
- clientIds: { assistantMessageId, userMessageId },
- context: { agentId: 'agent-1', agentShareId: 'share-1', scope: 'main', topicId: 'topic-1' },
- parentOperationId: 'op-1',
- tempMessageIds: [assistantMessageId],
- }),
- );
- // Existing topic: the server rows land in the same bucket, nothing to drop.
- expect(store.internal_dispatchMessage).not.toHaveBeenCalled();
- });
-
- it('drops the pre-topic optimistic rows after a new topic was created', async () => {
- await sendVisitorMessage({ ...params, topicId: undefined });
-
- expect(store.executeGatewayAgent).toHaveBeenCalledWith(
- expect.objectContaining({ context: expect.objectContaining({ topicId: undefined }) }),
- );
- expect(store.internal_dispatchMessage).toHaveBeenCalledWith(
- expect.objectContaining({ type: 'deleteMessages' }),
- { operationId: 'op-1' },
- );
- });
-
- it('fails the op, removes the optimistic rows and rethrows when the gateway rejects', async () => {
- const error = new Error('limit');
- store.executeGatewayAgent.mockRejectedValueOnce(error);
-
- await expect(sendVisitorMessage(params)).rejects.toBe(error);
-
- expect(store.failOperation).toHaveBeenCalledWith('op-1', {
- message: 'limit',
- type: 'GatewayError',
- });
- expect(store.internal_dispatchMessage).toHaveBeenCalledWith(
- expect.objectContaining({ type: 'deleteMessages' }),
- { operationId: 'op-1' },
- );
- });
-
- it('keeps a cancelled op cancelled instead of marking it failed', async () => {
- store.operations = { 'op-1': { status: 'cancelled' } };
- store.executeGatewayAgent.mockRejectedValueOnce(new Error('aborted'));
-
- await expect(sendVisitorMessage(params)).rejects.toThrow('aborted');
-
- expect(store.failOperation).not.toHaveBeenCalled();
- expect(store.internal_dispatchMessage).toHaveBeenCalled();
- });
-});
diff --git a/src/features/AgentShareVisitor/sendVisitorMessage.ts b/src/features/AgentShareVisitor/sendVisitorMessage.ts
deleted file mode 100644
index 26ce54498b9..00000000000
--- a/src/features/AgentShareVisitor/sendVisitorMessage.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-import { LOADING_FLAT } from '@lobechat/const';
-import { generateEntityId } from '@lobechat/utils';
-
-import { useChatStore } from '@/store/chat';
-
-export interface SendVisitorMessageParams {
- agentId: string;
- message: string;
- shareId: string;
- /** Absent → the run creates a new visitor topic. */
- topicId?: string | null;
-}
-
-/**
- * Share-visitor send: the optimistic echo of the owner `sendMessage` path
- * (`conversationLifecycle.ts`), without its owner-only preamble.
- *
- * `sendMessage` itself cannot be reused here — it reads the full owner agent
- * config and runs `ensureAgentManagementAccess`, which a visitor fails. But
- * calling `executeGatewayAgent` bare (the previous behaviour) left the list
- * empty until the first gateway event: no user bubble, no assistant
- * placeholder, and nothing for the loading UI to attach to. This mirrors the
- * pieces that matter for the visitor:
- *
- * 1. Mint the final row ids up front — the share `execAgent` route honours
- * `clientIds` verbatim, so the optimistic rows never need re-keying.
- * 2. Insert the user bubble and a `LOADING_FLAT` assistant placeholder
- * immediately, under a `sendMessage` operation so `ContentLoading` shows
- * the generating state during the phase-1 round-trip.
- * 3. Hand the operation to `executeGatewayAgent` as `parentOperationId`, which
- * completes it once the child `execServerAgentRuntime` op is running.
- */
-export const sendVisitorMessage = async ({
- agentId,
- message,
- shareId,
- topicId,
-}: SendVisitorMessageParams) => {
- const store = useChatStore.getState();
- const messageContext = {
- agentId,
- agentShareId: shareId,
- scope: 'main' as const,
- topicId: topicId ?? undefined,
- };
- const userMessageId = generateEntityId('messages');
- const assistantMessageId = generateEntityId('messages');
-
- const { operationId } = store.startOperation({
- context: { ...messageContext, messageId: userMessageId },
- label: 'Send Message',
- type: 'sendMessage',
- });
-
- store.optimisticCreateTmpMessage(
- { agentId, content: message, role: 'user', topicId: messageContext.topicId },
- { operationId, tempMessageId: userMessageId },
- );
- store.optimisticCreateTmpMessage(
- { agentId, content: LOADING_FLAT, role: 'assistant', topicId: messageContext.topicId },
- { operationId, tempMessageId: assistantMessageId },
- );
- store.associateMessageWithOperation(userMessageId, operationId);
- store.associateMessageWithOperation(assistantMessageId, operationId);
-
- const removeOptimisticRows = () => {
- store.internal_dispatchMessage(
- { ids: [userMessageId, assistantMessageId], type: 'deleteMessages' },
- { operationId },
- );
- };
-
- try {
- const result = await store.executeGatewayAgent({
- clientIds: { assistantMessageId, userMessageId },
- context: messageContext,
- message,
- messageContext,
- parentOperationId: operationId,
- tempMessageIds: [assistantMessageId],
- });
- // A new topic is fetched and switched to by the gateway under its real id;
- // the optimistic rows were written to the pre-topic bucket and would
- // otherwise linger there for the next "new conversation" surface.
- if (!topicId) removeOptimisticRows();
- return result;
- } catch (error) {
- // A Stop during phase-1 already marked the op cancelled — keep that.
- if (useChatStore.getState().operations[operationId]?.status !== 'cancelled') {
- store.failOperation(operationId, {
- message: error instanceof Error ? error.message : 'Unknown error',
- type: 'GatewayError',
- });
- }
- removeOptimisticRows();
- throw error;
- }
-};
diff --git a/src/features/AgentShareVisitor/shareInteractivity.ts b/src/features/AgentShareVisitor/shareInteractivity.ts
deleted file mode 100644
index 8fedb1de6a3..00000000000
--- a/src/features/AgentShareVisitor/shareInteractivity.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import type { SharedAgentData } from '@lobechat/types';
-
-/**
- * Whether the share still accepts visitor traffic.
- *
- * Every visitor-facing `shareChat` procedure runs through
- * `resolveLinkShareOrThrow`, which rejects anything but `link` visibility with
- * `FORBIDDEN`. An owner previewing their own private share therefore reaches
- * this page (via `assertShareAccess`) but must not fire those calls — chatting
- * and the topic list alike would only render a useless error.
- */
-export const isShareInteractive = (visibility: SharedAgentData['visibility']): boolean =>
- visibility === 'link';
diff --git a/src/features/AgentShareVisitor/topicPanelViewState.test.ts b/src/features/AgentShareVisitor/topicPanelViewState.test.ts
deleted file mode 100644
index e0419d1cd0c..00000000000
--- a/src/features/AgentShareVisitor/topicPanelViewState.test.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import { getTopicPanelViewState } from './topicPanelViewState';
-
-describe('getTopicPanelViewState', () => {
- it('reports error first, even while a revalidation is in flight', () => {
- expect(getTopicPanelViewState(undefined, new Error('boom'), true)).toBe('error');
- expect(getTopicPanelViewState([{}], new Error('boom'), false)).toBe('error');
- });
-
- it('reports loading before falling back to empty', () => {
- expect(getTopicPanelViewState(undefined, undefined, true)).toBe('loading');
- });
-
- it('only reports empty for a settled, genuinely empty list', () => {
- expect(getTopicPanelViewState([], undefined, false)).toBe('empty');
- expect(getTopicPanelViewState(undefined, undefined, false)).toBe('empty');
- });
-
- it('reports list when topics exist', () => {
- expect(getTopicPanelViewState([{}], undefined, false)).toBe('list');
- });
-});
diff --git a/src/features/AgentShareVisitor/topicPanelViewState.ts b/src/features/AgentShareVisitor/topicPanelViewState.ts
deleted file mode 100644
index 76784fb0c3f..00000000000
--- a/src/features/AgentShareVisitor/topicPanelViewState.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-/**
- * The visitor topic list has four mutually-exclusive states, and an SWR fetch
- * only tells the caller two independent booleans (`isLoading`, `error`) plus
- * possibly-stale `data`. Centralizing the branch here keeps `error` and
- * `isLoading` checked *before* falling back to "no topics" — otherwise a
- * pending or failed fetch (where `data` is still `undefined`) renders the same
- * empty state as a genuinely empty list, silently misinforming the visitor.
- */
-export type TopicPanelViewState = 'empty' | 'error' | 'list' | 'loading';
-
-export const getTopicPanelViewState = (
- topics: unknown[] | undefined,
- error: unknown,
- isLoading: boolean,
-): TopicPanelViewState => {
- if (error) return 'error';
- if (isLoading) return 'loading';
- if (!topics?.length) return 'empty';
- return 'list';
-};
diff --git a/src/features/AgentShareVisitor/topicRowActivation.test.ts b/src/features/AgentShareVisitor/topicRowActivation.test.ts
deleted file mode 100644
index b2278558fd7..00000000000
--- a/src/features/AgentShareVisitor/topicRowActivation.test.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import { isTopicRowActivationKey } from './topicRowActivation';
-
-describe('isTopicRowActivationKey', () => {
- it('activates on Enter', () => {
- expect(isTopicRowActivationKey('Enter')).toBe(true);
- });
-
- it('activates on Space', () => {
- expect(isTopicRowActivationKey(' ')).toBe(true);
- });
-
- it('ignores other keys', () => {
- expect(isTopicRowActivationKey('Tab')).toBe(false);
- expect(isTopicRowActivationKey('ArrowDown')).toBe(false);
- expect(isTopicRowActivationKey('a')).toBe(false);
- });
-});
diff --git a/src/features/AgentShareVisitor/topicRowActivation.ts b/src/features/AgentShareVisitor/topicRowActivation.ts
deleted file mode 100644
index 5b93db199bb..00000000000
--- a/src/features/AgentShareVisitor/topicRowActivation.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-/**
- * Whether a `KeyboardEvent.key` should activate a visitor topic row.
- *
- * Extracted so the div-as-button keyboard semantics (mirroring a native
- * `<button>`: only Enter/Space activate) are unit-testable without rendering
- * `TopicPanel` — see `topicRowActivation.test.ts`.
- */
-export const isTopicRowActivationKey = (key: string): boolean => key === 'Enter' || key === ' ';
diff --git a/src/features/AgentShareVisitor/useAgentShareVisitorRouteMeta.test.ts b/src/features/AgentShareVisitor/useAgentShareVisitorRouteMeta.test.ts
deleted file mode 100644
index 61904d58c8d..00000000000
--- a/src/features/AgentShareVisitor/useAgentShareVisitorRouteMeta.test.ts
+++ /dev/null
@@ -1,139 +0,0 @@
-import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
-import { createElement, type PropsWithChildren } from 'react';
-import { SWRConfig } from 'swr';
-import { afterEach, describe, expect, it, vi } from 'vitest';
-
-import type { DynamicRouteMeta } from '@/spa/router/routeMeta';
-
-import { useAgentShareVisitorRouteMeta } from './useAgentShareVisitorRouteMeta';
-import { useSharedAgent } from './useSharedAgent';
-
-const { getSharedAgent } = vi.hoisted(() => ({ getSharedAgent: vi.fn() }));
-
-vi.mock('@/services/agentShare', () => ({ agentShareService: { getSharedAgent } }));
-
-const createWrapper = () => {
- const cache = new Map();
-
- return ({ children }: PropsWithChildren) =>
- createElement(
- SWRConfig,
- { value: { dedupingInterval: 0, provider: () => cache, shouldRetryOnError: false } },
- children,
- );
-};
-
-describe('useAgentShareVisitorRouteMeta', () => {
- afterEach(() => {
- cleanup();
- vi.resetAllMocks();
- });
-
- it('resolves the agent name from the same request as the visitor page', async () => {
- let resolveAgent!: (data: { agentMeta: { name: string; title: string } }) => void;
- getSharedAgent.mockReturnValue(
- new Promise((resolve) => {
- resolveAgent = resolve;
- }),
- );
- const onResolve = vi.fn<(meta: DynamicRouteMeta) => void>();
-
- renderHook(
- () => {
- useSharedAgent('alice');
- useAgentShareVisitorRouteMeta({ onResolve, params: { slugOrId: 'alice' } });
- },
- { wrapper: createWrapper() },
- );
-
- expect(onResolve.mock.lastCall?.[0].title).toBeUndefined();
-
- await act(async () => {
- resolveAgent({ agentMeta: { name: 'Alice', title: 'Writing Assistant' } });
- });
-
- await waitFor(() => expect(onResolve.mock.lastCall?.[0].title).toBe('Alice'));
- expect(getSharedAgent).toHaveBeenCalledTimes(1);
- });
-
- it('reads cached metadata without counting another view when the title mounts later', async () => {
- getSharedAgent.mockResolvedValue({ agentMeta: { name: 'Alice' } });
- const wrapper = createWrapper();
- const page = renderHook(() => useSharedAgent('alice'), { wrapper });
-
- await waitFor(() => expect(page.result.current.data).toBeDefined());
- page.unmount();
-
- const onResolve = vi.fn<(meta: DynamicRouteMeta) => void>();
- renderHook(() => useAgentShareVisitorRouteMeta({ onResolve, params: { slugOrId: 'alice' } }), {
- wrapper,
- });
-
- await waitFor(() => expect(onResolve.mock.lastCall?.[0].title).toBe('Alice'));
- expect(getSharedAgent).toHaveBeenCalledTimes(1);
- });
-
- it.each([
- [{ name: '', title: 'Writing Assistant' }, 'Writing Assistant'],
- [{ name: ' ', title: ' ' }, undefined],
- [{}, undefined],
- ])('resolves display name or allows the static fallback for %j', async (agentMeta, title) => {
- getSharedAgent.mockResolvedValue({ agentMeta });
- const onResolve = vi.fn<(meta: DynamicRouteMeta) => void>();
-
- const { result } = renderHook(
- () => {
- const shared = useSharedAgent('alice');
- useAgentShareVisitorRouteMeta({ onResolve, params: { slugOrId: 'alice' } });
- return shared;
- },
- { wrapper: createWrapper() },
- );
-
- await waitFor(() => expect(result.current.data).toBeDefined());
- expect(onResolve.mock.lastCall?.[0].title).toBe(title);
- });
-
- it('clears the previous agent name when navigating to an unavailable share', async () => {
- getSharedAgent.mockResolvedValueOnce({ agentMeta: { name: 'Alice' } });
- getSharedAgent.mockRejectedValueOnce(new Error('Share unavailable'));
- const onResolve = vi.fn<(meta: DynamicRouteMeta) => void>();
-
- const { rerender, result } = renderHook(
- ({ slugOrId }) => {
- const shared = useSharedAgent(slugOrId);
- useAgentShareVisitorRouteMeta({ onResolve, params: { slugOrId } });
- return shared;
- },
- { initialProps: { slugOrId: 'alice' }, wrapper: createWrapper() },
- );
-
- await waitFor(() => expect(onResolve.mock.lastCall?.[0].title).toBe('Alice'));
- rerender({ slugOrId: 'unavailable' });
- await waitFor(() => expect(result.current.error).toBeDefined());
- expect(onResolve.mock.lastCall?.[0].title).toBeUndefined();
- });
-
- it('falls back after a failed refresh even when SWR retains cached metadata', async () => {
- getSharedAgent.mockResolvedValue({ agentMeta: { name: 'Alice' } });
- const onResolve = vi.fn<(meta: DynamicRouteMeta) => void>();
-
- const { result } = renderHook(
- () => {
- const shared = useSharedAgent('alice');
- useAgentShareVisitorRouteMeta({ onResolve, params: { slugOrId: 'alice' } });
- return shared;
- },
- { wrapper: createWrapper() },
- );
-
- await waitFor(() => expect(onResolve.mock.lastCall?.[0].title).toBe('Alice'));
- getSharedAgent.mockRejectedValue(new Error('Share unavailable'));
- await act(async () => {
- await result.current.mutate();
- });
-
- expect(result.current.data?.agentMeta.name).toBe('Alice');
- await waitFor(() => expect(onResolve.mock.lastCall?.[0].title).toBeUndefined());
- });
-});
diff --git a/src/features/AgentShareVisitor/useAgentShareVisitorRouteMeta.ts b/src/features/AgentShareVisitor/useAgentShareVisitorRouteMeta.ts
deleted file mode 100644
index 1aaf260d34e..00000000000
--- a/src/features/AgentShareVisitor/useAgentShareVisitorRouteMeta.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { agentDisplayName } from '@lobechat/types';
-import useSWR from 'swr';
-
-import { usePublishDynamicRouteMeta } from '@/features/RouteMeta/usePublishDynamicRouteMeta';
-import { shareKeys } from '@/libs/swr/keys';
-import type { DynamicRouteMetaProps } from '@/spa/router/routeMeta';
-
-import type { useSharedAgent } from './useSharedAgent';
-
-export const useAgentShareVisitorRouteMeta = ({ onResolve, params }: DynamicRouteMetaProps) => {
- /** The page owns fetching because fetching a share also counts a page view. */
- const { data, error } = useSWR<ReturnType<typeof useSharedAgent>['data']>(
- params.slugOrId ? shareKeys.agentInfo(params.slugOrId) : null,
- null,
- { revalidateOnMount: false },
- );
-
- usePublishDynamicRouteMeta(
- { title: error ? undefined : agentDisplayName(data?.agentMeta) },
- onResolve,
- );
-};
-
-const AgentShareVisitorDynamicMeta = (props: DynamicRouteMetaProps) => {
- useAgentShareVisitorRouteMeta(props);
-
- return null;
-};
-
-export default AgentShareVisitorDynamicMeta;
diff --git a/src/features/AgentShareVisitor/useShareRunStop.test.ts b/src/features/AgentShareVisitor/useShareRunStop.test.ts
deleted file mode 100644
index 9bffd640292..00000000000
--- a/src/features/AgentShareVisitor/useShareRunStop.test.ts
+++ /dev/null
@@ -1,151 +0,0 @@
-import { act, renderHook, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import type { Operation } from '@/store/chat/slices/operation/types';
-import { messageMapKey } from '@/store/chat/utils/messageMapKey';
-
-const mocks = vi.hoisted(() => ({
- interruptTask: vi.fn(),
-}));
-
-vi.mock('@/services/shareChat', () => ({
- shareChatService: { interruptTask: mocks.interruptTask },
-}));
-
-const updateOperationMetadata = vi.fn();
-let operations: Operation[] = [];
-
-const contextKey = messageMapKey({ agentId: 'agent-1', scope: 'main', topicId: 'topic-1' });
-
-// A tiny fake chat store, same shape used by `useVisitorConversationSeed.test.ts`:
-// only the bits `useShareRunStop` actually touches (`operationsByContext` /
-// `operations` for the real `getOperationsByContext` selector, plus
-// `updateOperationMetadata`).
-vi.mock('@/store/chat', () => ({
- useChatStore: {
- getState: () => ({
- operations: Object.fromEntries(operations.map((op) => [op.id, op])),
- operationsByContext: { [contextKey]: operations.map((op) => op.id) },
- updateOperationMetadata,
- }),
- },
-}));
-
-const { resolveRunningShareOperation, useShareRunStop } = await import('./useShareRunStop');
-
-const runningOp = (overrides: Partial<Operation> = {}): Operation =>
- ({
- abortController: new AbortController(),
- context: { agentId: 'agent-1', scope: 'main', topicId: 'topic-1' },
- id: 'local-op-1',
- metadata: { serverOperationId: 'server-op-1', startTime: Date.now() },
- status: 'running',
- type: 'execServerAgentRuntime',
- ...overrides,
- }) as Operation;
-
-describe('resolveRunningShareOperation', () => {
- it('returns undefined when nothing is running', () => {
- expect(resolveRunningShareOperation([])).toBeUndefined();
- });
-
- it('ignores operations that are not AI-runtime types', () => {
- const op = runningOp({ type: 'sendMessage' as Operation['type'] });
- expect(resolveRunningShareOperation([op])).toBeUndefined();
- });
-
- it('ignores operations missing a server-side operation id', () => {
- const op = runningOp({ metadata: { startTime: Date.now() } });
- expect(resolveRunningShareOperation([op])).toBeUndefined();
- });
-
- it('picks the running execServerAgentRuntime operation', () => {
- const op = runningOp();
- expect(resolveRunningShareOperation([op])).toEqual({
- localOperationId: 'local-op-1',
- serverOperationId: 'server-op-1',
- topicId: 'topic-1',
- });
- });
-});
-
-describe('useShareRunStop', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- operations = [];
- });
-
- it('is a no-op when nothing is running for the context', async () => {
- const { result } = renderHook(() => useShareRunStop('share-1', 'agent-1', 'topic-1'));
-
- await act(async () => {
- await result.current.stopSharedRun();
- });
-
- expect(mocks.interruptTask).not.toHaveBeenCalled();
- expect(updateOperationMetadata).not.toHaveBeenCalled();
- });
-
- it('flips isAborting immediately and calls shareChat.interruptTask for the running op', async () => {
- operations = [runningOp()];
- mocks.interruptTask.mockResolvedValueOnce({ success: true });
- const { result } = renderHook(() => useShareRunStop('share-1', 'agent-1', 'topic-1'));
-
- await act(async () => {
- await result.current.stopSharedRun();
- });
-
- expect(updateOperationMetadata).toHaveBeenCalledWith('local-op-1', { isAborting: true });
- expect(mocks.interruptTask).toHaveBeenCalledWith('share-1', 'topic-1', 'server-op-1');
- expect(result.current.stopping).toBe(false);
- expect(result.current.stopError).toBeUndefined();
- });
-
- it('surfaces an interrupt failure and restores the loading indicator instead of swallowing it', async () => {
- operations = [runningOp()];
- mocks.interruptTask.mockRejectedValueOnce(new Error('already finished'));
- const { result } = renderHook(() => useShareRunStop('share-1', 'agent-1', 'topic-1'));
-
- await act(async () => {
- await result.current.stopSharedRun();
- });
-
- await waitFor(() => {
- expect(result.current.stopError).toBeInstanceOf(Error);
- });
- // Restored to `false` — the interrupt didn't land, so the run is presumably
- // still going and the busy indicator should not stay stuck off.
- expect(updateOperationMetadata).toHaveBeenLastCalledWith('local-op-1', {
- isAborting: false,
- });
- expect(result.current.stopping).toBe(false);
- });
-
- it('ignores a concurrent stop while one is already in flight', async () => {
- operations = [runningOp()];
- let resolveFirst: ((value: { success: boolean }) => void) | undefined;
- mocks.interruptTask.mockImplementationOnce(
- () =>
- new Promise((resolve) => {
- resolveFirst = resolve;
- }),
- );
- const { result } = renderHook(() => useShareRunStop('share-1', 'agent-1', 'topic-1'));
-
- let firstCall!: Promise<void>;
- act(() => {
- firstCall = result.current.stopSharedRun();
- });
- expect(result.current.stopping).toBe(true);
-
- await act(async () => {
- await result.current.stopSharedRun();
- });
- expect(mocks.interruptTask).toHaveBeenCalledTimes(1);
-
- resolveFirst?.({ success: true });
- await act(async () => {
- await firstCall;
- });
- });
-});
diff --git a/src/features/AgentShareVisitor/useShareRunStop.ts b/src/features/AgentShareVisitor/useShareRunStop.ts
deleted file mode 100644
index c03339b747b..00000000000
--- a/src/features/AgentShareVisitor/useShareRunStop.ts
+++ /dev/null
@@ -1,123 +0,0 @@
-import { useCallback, useEffect, useState } from 'react';
-
-import { shareChatService } from '@/services/shareChat';
-import { useChatStore } from '@/store/chat';
-import { operationSelectors } from '@/store/chat/slices/operation/selectors';
-import { AI_RUNTIME_OPERATION_TYPES, type Operation } from '@/store/chat/slices/operation/types';
-
-export interface ShareRunStop {
- /** Set when the interrupt request itself failed — lets the caller offer a retry. */
- stopError: unknown;
- /** Whether an interrupt request is currently in flight. */
- stopping: boolean;
- /**
- * Ask the server to interrupt the share's currently running operation.
- * No-op if nothing is running for this (agentId, topicId) context.
- */
- stopSharedRun: () => Promise<void>;
-}
-
-/**
- * The bits `stopSharedRun` needs off the running operation: the server-side id
- * `shareChat.interruptTask` requires (distinct from the local operation id),
- * and the topic it belongs to (read off the operation itself rather than the
- * composer's `topicId` prop, which can still be stale for the first turn of a
- * brand-new topic — see `resolveRunningShareOperation`'s doc comment).
- */
-export interface RunningShareOperation {
- localOperationId: string;
- serverOperationId: string;
- topicId: string;
-}
-
-/**
- * Pick the running gateway operation for a share context, if any — pure so it
- * can be unit-tested without a full zustand store mock (see
- * `useShareRunStop.test.ts`, mirroring the `topicPanelViewState.ts` precedent).
- *
- * Reads `operation.context.topicId` rather than trusting a caller-supplied
- * topicId: for a fresh share topic the operation is created (and starts
- * streaming) with the server-minted topic id before `VisitorConversation`'s
- * `activeTopicId` state has necessarily re-rendered the composer, so the prop
- * can momentarily lag. The operation's own context never does.
- */
-export const resolveRunningShareOperation = (
- operations: Operation[],
-): RunningShareOperation | undefined => {
- const operation = operations.find(
- (op) => AI_RUNTIME_OPERATION_TYPES.includes(op.type) && op.status === 'running',
- );
- if (!operation?.metadata.serverOperationId || !operation.context.topicId) return undefined;
-
- return {
- localOperationId: operation.id,
- serverOperationId: operation.metadata.serverOperationId,
- topicId: operation.context.topicId,
- };
-};
-
-/**
- * Visitor-facing counterpart of the main composer's Stop button.
- *
- * Deliberately does NOT go through `cancelOperation`/`cancelOperations`: those
- * already forward gateway-mode share runs to `shareChatService.interruptTask`
- * via the `onOperationCancel` handler registered in `gateway.ts`, but that
- * call is fire-and-forget and swallows its own errors (see
- * `operation/actions.ts` `cancelOperation`), so a failed interrupt would never
- * reach the visitor. Worse, the server's `interruptTask` route rejects with
- * `NOT_FOUND` unless the given operationId still matches the topic's recorded
- * `runningOperation` (see `shareChat.ts`), so calling it a second time
- * ourselves on top of that handler risks a spurious failure once the first
- * call has already cleared it. Instead this owns the single interrupt call
- * end-to-end and reports its outcome.
- *
- * Flips `isAborting` on the local operation immediately on request (the same
- * flag `cancelOperation` sets) so the busy indicator clears right away like
- * the main composer's, without touching `onCancelHandler` — and reverts it if
- * the interrupt request itself fails, since the run is presumably still going.
- */
-export const useShareRunStop = (
- shareId: string,
- agentId: string,
- topicId?: string | null,
-): ShareRunStop => {
- const [stopping, setStopping] = useState(false);
- const [stopError, setStopError] = useState<unknown>();
-
- // The failure belongs to the run in the topic it happened in; carrying it into
- // another topic would offer a retry that resolves no running operation there.
- useEffect(() => {
- setStopError(undefined);
- }, [topicId]);
-
- const stopSharedRun = useCallback(async () => {
- if (stopping) return;
-
- const operations = operationSelectors.getOperationsByContext({
- agentId,
- scope: 'main',
- topicId: topicId ?? undefined,
- })(useChatStore.getState());
- const target = resolveRunningShareOperation(operations);
- if (!target) return;
-
- const { updateOperationMetadata } = useChatStore.getState();
- setStopping(true);
- setStopError(undefined);
- updateOperationMetadata(target.localOperationId, { isAborting: true });
-
- try {
- await shareChatService.interruptTask(shareId, target.topicId, target.serverOperationId);
- } catch (error) {
- console.error('[AgentShareVisitor] interruptTask failed:', error);
- // The interrupt didn't land — the run is presumably still going, so
- // restore the loading indicator and let the visitor retry.
- updateOperationMetadata(target.localOperationId, { isAborting: false });
- setStopError(error);
- } finally {
- setStopping(false);
- }
- }, [agentId, shareId, stopping, topicId]);
-
- return { stopError, stopping, stopSharedRun };
-};
diff --git a/src/features/AgentShareVisitor/useSharedAgent.ts b/src/features/AgentShareVisitor/useSharedAgent.ts
deleted file mode 100644
index f2ee4dd44b1..00000000000
--- a/src/features/AgentShareVisitor/useSharedAgent.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import useSWR from 'swr';
-
-import { shareKeys } from '@/libs/swr/keys';
-import { agentShareService } from '@/services/agentShare';
-
-/**
- * Fetch the visitor-facing metadata of an agent share, resolved from the URL
- * segment (a custom slug or the raw share id).
- *
- * `getSharedAgent` counts a page view server-side, so revalidation on focus /
- * reconnect is off: re-focusing the same mounted visit must not increment it
- * again.
- */
-export const useSharedAgent = (slugOrId?: string) =>
- useSWR(
- slugOrId ? shareKeys.agentInfo(slugOrId) : null,
- () => agentShareService.getSharedAgent(slugOrId!),
- { revalidateOnFocus: false, revalidateOnReconnect: false },
- );
diff --git a/src/features/AgentShareVisitor/useVisitorConversationSeed.test.ts b/src/features/AgentShareVisitor/useVisitorConversationSeed.test.ts
deleted file mode 100644
index dae12750bf8..00000000000
--- a/src/features/AgentShareVisitor/useVisitorConversationSeed.test.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import type { SharedAgentData } from '@lobechat/types';
-import { act, renderHook } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { useVisitorConversationSeed } from './useVisitorConversationSeed';
-
-const mocks = vi.hoisted(() => ({
- chatState: {} as Record<string, unknown>,
- seedAgent: vi.fn(),
-}));
-
-vi.mock('@/store/agent', () => ({
- useAgentStore: {
- getState: () => ({ internal_dispatchAgentMap: mocks.seedAgent }),
- setState: vi.fn(),
- },
-}));
-vi.mock('@/store/chat', () => ({
- useChatStore: {
- setState: (state: Record<string, unknown>) => Object.assign(mocks.chatState, state),
- },
-}));
-
-const agentMeta = (name: string): SharedAgentData['agentMeta'] => ({
- avatar: null,
- backgroundColor: null,
- description: null,
- name,
- title: null,
-});
-
-const identity: Pick<SharedAgentData, 'agentId' | 'agentMeta' | 'shareId'> = {
- agentId: 'agt_shared',
- agentMeta: agentMeta('Shared assistant'),
- shareId: 'share_1',
-};
-
-describe('useVisitorConversationSeed', () => {
- beforeEach(() => {
- mocks.chatState = { activeAgentId: 'agt_previous', activeTopicId: 'tpc_previous' };
- });
-
- it('restores the URL topic on direct entry and follows history navigation', () => {
- const { result, rerender } = renderHook(
- ({ topicId }: { topicId?: string }) => useVisitorConversationSeed(identity, topicId),
- { initialProps: { topicId: 'tpc_1' } as { topicId?: string } },
- );
- expect(result.current).toBe(true);
- expect(mocks.chatState).toMatchObject({ activeAgentId: 'agt_shared', activeTopicId: 'tpc_1' });
- rerender({ topicId: 'tpc_2' });
- expect(mocks.chatState.activeTopicId).toBe('tpc_2');
- rerender({ topicId: 'tpc_1' });
- expect(mocks.chatState.activeTopicId).toBe('tpc_1');
- rerender({ topicId: undefined });
- expect(mocks.chatState.activeTopicId).toBeUndefined();
- });
-
- it('does not reset a newly created topic when share metadata revalidates', () => {
- const { rerender } = renderHook((data) => useVisitorConversationSeed(data), {
- initialProps: identity,
- });
- act(() => {
- mocks.chatState.activeTopicId = 'tpc_created';
- });
- rerender({ ...identity, agentMeta: agentMeta('Renamed assistant') });
- expect(mocks.chatState.activeTopicId).toBe('tpc_created');
- rerender({ ...identity, agentId: 'agt_other', shareId: 'share_2' });
- expect(mocks.chatState.activeTopicId).toBeUndefined();
- });
-});
diff --git a/src/features/AgentShareVisitor/useVisitorConversationSeed.ts b/src/features/AgentShareVisitor/useVisitorConversationSeed.ts
deleted file mode 100644
index ef44475b018..00000000000
--- a/src/features/AgentShareVisitor/useVisitorConversationSeed.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-'use client';
-
-import type { SharedAgentData } from '@lobechat/types';
-import { useLayoutEffect, useState } from 'react';
-
-import { useAgentStore } from '@/store/agent';
-import { useChatStore } from '@/store/chat';
-
-type SharedAgentIdentity = Pick<SharedAgentData, 'agentId' | 'agentMeta' | 'shareId'>;
-
-const seedAgentMap = (agentId: string, agentMeta: SharedAgentIdentity['agentMeta']) => {
- // Visitors cannot call the owner-scoped agent-config API, so seed a minimal
- // `agentMap` entry from the share metadata by hand — mere presence is what
- // flips `isAgentConfigLoading*` off for the welcome header and chat input
- // skeletons. Merged via the store's dispatcher so nulls never clobber
- // existing fields.
- useAgentStore.getState().internal_dispatchAgentMap(agentId, {
- avatar: agentMeta.avatar ?? undefined,
- backgroundColor: agentMeta.backgroundColor ?? undefined,
- name: agentMeta.name ?? undefined,
- title: agentMeta.title ?? undefined,
- });
-};
-
-/**
- * Seeds the agent/chat stores for the visitor-facing share surface and reports
- * whether the URL selection has landed before mounting the conversation.
- *
- * Split into two effects with different dependencies on purpose:
- * - **selection effect** (`agentId`/`shareId`/`topicId`): initializes the
- * chat-store selection from the URL, including browser history navigation.
- * - **metadata effect** (`agentMeta`): non-destructive agentMap re-seed so
- * the header avatar/name/title stay fresh. An SWR revalidation hands back a
- * brand-new `agentMeta` object even when the identity hasn't changed;
- * folding this into the identity effect would wipe `activeTopicId` on every
- * metadata refresh and yank the visitor into a new conversation mid-chat.
- */
-export const useVisitorConversationSeed = (
- { agentId, agentMeta, shareId }: SharedAgentIdentity,
- topicId?: string,
-): boolean => {
- const [seeded, setSeeded] = useState<{
- agentId: string;
- shareId: string;
- topicId?: string;
- }>();
-
- useLayoutEffect(() => {
- seedAgentMap(agentId, agentMeta);
- useAgentStore.setState({ activeAgentId: agentId }, false, 'AgentShareVisitor/seedSharedAgent');
- useChatStore.setState(
- {
- activeAgentId: agentId,
- activeGroupId: undefined,
- activeThreadId: undefined,
- activeTopicId: topicId,
- },
- false,
- 'AgentShareVisitor/sync',
- );
- setSeeded({ agentId, shareId, topicId });
- // Metadata refreshes must not reset selection while a new topic is being created.
- }, [agentId, shareId, topicId]);
-
- useLayoutEffect(() => {
- seedAgentMap(agentId, agentMeta);
- }, [agentId, agentMeta]);
-
- return seeded?.agentId === agentId && seeded?.shareId === shareId && seeded?.topicId === topicId;
-};
diff --git a/src/features/AgentShareVisitor/useVisitorTopicRoute.test.ts b/src/features/AgentShareVisitor/useVisitorTopicRoute.test.ts
deleted file mode 100644
index be629ad2047..00000000000
--- a/src/features/AgentShareVisitor/useVisitorTopicRoute.test.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import { act, renderHook } from '@testing-library/react';
-import { createElement, type PropsWithChildren } from 'react';
-import { createMemoryRouter, RouterProvider } from 'react-router';
-import { describe, expect, it } from 'vitest';
-
-import { useVisitorTopicRoute } from './useVisitorTopicRoute';
-
-const setup = (initialEntry = '/a/my-bot/tpc_1') => {
- let router: ReturnType<typeof createMemoryRouter>;
- const wrapper = ({ children }: PropsWithChildren) => {
- router = createMemoryRouter([{ element: children, path: '/a/:slugOrId/:topicId?' }], {
- initialEntries: [initialEntry],
- });
- return createElement(RouterProvider, { router });
- };
- const hook = renderHook(useVisitorTopicRoute, { wrapper });
- return { ...hook, getRouter: () => router };
-};
-
-describe('useVisitorTopicRoute', () => {
- it('updates the URL for selection and restores topics through back/forward', async () => {
- const { result, getRouter } = setup();
- expect(result.current.topicId).toBe('tpc_1');
- await act(() => result.current.selectTopic('tpc_2'));
- expect(getRouter().state.location.pathname).toBe('/a/my-bot/tpc_2');
- expect(result.current.topicId).toBe('tpc_2');
- await act(() => getRouter().navigate(-1));
- expect(result.current.topicId).toBe('tpc_1');
- await act(() => getRouter().navigate(1));
- expect(result.current.topicId).toBe('tpc_2');
- await act(() => result.current.selectTopic());
- expect(getRouter().state.location.pathname).toBe('/a/my-bot');
- expect(result.current.topicId).toBeUndefined();
- });
-
- it('replaces the blank conversation URL once a topic is created', async () => {
- const { result, getRouter } = setup();
- await act(() => result.current.selectTopic());
- await act(() => result.current.onTopicCreated('tpc_created'));
- expect(getRouter().state.location.pathname).toBe('/a/my-bot/tpc_created');
- await act(() => getRouter().navigate(-1));
- expect(result.current.topicId).toBe('tpc_1');
- });
-
- it('does not push a duplicate entry when the destination is already current', async () => {
- const { result, getRouter } = setup('/a/my-bot');
- const initialKey = getRouter().state.location.key;
- await act(() => result.current.selectTopic());
- expect(getRouter().state.location.key).toBe(initialKey);
- // A first message that was still creating its topic must still land in the URL.
- await act(() => result.current.onTopicCreated('tpc_created'));
- expect(getRouter().state.location.pathname).toBe('/a/my-bot/tpc_created');
- const createdKey = getRouter().state.location.key;
- await act(() => result.current.selectTopic('tpc_created'));
- expect(getRouter().state.location.key).toBe(createdKey);
- });
-
- it('does not navigate back when a send finishes after selecting another topic', async () => {
- const { result, getRouter } = setup('/a/my-bot');
- const onTopicCreated = result.current.onTopicCreated;
- await act(() => result.current.selectTopic('tpc_other'));
- await act(() => onTopicCreated('tpc_late'));
- expect(getRouter().state.location.pathname).toBe('/a/my-bot/tpc_other');
- });
-});
diff --git a/src/features/AgentShareVisitor/useVisitorTopicRoute.ts b/src/features/AgentShareVisitor/useVisitorTopicRoute.ts
deleted file mode 100644
index 54a25b4c7c0..00000000000
--- a/src/features/AgentShareVisitor/useVisitorTopicRoute.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import { useLayoutEffect, useRef } from 'react';
-import { useLocation, useNavigate, useParams } from 'react-router';
-
-import { buildAgentShareVisitorPath } from './visitorPath';
-
-/** The URL owns selection; a created topic replaces its blank conversation entry. */
-export const useVisitorTopicRoute = () => {
- const { slugOrId = '', topicId } = useParams<{ slugOrId: string; topicId: string }>();
- const location = useLocation();
- const navigate = useNavigate();
- const currentLocationKey = useRef<string | undefined>(location.key);
-
- useLayoutEffect(() => {
- currentLocationKey.current = location.key;
- return () => {
- currentLocationKey.current = undefined;
- };
- }, [location.key]);
-
- /**
- * Re-selecting the current topic (or "new topic" while already on the blank
- * conversation) must not push a duplicate history entry: Back would look
- * inert, and the new location key would make a still-pending
- * `onTopicCreated` think the visitor left and skip the URL replacement.
- */
- const navigateIfChanged = (path: string, options?: { replace?: boolean }) => {
- if (path === location.pathname) return;
- navigate(path, options);
- };
-
- return {
- onTopicCreated: (createdTopicId: string) => {
- /** A delayed send must not pull the visitor back after they navigate away. */
- if (currentLocationKey.current !== location.key) return;
- navigateIfChanged(buildAgentShareVisitorPath(slugOrId, createdTopicId), { replace: true });
- },
- selectTopic: (nextTopicId?: string) => {
- navigateIfChanged(buildAgentShareVisitorPath(slugOrId, nextTopicId));
- },
- topicId,
- };
-};
diff --git a/src/features/AgentShareVisitor/useVisitorTopics.ts b/src/features/AgentShareVisitor/useVisitorTopics.ts
deleted file mode 100644
index a4e21f1f001..00000000000
--- a/src/features/AgentShareVisitor/useVisitorTopics.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import useSWR from 'swr';
-
-import { shareKeys } from '@/libs/swr/keys';
-import { shareChatService } from '@/services/shareChat';
-
-/**
- * The visitor's own topics on this shared agent (server-scoped by senderId).
- *
- * `enabled` is off for a non-interactive share (see `isShareInteractive`):
- * `shareChat.getTopics` requires `link` visibility, so an owner previewing
- * their own private share would otherwise always see a `FORBIDDEN` panel with
- * a retry that can never succeed. With the fetch skipped the panel falls
- * through to its empty state, which is the truth for a preview.
- */
-export const useVisitorTopics = (shareId: string, enabled = true) =>
- useSWR(
- enabled ? shareKeys.visitorTopics(shareId) : null,
- () => shareChatService.getTopics(shareId),
- {
- revalidateOnFocus: false,
- },
- );
diff --git a/src/features/AgentShareVisitor/visitorPath.test.ts b/src/features/AgentShareVisitor/visitorPath.test.ts
deleted file mode 100644
index 6e4d9ec4843..00000000000
--- a/src/features/AgentShareVisitor/visitorPath.test.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import {
- buildAgentShareOwnerPath,
- buildAgentShareSignInUrl,
- buildAgentShareVisitorPath,
-} from './visitorPath';
-
-describe('visitorPath', () => {
- it('builds the visitor page path under /a', () => {
- expect(buildAgentShareVisitorPath('my-bot')).toBe('/a/my-bot');
- });
-
- it('returns a signed-in visitor to the same share', () => {
- expect(buildAgentShareSignInUrl('my-bot')).toBe('/signin?callbackUrl=%2Fa%2Fmy-bot');
- });
-
- it('builds a bookmarkable topic path and preserves it through sign-in', () => {
- expect(buildAgentShareVisitorPath('my-bot', 'tpc_1')).toBe('/a/my-bot/tpc_1');
- expect(buildAgentShareSignInUrl('my-bot', 'tpc_1')).toBe(
- '/signin?callbackUrl=%2Fa%2Fmy-bot%2Ftpc_1',
- );
- });
-
- describe('buildAgentShareOwnerPath', () => {
- it('sends the creator to the share settings on desktop', () => {
- expect(buildAgentShareOwnerPath('agt_1')).toBe('/agent/agt_1/share');
- });
-
- it('sends the creator to the agent itself on mobile, which has no share settings page', () => {
- expect(buildAgentShareOwnerPath('agt_1', { mobile: true })).toBe('/agent/agt_1');
- });
- });
-});
diff --git a/src/features/AgentShareVisitor/visitorPath.ts b/src/features/AgentShareVisitor/visitorPath.ts
deleted file mode 100644
index cb3d5e5bd47..00000000000
--- a/src/features/AgentShareVisitor/visitorPath.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { buildAuthReturnUrl } from '@/utils/authReturnUrl';
-
-/**
- * Route prefix of the agent-share visitor page. `/a/<slug>` on purpose — short
- * enough to read aloud, and not `/agent/…`, which the marketing site already
- * uses for the public agent market, so a shared link can never be mistaken
- * for (or proxied to) a market listing.
- */
-export const AGENT_SHARE_VISITOR_PATH = '/a';
-
-/** Visitor page of an agent share, by custom slug or raw share id. */
-export const buildAgentShareVisitorPath = (slugOrId: string, topicId?: string) =>
- `${AGENT_SHARE_VISITOR_PATH}/${slugOrId}${topicId ? `/${topicId}` : ''}`;
-
-/** Sign-in URL that returns the visitor to the same share once signed in. */
-export const buildAgentShareSignInUrl = (slugOrId: string, topicId?: string) =>
- buildAuthReturnUrl('signin', buildAgentShareVisitorPath(slugOrId, topicId));
-
-/**
- * Where the CREATOR lands when they open their own share link: the share
- * settings page, or the agent itself on a platform without that page
- * (mobile). The creator is never a visitor of their own share.
- */
-export const buildAgentShareOwnerPath = (agentId: string, { mobile = false } = {}) =>
- mobile ? `/agent/${agentId}` : `/agent/${agentId}/share`;
diff --git a/src/routes/(main)/agent/profile/features/Header/index.test.tsx b/src/routes/(main)/agent/profile/features/Header/index.test.tsx
index 8bb4495b4b3..934af76e688 100644
--- a/src/routes/(main)/agent/profile/features/Header/index.test.tsx
+++ b/src/routes/(main)/agent/profile/features/Header/index.test.tsx
@@ -37,8 +37,11 @@ const mocks = vi.hoisted(() => ({
removeAgent: vi.fn(),
},
hasActiveWorkspace: true,
- /** What the share-entry hook's live-share lookup resolves to. */
- shareStatus: null as { visibility: 'link' | 'private' } | null,
+ /**
+ * What the Agent Share business slot reports. The rules behind it live with
+ * the deployment that offers sharing; this file only renders the outcome.
+ */
+ shareSupport: { publishable: false, supported: false, visible: false as boolean | undefined },
serverConfigState: {
featureFlags: { enableAgentShare: undefined as boolean | undefined },
// Business features on by default in these tests — the Cloud-only
@@ -58,14 +61,8 @@ const mocks = vi.hoisted(() => ({
},
}));
-// `useAgentShareSupported` looks the live share up (via SWR) only for an
-// account that may not publish; resolve it synchronously here.
-vi.mock('swr', () => ({
- default: (key: unknown, fetcher: () => unknown) => ({ data: key ? fetcher() : undefined }),
-}));
-
-vi.mock('@/services/agentShare', () => ({
- agentShareService: { getShareStatus: () => mocks.shareStatus },
+vi.mock('@/business/client/useAgentShareSupported', () => ({
+ useAgentShareSupported: () => mocks.shareSupport,
}));
vi.mock('@lobechat/const', async (importOriginal) => ({
@@ -298,6 +295,7 @@ describe('Agent profile Header', () => {
mocks.resourceAccess.canEditResource = true;
mocks.resourceAccess.canManageResource = true;
mocks.hasActiveWorkspace = true;
+ mocks.shareSupport = { publishable: false, supported: false, visible: false };
mocks.serverConfigState.featureFlags.enableAgentShare = undefined;
mocks.serverConfigState.serverConfig.enableBusinessFeatures = true;
});
@@ -349,73 +347,37 @@ describe('Agent profile Header', () => {
});
describe('share entry', () => {
- // Agent sharing is personal-only, so the entry needs a personal agent;
- // the rollout flag is on unless a case says otherwise.
- beforeEach(() => {
- mocks.hasActiveWorkspace = false;
- mocks.serverConfigState.featureFlags.enableAgentShare = true;
- mocks.shareStatus = null;
- });
-
- it('offers the share entry to a personal agent owner', () => {
- render(<Header />);
-
- expect(screen.getByTestId('share-entry-icon')).toBeInTheDocument();
- });
-
- // Outside the rollout allowlist the entry is hidden entirely …
- it('hides the share entry when the account may not publish and has no live share', () => {
- mocks.serverConfigState.featureFlags.enableAgentShare = false;
- mocks.shareStatus = null;
-
+ // Agent sharing runs a visitor's conversation on the creator's account, so
+ // the capability is contributed by the deployment that does that
+ // accounting. This file owns only what the header does with the answer;
+ // the rules themselves are tested with the slot's real implementation.
+ it('offers no share entry by default', () => {
render(<Header />);
expect(screen.queryByTestId('share-entry-icon')).toBeNull();
});
- // … unless a share is already live: an owner rolled back out of the
- // allowlist still needs the entry to reach (and revoke) it.
- it('keeps the share entry for a live share when the account may not publish', () => {
- mocks.serverConfigState.featureFlags.enableAgentShare = false;
- mocks.shareStatus = { visibility: 'link' };
-
- render(<Header />);
-
- expect(screen.getByTestId('share-entry-icon')).toBeInTheDocument();
- });
-
it('hides the share entry while the capability is still unresolved', () => {
- mocks.serverConfigState.featureFlags.enableAgentShare = undefined;
- mocks.shareStatus = null;
+ mocks.shareSupport = { publishable: false, supported: true, visible: undefined };
render(<Header />);
expect(screen.queryByTestId('share-entry-icon')).toBeNull();
});
- // Unlike the rollout flag above, `enableBusinessFeatures` is structural:
- // an OSS deployment has no Agent Share surface at all, server-enforced by
- // `ENABLE_BUSINESS_FEATURES` — there is no live share to revoke there, so
- // hiding the entry entirely (not just disabling publish) is correct.
- it('hides the share entry on a deployment without business features', () => {
- mocks.serverConfigState.serverConfig.enableBusinessFeatures = false;
+ it('offers the share entry when the deployment reports it visible', () => {
+ mocks.shareSupport = { publishable: true, supported: true, visible: true };
render(<Header />);
- expect(screen.queryByTestId('share-entry-icon')).toBeNull();
- });
-
- it('hides the share entry for a workspace agent', () => {
- mocks.hasActiveWorkspace = true;
-
- render(<Header />);
-
- expect(screen.queryByTestId('share-entry-icon')).toBeNull();
+ expect(screen.getByTestId('share-entry-icon')).toBeInTheDocument();
});
- // Share settings are a sibling tab of the profile group now, so the entry
+ // Share settings are a sibling tab of the profile group, so the entry
// navigates instead of opening a modal.
it('navigates to the share tab', () => {
+ mocks.shareSupport = { publishable: true, supported: true, visible: true };
+
render(<Header />);
fireEvent.click(screen.getByTestId('share-entry-icon'));
diff --git a/src/routes/(main)/agent/profile/features/Header/index.tsx b/src/routes/(main)/agent/profile/features/Header/index.tsx
index b3c88548211..86cf73ebb31 100644
--- a/src/routes/(main)/agent/profile/features/Header/index.tsx
+++ b/src/routes/(main)/agent/profile/features/Header/index.tsx
@@ -24,11 +24,11 @@ import { useAgentTransferToMemberMenuItem } from '@/business/client/hooks/useAge
import { useAuthorInfo } from '@/business/client/hooks/useAuthorInfo';
import { useBusinessAgentImportMenuItem } from '@/business/client/hooks/useBusinessAgentImportMenuItem';
import { useHasActiveWorkspace } from '@/business/client/hooks/useHasActiveWorkspace';
+import { useAgentShareSupported } from '@/business/client/useAgentShareSupported';
import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
import AgentBreadcrumb from '@/features/AgentBreadcrumb';
import { useAgentMarketSubmission } from '@/features/AgentMarketSubmission/useAgentMarketSubmission';
import AgentProfileTabs, { AGENT_PROFILE_TABS_CENTER_STYLE } from '@/features/AgentProfileTabs';
-import { useAgentShareSupported } from '@/features/AgentShareSettings/useAgentShareSupported';
import NavHeader from '@/features/NavHeader';
import { formatPageEditorInfoTime } from '@/features/PageEditor/formatPageEditorInfoTime';
import AccessLevelTag from '@/features/ResourcePermission/AccessLevelTag';
diff --git a/src/routes/(main)/agent/share/index.tsx b/src/routes/(main)/agent/share/index.tsx
index 6d2de0a4f43..a4f91a16443 100644
--- a/src/routes/(main)/agent/share/index.tsx
+++ b/src/routes/(main)/agent/share/index.tsx
@@ -3,8 +3,8 @@
import { memo, Suspense } from 'react';
import { useParams } from 'react-router';
+import AgentShareSettingsPage from '@/business/client/AgentShareSettingsPage';
import AgentShareSkeleton from '@/components/Skeleton/AgentShare';
-import AgentShareSettingsPage from '@/features/AgentShareSettings/Page';
import ResourceConfigAccessGate from '@/features/ResourcePermission/ResourceConfigAccessGate';
const AgentSharePage = memo(() => {
diff --git a/src/spa/BootShell/routeScope.test.ts b/src/spa/BootShell/routeScope.test.ts
index 0dc4d0fe8ae..dc5c054ee0d 100644
--- a/src/spa/BootShell/routeScope.test.ts
+++ b/src/spa/BootShell/routeScope.test.ts
@@ -23,8 +23,8 @@ describe('isMainLayoutLocation', () => {
// The shell would otherwise promise chrome these pages never render — the
// exact "logo → app-shell skeleton → logo → page" sequence this guards.
it.each([
- ['Web', webDesktopRoutes, ['/onboarding', '/verify-im', '/a/my-bot']],
- ['Electron', electronDesktopRoutes, ['/desktop-onboarding', '/a/my-bot']],
+ ['Web', webDesktopRoutes, ['/onboarding', '/verify-im']],
+ ['Electron', electronDesktopRoutes, ['/desktop-onboarding']],
])('%s excludes standalone routes outside the main layout', (_, routes, paths) => {
for (const pathname of paths as string[]) {
expect(isMainLayoutLocation(routes as never, pathname), `${pathname} is standalone`).toBe(
diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsx
index f3ee8b78279..c2e2e8bfceb 100644
--- a/src/spa/router/desktopRouter.shared.tsx
+++ b/src/spa/router/desktopRouter.shared.tsx
@@ -32,7 +32,6 @@ import {
BusinessResourceRoutes,
} from '@/business/client/BusinessDesktopRoutes';
import BrandTextLoading from '@/components/Loading/BrandTextLoading';
-import AgentShareVisitorSkeleton from '@/components/Skeleton/AgentShareVisitor';
import AppsSkeleton from '@/components/Skeleton/Apps';
import CommunityHomeSkeleton from '@/components/Skeleton/CommunityHome';
import CommunityListSkeleton from '@/components/Skeleton/CommunityList';
@@ -47,8 +46,6 @@ import { createSurfaceSkeleton } from '@/components/Skeleton/Surface';
import { acceptanceRouteMeta } from '@/features/Acceptance/routeMeta';
import { agentDocumentRouteMeta } from '@/features/AgentDocumentPage/routeMeta';
import { goalDetailRouteMeta, goalsRouteMeta } from '@/features/AgentGoals/routeMeta';
-import { agentShareVisitorRouteMeta } from '@/features/AgentShareVisitor/routeMeta';
-import { AGENT_SHARE_VISITOR_PATH } from '@/features/AgentShareVisitor/visitorPath';
import { taskRouteMeta, tasksRouteMeta } from '@/features/AgentTasks/routeMeta';
import { agentsRouteMeta } from '@/features/AgentViewAll/routeMeta';
import { pageRouteMeta } from '@/features/Pages/routeMeta';
@@ -1654,21 +1651,6 @@ export const createSharedDesktopRoutes = ({
errorElement: <ErrorBoundary />,
path: '/',
},
- {
- // The agent-share visitor page. A sibling of the main layout, not a child:
- // a visitor has no business with the creator's nav rail, workspace scope,
- // or command palette, and the page draws its own product bar. Outside
- // `withSegmentFallback`, so the skeleton is passed explicitly — the same
- // one the page shows while the share itself loads.
- element: dynamicElement(
- () => import('@/features/AgentShareVisitor/Page'),
- 'Desktop > Share > Agent',
- { fallback: delayed(<AgentShareVisitorSkeleton />) },
- ),
- errorElement: <ErrorBoundary />,
- handle: { meta: agentShareVisitorRouteMeta },
- path: `${AGENT_SHARE_VISITOR_PATH}/:slugOrId/:topicId?`,
- },
...BusinessDesktopRoutesWithoutMainLayout,
...platformRoutes,
onboardingRoute,
diff --git a/src/spa/router/desktopRouter.sync.test.tsx b/src/spa/router/desktopRouter.sync.test.tsx
index d21b024ea95..80c8b46f8ea 100644
--- a/src/spa/router/desktopRouter.sync.test.tsx
+++ b/src/spa/router/desktopRouter.sync.test.tsx
@@ -283,11 +283,12 @@ describe('desktop router shared definition', () => {
// `/share/*` moved to the standalone Share app (apps/share).
expect(webPaths).not.toContain('/share/t');
expect(webPaths).not.toContain('/share/page');
- // …and the agent-share visitor surface lives at `/a/:slugOrId`, a sibling
- // of the main layout on every platform (Web, Electron, and the mobile
- // router — see mobileRouter.test.tsx).
- expect(webPaths).toContain('/a/:slugOrId/:topicId?');
- expect(electronPaths).toContain('/a/:slugOrId/:topicId?');
+ // …and the agent-share visitor surface is no longer defined here: it runs
+ // a visitor's conversation on the creator's account, so it ships with the
+ // deployment that does that accounting and registers itself through
+ // `BusinessDesktopRoutesWithoutMainLayout`.
+ expect(webPaths).not.toContain('/a/:slugOrId/:topicId?');
+ expect(electronPaths).not.toContain('/a/:slugOrId/:topicId?');
expect(webPaths).not.toContain('/verify');
expect(webPaths).toContain('/acceptance');
expect(webPaths).toContain('/onboarding');
@@ -548,20 +549,12 @@ describe('desktop router shared definition', () => {
it.each([
['Web', webDesktopRoutes],
['Electron', electronDesktopRoutes],
- ])(
- '%s serves the agent-share visitor page on /a/:slugOrId outside the main layout',
- (_, routes) => {
- const matches = matchRoutes(routes, '/a/my-bot');
-
- expect(matches).toHaveLength(1);
- expect(matches?.[0]?.route.path).toBe('/a/:slugOrId/:topicId?');
- expect(matches?.[0]?.params).toMatchObject({ slugOrId: 'my-bot' });
-
- const topicMatches = matchRoutes(routes, '/a/my-bot/tpc_saved');
- expect(topicMatches).toHaveLength(1);
- expect(topicMatches?.[0]?.params).toEqual({ slugOrId: 'my-bot', topicId: 'tpc_saved' });
- },
- );
+ ])('%s leaves the agent-share visitor surface to the business routes', (_, routes) => {
+ // The open-source tree no longer defines `/a/*`; a deployment that offers
+ // agent sharing contributes it through the business slot, so the path
+ // falls through to not-found here.
+ expect(matchRoutes(routes, '/a/my-bot')?.at(-1)?.route.path).toBe('*');
+ });
it('keeps business resource and task routes in the shared definition', async () => {
const [sharedSource] = await readRouterSources();
diff --git a/src/spa/router/mobileRouter.config.tsx b/src/spa/router/mobileRouter.config.tsx
index c087395b714..798888612b6 100644
--- a/src/spa/router/mobileRouter.config.tsx
+++ b/src/spa/router/mobileRouter.config.tsx
@@ -6,14 +6,11 @@ import {
BusinessMobileRoutesWithMainLayout,
BusinessMobileRoutesWithoutMainLayout,
} from '@/business/client/BusinessMobileRoutes';
-import AgentShareVisitorSkeleton from '@/components/Skeleton/AgentShareVisitor';
import AppsSkeleton from '@/components/Skeleton/Apps';
import CommunityListSkeleton from '@/components/Skeleton/CommunityList';
import { delayed } from '@/components/Skeleton/Delayed';
import { createSurfaceSkeleton } from '@/components/Skeleton/Surface';
import { acceptanceRouteMeta } from '@/features/Acceptance/routeMeta';
-import { agentShareVisitorRouteMeta } from '@/features/AgentShareVisitor/routeMeta';
-import { AGENT_SHARE_VISITOR_PATH } from '@/features/AgentShareVisitor/visitorPath';
import { mobileAgentSettingsRouteMeta } from '@/features/RouteMeta/mobileRouteMeta';
import WorkspaceProviderRedirect from '@/features/WorkspaceSetting/ProviderRedirect';
import { agentRouteMeta } from '@/routes/(main)/agent/features/routeMeta';
@@ -674,20 +671,6 @@ export const mobileRoutes: RouteObject[] = [
},
...BusinessMobileRoutesWithoutMainLayout,
- // The agent-share visitor page needs the full chat runtime, so it stays in
- // the main SPA on every platform (`/share/*` proper is the standalone Share
- // app). Outside the `/` layout: a visitor gets no nav, no workspace scope.
- {
- element: dynamicElement(
- () => import('@/features/AgentShareVisitor/Page'),
- 'Mobile > Share > Agent',
- { fallback: delayed(<AgentShareVisitorSkeleton />) },
- ),
- errorElement: <ErrorBoundary />,
- handle: { meta: agentShareVisitorRouteMeta },
- path: `${AGENT_SHARE_VISITOR_PATH}/:slugOrId/:topicId?`,
- },
-
// Messenger verify route (outside main layout)
{
element: dynamicElement(() => import('@/routes/verify-im'), 'Mobile > VerifyIm'),
diff --git a/src/spa/router/mobileRouter.test.tsx b/src/spa/router/mobileRouter.test.tsx
index 26f9c32182b..ec34dfe26e9 100644
--- a/src/spa/router/mobileRouter.test.tsx
+++ b/src/spa/router/mobileRouter.test.tsx
@@ -8,18 +8,12 @@ import { mobileRoutes } from './mobileRouter.config';
import { getRouteMetaFromHandle } from './routeMeta';
describe('mobileRouter agent share route', () => {
- it('serves the agent-share visitor page on /a/:slugOrId outside the main layout', () => {
- const matches = matchRoutes(mobileRoutes, '/a/my-agent');
-
- expect(matches).toHaveLength(1);
- expect(matches?.[0]?.route.path).toBe('/a/:slugOrId/:topicId?');
- expect(matches?.[0]?.params).toMatchObject({ slugOrId: 'my-agent' });
- });
-
- it('opens a visitor topic directly without the owner layout', () => {
- const matches = matchRoutes(mobileRoutes, '/a/my-agent/tpc_saved');
- expect(matches).toHaveLength(1);
- expect(matches?.[0]?.params).toEqual({ slugOrId: 'my-agent', topicId: 'tpc_saved' });
+ it('leaves the agent-share visitor surface to the business routes', () => {
+ // Agent sharing runs a visitor's conversation on the creator's account, so
+ // the surface ships with the deployment that does that accounting and
+ // registers itself through `BusinessMobileRoutesWithoutMainLayout`.
+ // Nothing claims `/a/*` any more, so it falls through to not-found.
+ expect(matchRoutes(mobileRoutes, '/a/my-agent')?.at(-1)?.route.path).toBe('*');
});
it('keeps the creator agent surface on /agent/:aid', () => {