🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(agent-share): share settings tabs, /a/:slug visitor page with product bar and editor (#19180)
YuTengjing36ca481bf021
diff --git a/apps/server/src/routers/lambda/__tests__/agent.test.ts b/apps/server/src/routers/lambda/__tests__/agent.test.tsindex 785420c4e90..17cf374e444 100644--- a/apps/server/src/routers/lambda/__tests__/agent.test.ts+++ b/apps/server/src/routers/lambda/__tests__/agent.test.ts@@ -5,7 +5,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { INBOX_SESSION_ID } from '@/const/session';import { DEFAULT_AGENT_CONFIG } from '@/const/settings';import { AgentModel } from '@/database/models/agent';-import { AgentShareModel } from '@/database/models/agentShare';import { ChatGroupModel } from '@/database/models/chatGroup';import { FileModel } from '@/database/models/file';import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';@@ -49,10 +48,6 @@ vi.mock('@/database/models/agent', () => ({AgentModel: vi.fn(),}));-vi.mock('@/database/models/agentShare', () => ({- AgentShareModel: { findBySlugOrId: vi.fn() },-}));-vi.mock('@/database/models/session', () => ({SessionModel: vi.fn(),}));@@ -1027,92 +1022,28 @@ describe('agentRouter', () => {});});- describe('resolveAgentRoute', () => {- const findBySlugOrIdMock = vi.mocked(AgentShareModel.findBySlugOrId);-+ describe('resolveAgentRoute (released-client compatibility)', () => {it('treats an id-shaped param as an own agent without touching the database', async () => {const caller = agentRouter.createCaller(mockCtx);const result = await caller.resolveAgentRoute({ slugOrId: 'agt_abc123' });expect(result).toEqual({ agentId: 'agt_abc123', kind: 'own' });expect(agentModelMock.resolveIdBySlug).not.toHaveBeenCalled();- expect(findBySlugOrIdMock).not.toHaveBeenCalled();});- it('resolves an own agent slug to its id, without a share lookup', async () => {+ it('resolves an own agent slug to its id', async () => {agentModelMock.resolveIdBySlug.mockResolvedValue('agt_from_slug');const caller = agentRouter.createCaller(mockCtx);const result = await caller.resolveAgentRoute({ slugOrId: 'my-bot' });expect(result).toEqual({ agentId: 'agt_from_slug', kind: 'own' });- expect(findBySlugOrIdMock).not.toHaveBeenCalled();- });-- it('falls back to an agent share when no own agent claims the slug', async () => {- agentModelMock.resolveIdBySlug.mockResolvedValue(null);- findBySlugOrIdMock.mockResolvedValue({- ownerId: 'someone-else',- shareId: 'share-1',- visibility: 'link',- } as any);-- const caller = agentRouter.createCaller(mockCtx);-- expect(await caller.resolveAgentRoute({ slugOrId: 'shared-bot' })).toEqual({ kind: 'share' });- });-- it('sends the creator following their OWN share link to the agent, not the visitor surface', async () => {- agentModelMock.resolveIdBySlug.mockResolvedValue(null);- findBySlugOrIdMock.mockResolvedValue({- agentId: 'agt_mine',- ownerId: mockCtx.userId,- shareId: 'share-1',- } as any);-- const caller = agentRouter.createCaller(mockCtx);-- expect(await caller.resolveAgentRoute({ slugOrId: 'my-share-slug' })).toEqual({- agentId: 'agt_mine',- kind: 'ownShare',- });- });-- // Same rule as `assertShareAccess`: a paused share must look exactly like- // a missing one to a stranger, or this resolver becomes a slug oracle.- it('reports a stranger’s private share as not found', async () => {- agentModelMock.resolveIdBySlug.mockResolvedValue(null);- findBySlugOrIdMock.mockResolvedValue({- ownerId: 'someone-else',- shareId: 'share-1',- visibility: 'private',- } as any);-- const caller = agentRouter.createCaller(mockCtx);-- expect(await caller.resolveAgentRoute({ slugOrId: 'private-bot' })).toEqual({- kind: 'notFound',- });- });-- it('routes a stranger’s link share to the share surface', async () => {- agentModelMock.resolveIdBySlug.mockResolvedValue(null);- findBySlugOrIdMock.mockResolvedValue({- ownerId: 'someone-else',- shareId: 'share-1',- visibility: 'link',- } as any);-- const caller = agentRouter.createCaller(mockCtx);-- expect(await caller.resolveAgentRoute({ slugOrId: 'open-bot' })).toEqual({- kind: 'share',- });});- it('reports not found when the slug matches neither an agent nor a share', async () => {+ // The lookup is ownership-scoped, so a stranger's slug is indistinguishable+ // from a missing one and this resolver cannot become a slug oracle.+ it('reports not found when no agent of the caller claims the slug', async () => {agentModelMock.resolveIdBySlug.mockResolvedValue(null);- findBySlugOrIdMock.mockResolvedValue(null);const caller = agentRouter.createCaller(mockCtx);diff --git a/apps/server/src/routers/lambda/agent.ts b/apps/server/src/routers/lambda/agent.tsindex 6d96f9cd10a..cc3cbfb1cfc 100644--- a/apps/server/src/routers/lambda/agent.ts+++ b/apps/server/src/routers/lambda/agent.ts@@ -19,7 +19,6 @@ import {AgentOwnedByGroupError,} from '@/database/models/agent';import { AGENT_COPY_IN_PROGRESS } from '@/database/models/agentCopyJob';-import { AgentShareModel } from '@/database/models/agentShare';import {AGENT_TRANSFER_IN_PROGRESS,AgentTransferJobModel,@@ -119,17 +118,14 @@ const protectAgentConfig = async <T extends Record<string, any>>(/** What a `/agent/:slugOrId` param resolves to — see `resolveAgentRoute`. */export interface AgentRouteResolution {- /** The resolved agent id. Present for `own` and `ownShare` routes. */+ /** The resolved agent id. Present for `own` routes. */agentId?: string;/*** `own`: one of the caller's agents (by id or by agent slug).- * `ownShare`: a share link of the caller's OWN agent — the creator opened- * their own share URL, and is sent to that agent's share settings instead- * of the visitor surface.- * `share`: someone else's agent share (access is still gated by `getSharedAgent`).- * `notFound`: neither — the caller sees the agent not-found surface.+ * `notFound`: no agent of the caller's claims the param — the caller sees+ * the agent not-found surface.*/- kind: 'own' | 'ownShare' | 'share' | 'notFound';+ kind: 'own' | 'notFound';}const agentProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {@@ -1461,10 +1457,6 @@ export const agentRouter = router({** Read-only and ownership-scoped: an unknown slug and someone else's slug both* return `null`, so this cannot be used to probe which slugs exist.- *- * @deprecated Superseded by `resolveAgentRoute`, which answers the same- * question plus "is this an agent share?" in one round trip. Kept because- * already-shipped clients (e.g. an installed desktop bundle) still call it.*/resolveAgentIdBySlug: agentProcedure.input(z.object({ slug: z.string() }))@@ -1474,21 +1466,19 @@ export const agentRouter = router({}),/**- * Decide what `/agent/:slugOrId` points at: one of the caller's own agents,- * or an agent share opened by a visitor. Both surfaces live on the same- * route, so the client needs a single answer before it can pick a shell.+ * Compatibility endpoint for released clients that still resolve their+ * agent routes here. Keep ownership-scoped lookup behavior so those clients+ * can open their own agents without restoring share-link routing.+ *+ * @deprecated New clients resolve slugs with `resolveAgentIdBySlug`.** Resolution order, cheapest first:* 1. an id-shaped param is always an own-agent route (no query at all);* 2. an ownership-scoped agent-slug lookup;- * 3. an agent-share lookup by custom slug or share id.+ * 3. otherwise `notFound`.*- * Step 3 applies the same existence rule as `assertShareAccess`: a private- * share is only visible to its owner, so a stranger gets `notFound` rather- * than `share` and cannot use this resolver to probe which custom slugs /- * ids exist. `share.getSharedAgent` remains the access gate for everything- * else (sign-in state, view counting). An own slug always wins over a share- * slug of the same name.+ * The slug lookup is ownership-scoped on purpose: a stranger's slug reads as+ * `notFound`, so this resolver cannot be used to probe which slugs exist.*/resolveAgentRoute: agentProcedure.input(z.object({ slugOrId: z.string().trim().min(1) }))@@ -1503,14 +1493,6 @@ export const agentRouter = router({const agentId = await ctx.agentModel.resolveIdBySlug(slugOrId);if (agentId) return { agentId, kind: 'own' };- const share = await AgentShareModel.findBySlugOrId(ctx.serverDB, slugOrId);- // The creator following their own share link is not a visitor: the- // client redirects `ownShare` to the agent's share settings.- if (share) {- if (share.ownerId === ctx.userId) return { agentId: share.agentId, kind: 'ownShare' };- if (share.visibility === 'link') return { kind: 'share' };- }-return { kind: 'notFound' };}),diff --git a/e2e/src/features/routes/core-routes.feature b/e2e/src/features/routes/core-routes.featureindex e727b0f5301..a837e8ef3eb 100644--- a/e2e/src/features/routes/core-routes.feature+++ b/e2e/src/features/routes/core-routes.feature@@ -38,3 +38,8 @@ 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 keyboarddiff --git a/e2e/src/steps/routes/routes.steps.ts b/e2e/src/steps/routes/routes.steps.tsindex 6d1aa7c584b..f521393b728 100644--- a/e2e/src/steps/routes/routes.steps.ts+++ b/e2e/src/steps/routes/routes.steps.ts@@ -1,7 +1,7 @@import { Given, Then } from '@cucumber/cucumber';import { expect } from '@playwright/test';-import { CustomWorld } from '../../support/world';+import type { CustomWorld } from '../../support/world';// ============================================// Given Steps (Preconditions)@@ -17,6 +17,18 @@ 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/eslint.config.mjs b/eslint.config.mjsindex 667b3c12382..a39a6a74372 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -205,6 +205,25 @@ export default eslint(}),},},+ {+ files: ['src/components/Skeleton/**/*.{ts,tsx}'],+ rules: {+ 'no-restricted-imports': createRestrictedImportRule({+ paths: [+ {+ name: '@/components/Skeleton',+ message:+ 'Skeleton internals must import sibling components directly to avoid a cycle through their own barrel.',+ },+ {+ name: '@/components/Skeleton/index',+ message:+ 'Skeleton internals must import sibling components directly to avoid a cycle through their own barrel.',+ },+ ],+ }),+ },+ },{files: ['src/features/Conversation/**/*.{ts,tsx}'],rules: {diff --git a/locales/en-US/agent.json b/locales/en-US/agent.jsonindex 44aee57b918..65ed4618ed0 100644--- a/locales/en-US/agent.json+++ b/locales/en-US/agent.json@@ -312,8 +312,6 @@"share.settings.link.slugError.tooLong": "Custom links can be at most 64 characters.","share.settings.link.slugError.tooShort": "Custom links need at least 3 characters.","share.settings.link.slugHint": "3–64 characters: lowercase letters, numbers and hyphens. Leave it empty to use the generated link.",- "share.settings.link.slugLabel": "Custom link",- "share.settings.link.slugPlaceholder": "my-agent","share.settings.link.slugSaved": "Custom link updated","share.settings.link.title": "Share link","share.settings.link.viewCount": "{{views}} views",@@ -329,10 +327,14 @@"share.settings.permissions.showModelInfo": "Show which model is used","share.settings.permissions.showModelInfoHint": "Off by default: your model and provider choice stays hidden.","share.settings.permissions.title": "Permissions",+ "share.settings.tabs.access": "Access",+ "share.settings.tabs.stats": "Stats","share.settings.title": "Share Agent",+ "share.settings.tools.apiGrantedCount": "{{granted}} of {{total}} APIs granted","share.settings.tools.apiNotAvailableToVisitors": "This action can never be used in a shared run — it either needs your approval or is otherwise off-limits to visitors.","share.settings.tools.apiWritesOwnerData": "Visitors can never write to your memory — this action stays off in shared runs.","share.settings.tools.availableGroup": "Not granted · {{count}}",+ "share.settings.tools.configureApis": "Choose which APIs visitors can call","share.settings.tools.desc": "Only the tools you tick here can be called during a visitor run. Tools that could reach your device or local files are never offered.","share.settings.tools.empty": "This Agent has no tools that can be granted to visitors.","share.settings.tools.grantedEmpty": "No tools granted yet — visitors get a plain chat. Pick from the list below to grant one.",@@ -370,6 +372,7 @@"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.topBar.home": "Go to my LobeHub","share.visitor.topics.empty": "No conversations yet","share.visitor.topics.new": "New conversation","share.visitor.topics.title": "Conversations",diff --git a/locales/en-US/spend.json b/locales/en-US/spend.jsonindex 27c6f198e00..4067c894e4c 100644--- a/locales/en-US/spend.json+++ b/locales/en-US/spend.json@@ -6,6 +6,7 @@"duration.stage.end": "End","duration.stage.firstToken": "First Token","duration.stage.start": "Start",+ "table.agentShareDesc": "Every model call a visitor of this share triggered, billed to your account.","table.columns.TTFT.tooltip": "Time To First Token, unit: seconds","table.columns.duration": "Duration","table.columns.model": "Model",diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.jsonindex b8c0f1436b4..9c15f459d7d 100644--- a/locales/zh-CN/agent.json+++ b/locales/zh-CN/agent.json@@ -312,8 +312,6 @@"share.settings.link.slugError.tooLong": "自定义链接最多 64 个字符。","share.settings.link.slugError.tooShort": "自定义链接至少需要 3 个字符。","share.settings.link.slugHint": "3–64 个字符,仅支持小写字母、数字和连字符。留空则使用系统生成的链接。",- "share.settings.link.slugLabel": "自定义链接",- "share.settings.link.slugPlaceholder": "my-agent","share.settings.link.slugSaved": "自定义链接已更新","share.settings.link.title": "分享链接","share.settings.link.viewCount": "被浏览 {{views}} 次",@@ -329,10 +327,14 @@"share.settings.permissions.showModelInfo": "展示使用的模型","share.settings.permissions.showModelInfoHint": "默认关闭:不向访客暴露你选择的模型和服务商。","share.settings.permissions.title": "权限",+ "share.settings.tabs.access": "授权",+ "share.settings.tabs.stats": "统计","share.settings.title": "分享助手",+ "share.settings.tools.apiGrantedCount": "已开放 {{granted}}/{{total}} 个接口","share.settings.tools.apiNotAvailableToVisitors": "该操作无法在分享运行中使用:它要么需要你本人确认,要么本就不对访客开放。","share.settings.tools.apiWritesOwnerData": "访客不能写入你的记忆,该操作在分享运行中始终关闭。","share.settings.tools.availableGroup": "未开放 · {{count}}",+ "share.settings.tools.configureApis": "选择访客可调用的接口","share.settings.tools.desc": "只有在这里勾选的工具才能在访客运行中被调用。可能触达你设备或本地文件的工具永远不会出现在列表中。","share.settings.tools.empty": "这个助手没有可以开放给访客的工具。","share.settings.tools.grantedEmpty": "还没有开放任何工具,访客只能纯聊天。从下面的列表里勾选即可开放。",@@ -370,6 +372,7 @@"share.visitor.input.send": "发送","share.visitor.input.stop": "停止","share.visitor.privacyNotice": "本次会话运行在创建者的账号下,内容可能对创建者可见,请勿发送敏感信息。",+ "share.visitor.topBar.home": "回到我的 LobeHub","share.visitor.topics.empty": "还没有会话","share.visitor.topics.new": "新建会话","share.visitor.topics.title": "会话",diff --git a/locales/zh-CN/spend.json b/locales/zh-CN/spend.jsonindex 229dadd342f..cd51564b775 100644--- a/locales/zh-CN/spend.json+++ b/locales/zh-CN/spend.json@@ -6,6 +6,7 @@"duration.stage.end": "结束","duration.stage.firstToken": "首个令牌","duration.stage.start": "开始",+ "table.agentShareDesc": "访客通过这个分享触发的每一次模型调用,费用记在你的账户上。","table.columns.TTFT.tooltip": "首令牌时间,单位:秒","table.columns.duration": "耗时","table.columns.model": "模型",diff --git a/packages/const/src/agentShare.ts b/packages/const/src/agentShare.tsindex c1cf290c791..ac2edc664ff 100644--- a/packages/const/src/agentShare.ts+++ b/packages/const/src/agentShare.ts@@ -68,12 +68,13 @@ export const AGENT_SHARE_SLUG_PATTERN = /^[a-z0-9][a-z0-9-]{1,62}[a-z0-9]$/;/*** Slugs a share may not claim. Two groups:*- * 1. words that collide with existing (or foreseeable) static routes under the- * agent surface (e.g. `/agent/<slug>`, `/agent/new`), or that would- * otherwise confuse a share URL;- * 2. every builtin agent slug — a share lives at `/agent/<slug>`, the same- * route the creator's own agents use, and an own agent always wins the- * lookup, so a share taking a builtin slug would be permanently unreachable.+ * 1. words that collide with existing (or foreseeable) static routes next to+ * the share URL (`/a/<slug>`) or the agent surface (`/agent/new`), or that+ * would otherwise confuse a share URL;+ * 2. every builtin agent slug — share links used to live at `/agent/<slug>`,+ * the same route the creator's own agents use, and such legacy links are+ * still resolved there, where an own agent always wins the lookup. A share+ * on a builtin slug would be unreachable from any of those links.** The builtin slugs are duplicated here rather than imported: `@lobechat/const`* sits *below* `@lobechat/builtin-agents` in the dependency graph. The copy isdiff --git a/packages/database/src/models/__tests__/agentShare.test.ts b/packages/database/src/models/__tests__/agentShare.test.tsindex 7e06d75f506..cea4a49755d 100644--- a/packages/database/src/models/__tests__/agentShare.test.ts+++ b/packages/database/src/models/__tests__/agentShare.test.ts@@ -38,6 +38,9 @@ describe('AgentShareModel', () => {description: 'Shareable agent',id: agentId,name: 'Shareable Agent',+ // Explicit (the column defaults to random words): `create` seeds the+ // share slug from it, so tests below can assert the exact value.+ slug: 'shareable-agent',title: 'Shareable Agent Title',userId,},@@ -91,6 +94,63 @@ describe('AgentShareModel', () => {expect(rows[0].visibility).toBe('private');});+ describe('profile slug seed', () => {+ it("seeds the share slug from the agent's own profile slug", async () => {+ await serverDB+ .update(agents)+ .set({ slug: 'wild-built-using' })+ .where(eq(agents.id, agentId));++ const share = await agentShareModel.create(agentId, 'link');++ expect(share.shareConfig.slug).toBe('wild-built-using');+ expect(await AgentShareModel.findBySlugOrId(serverDB, 'wild-built-using')).toMatchObject({+ agentId,+ });+ });++ it('leaves the slug unset when another share already holds it', async () => {+ // Agent slugs are unique per owner only, so two owners can both have+ // an agent called `shared-name`; the share slug namespace is global.+ await serverDB.update(agents).set({ slug: 'shared-name' }).where(eq(agents.id, agentId));+ await serverDB+ .update(agents)+ .set({ slug: 'shared-name' })+ .where(eq(agents.id, otherAgentId));++ const first = await otherAgentShareModel.create(otherAgentId, 'link');+ const second = await agentShareModel.create(agentId, 'link');++ expect(first.shareConfig.slug).toBe('shared-name');+ expect(second.shareConfig.slug).toBeUndefined();+ expect(await AgentShareModel.findBySlugOrId(serverDB, 'shared-name')).toMatchObject({+ agentId: otherAgentId,+ });+ });++ it.each([+ ['reserved word', 'settings'],+ ['too short for a share slug', 'ab'],+ ])('leaves the slug unset when the profile slug is a %s', async (_, slug) => {+ await serverDB.update(agents).set({ slug }).where(eq(agents.id, agentId));++ const share = await agentShareModel.create(agentId, 'link');++ expect(share.shareConfig.slug).toBeUndefined();+ });++ it('does not touch the slug of an existing share on re-create', async () => {+ await serverDB.update(agents).set({ slug: 'first-name' }).where(eq(agents.id, agentId));+ await agentShareModel.create(agentId, 'link');+ await agentShareModel.updateSlug(agentId, null);+ await serverDB.update(agents).set({ slug: 'second-name' }).where(eq(agents.id, agentId));++ const recreated = await agentShareModel.create(agentId, 'link');++ expect(recreated.shareConfig.slug).toBeUndefined();+ });+ });+it('rejects missing, foreign, and workspace agents', async () => {await expect(agentShareModel.create('missing-agent')).rejects.toMatchObject({code: 'FORBIDDEN',@@ -141,8 +201,11 @@ describe('AgentShareModel', () => {const updated = await agentShareModel.updateConfig(agentId, config);const readBack = await agentShareModel.getByAgentId(agentId);- expect(updated?.shareConfig).toEqual(config);- expect(readBack?.shareConfig).toEqual(config);+ // The slug seeded from the agent's profile slug at `create` survives a+ // full config overwrite — it is owner-facing url state, not config.+ const expected = { ...config, slug: 'shareable-agent' };+ expect(updated?.shareConfig).toEqual(expected);+ expect(readBack?.shareConfig).toEqual(expected);});it('atomically merges stale cross-context patches without losing sibling fields', async () => {@@ -179,7 +242,8 @@ describe('AgentShareModel', () => {// `0` is a real cap ("stop all visitor runs"), never a cleared one.expect(updated?.shareConfig.monthlySpendLimit).toBe(0);expect(updated?.shareConfig.showModelInfo).toBe(true);- expect(updated?.shareConfig.slug).toBeUndefined();+ // The seeded profile slug is untouched; the smuggled one never lands.+ expect(updated?.shareConfig.slug).toBe('shareable-agent');expect(await AgentShareModel.findBySlugOrId(serverDB, 'sneaky-slug')).toBeNull();});diff --git a/packages/database/src/models/agentShare.ts b/packages/database/src/models/agentShare.tsindex b311cfa375d..566e73ad324 100644--- a/packages/database/src/models/agentShare.ts+++ b/packages/database/src/models/agentShare.ts@@ -60,8 +60,24 @@ export type AgentShareData = NonNullable</** Minimal locked-row snapshot returned by {@link AgentShareModel.lockOwnedAgentRow}. */interface LockedAgentSnapshot {id: string;+ /** The agent's own profile slug (`agents.slug`), unique per owner only. */+ slug: string | null;}+/**+ * Static share-slug rules shared by the owner-facing `updateSlug` and the+ * best-effort seed in `create`. A UUID-shaped slug would be unreachable:+ * `findBySlugOrId` resolves UUID-shaped input as a share id before ever trying+ * the slug lookup. Returns `null` when the slug passes.+ */+const getShareSlugRejection = (+ slug: string,+): 'INVALID_SHARE_SLUG' | 'RESERVED_SHARE_SLUG' | null => {+ if (!AGENT_SHARE_SLUG_PATTERN.test(slug) || isUuid(slug)) return 'INVALID_SHARE_SLUG';+ if (RESERVED_AGENT_SHARE_SLUGS.includes(slug)) return 'RESERVED_SHARE_SLUG';+ return null;+};+export class AgentShareModel {private db: LobeChatDatabase;private userId: string;@@ -103,7 +119,7 @@ export class AgentShareModel {ownerId: string,): Promise<LockedAgentSnapshot | null> => {const [agent] = await tx- .select({ id: agents.id })+ .select({ id: agents.id, slug: agents.slug }).from(agents).where(and(eq(agents.id, agentId), eq(agents.userId, ownerId), isNull(agents.workspaceId))).for('update');@@ -111,6 +127,62 @@ export class AgentShareModel {return agent ?? null;};+ /**+ * Cross-agent slug uniqueness barrier, to be called from an already-open+ * transaction. `shareConfig.slug` has no unique index (see the schema+ * JSDoc), and the `agents.id FOR UPDATE` lock only serializes writes on the+ * SAME agent: two agents racing for one slug hold different row locks and+ * would both pass a plain conflict SELECT (neither sees the other's+ * uncommitted write). The check is therefore additionally serialized on a+ * transaction-scoped advisory lock keyed by the slug itself, released+ * automatically at commit/rollback.+ */+ private static isShareSlugTaken = async (+ tx: LobeChatDatabase,+ slug: string,+ agentId: string,+ ): Promise<boolean> => {+ await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${`agent_share_slug:${slug}`}))`);++ const [conflict] = await tx+ .select({ id: agentShares.id })+ .from(agentShares)+ .where(+ and(sql`${agentShares.shareConfig} ->> 'slug' = ${slug}`, ne(agentShares.agentId, agentId)),+ )+ .limit(1);++ return !!conflict;+ };++ /**+ * Best-effort default for a brand-new share: the visitor url starts out as+ * `/a/<the agent's own profile slug>` instead of a bare UUID. Agent+ * slugs are unique per OWNER while share slugs are global, so a slug another+ * share already holds — or one the share rules reject — simply leaves the+ * seed unset; the owner can still pick any slug in the settings. Never+ * throws: a seed failure must not fail the share creation itself.+ */+ private static seedSlugFromAgent = async (+ tx: LobeChatDatabase,+ share: AgentShareItem,+ agentSlug: string | null,+ ): Promise<AgentShareItem> => {+ const slug = agentSlug?.trim().toLowerCase();+ if (!slug || getShareSlugRejection(slug)) return share;+ if (await AgentShareModel.isShareSlugTaken(tx, slug, share.agentId)) return share;++ const [updated] = await tx+ .update(agentShares)+ .set({+ shareConfig: sql<AgentShareConfig>`COALESCE(${agentShares.shareConfig}, '{}'::jsonb) || ${JSON.stringify({ slug })}::jsonb`,+ })+ .where(eq(agentShares.id, share.id))+ .returning();++ return updated ?? share;+ };+private withOwnedPersonalAgentLock = async <T>(agentId: string,mutation: (tx: LobeChatDatabase, agent: LockedAgentSnapshot) => Promise<T>,@@ -125,7 +197,7 @@ export class AgentShareModel {/** Create a private share by default, or return the existing share for the agent. */create = async (agentId: string, visibility: ShareVisibility = 'private') => {- const share = await this.withOwnedPersonalAgentLock(agentId, async (tx) => {+ const share = await this.withOwnedPersonalAgentLock(agentId, async (tx, agent) => {// One row per agent, forever: `onConflictDoNothing` on `agentId` makes a// re-enable fall back to the SELECT below, returning the existing row// untouched. That is what keeps a share's id and custom slug — i.e. the@@ -137,7 +209,9 @@ export class AgentShareModel {.onConflictDoNothing({ target: agentShares.agentId }).returning();- if (created) return created;+ // Only a freshly minted row gets the profile-slug default; an existing+ // row keeps whatever slug (or none) its owner already chose.+ if (created) return AgentShareModel.seedSlugFromAgent(tx, created, agent.slug);const [existing] = await tx.select()@@ -264,32 +338,13 @@ export class AgentShareModel {});}- // A UUID-shaped slug would be unreachable: `findBySlugOrId` resolves- // UUID-shaped input as a share id before ever trying the slug lookup.- if (!AGENT_SHARE_SLUG_PATTERN.test(slug) || isUuid(slug)) {- throw new TRPCError({ code: 'BAD_REQUEST', message: 'INVALID_SHARE_SLUG' });- }-- if (RESERVED_AGENT_SHARE_SLUGS.includes(slug)) {- throw new TRPCError({ code: 'BAD_REQUEST', message: 'RESERVED_SHARE_SLUG' });+ const rejection = getShareSlugRejection(slug);+ if (rejection) {+ throw new TRPCError({ code: 'BAD_REQUEST', message: rejection });}return this.withOwnedPersonalAgentLock(agentId, async (tx) => {- // Cross-agent uniqueness barrier: released automatically at commit/rollback.- await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${`agent_share_slug:${slug}`}))`);-- const [conflict] = await tx- .select({ id: agentShares.id })- .from(agentShares)- .where(- and(- sql`${agentShares.shareConfig} ->> 'slug' = ${slug}`,- ne(agentShares.agentId, agentId),- ),- )- .limit(1);-- if (conflict) {+ if (await AgentShareModel.isShareSlugTaken(tx, slug, agentId)) {throw new TRPCError({ code: 'CONFLICT', message: 'SHARE_SLUG_TAKEN' });}diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.tsindex acfaa005fb8..d07eea2bd90 100644--- a/packages/locales/src/default/agent.ts+++ b/packages/locales/src/default/agent.ts@@ -404,8 +404,6 @@ export default {'share.settings.link.slugError.tooShort': 'Custom links need at least 3 characters.','share.settings.link.slugHint':'3–64 characters: lowercase letters, numbers and hyphens. Leave it empty to use the generated link.',- 'share.settings.link.slugLabel': 'Custom link',- 'share.settings.link.slugPlaceholder': 'my-agent','share.settings.link.slugSaved': 'Custom link updated','share.settings.link.title': 'Share link','share.settings.link.viewCount': '{{views}} views',@@ -427,6 +425,8 @@ export default {'share.settings.permissions.showModelInfoHint':'Off by default: your model and provider choice stays hidden.','share.settings.permissions.title': 'Permissions',+ 'share.settings.tabs.access': 'Access',+ 'share.settings.tabs.stats': 'Stats','share.settings.title': 'Share Agent','share.settings.usage.conversations': 'Conversations','share.settings.usage.desc': 'What this share has attracted, and what it has cost you.',@@ -443,6 +443,8 @@ export default {'share.settings.tools.apiWritesOwnerData':'Visitors can never write to your memory — this action stays off in shared runs.','share.settings.tools.availableGroup': 'Not granted · {{count}}',+ 'share.settings.tools.apiGrantedCount': '{{granted}} of {{total}} APIs granted',+ 'share.settings.tools.configureApis': 'Choose which APIs visitors can call','share.settings.tools.empty': 'This Agent has no tools that can be granted to visitors.','share.settings.tools.grantedEmpty':'No tools granted yet — visitors get a plain chat. Pick from the list below to grant one.',@@ -485,6 +487,7 @@ 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.topBar.home': 'Go to my LobeHub','share.visitor.topics.empty': 'No conversations yet','share.visitor.topics.new': 'New conversation','share.visitor.topics.title': 'Conversations',diff --git a/packages/locales/src/default/spend.ts b/packages/locales/src/default/spend.tsindex 141d6a3c455..84148363f80 100644--- a/packages/locales/src/default/spend.ts+++ b/packages/locales/src/default/spend.ts@@ -38,6 +38,8 @@ export default {'table.columns.type.enums.imageGeneration': 'Image Generation','table.columns.type.enums.videoGeneration': 'Video Generation','table.columns.type.title': 'Type',+ 'table.agentShareDesc':+ 'Every model call a visitor of this share triggered, billed to your account.','table.desc': 'Details of credit usage for text generation, embedding, image generation, etc.','table.filters.allTypes': 'All types','table.filters.endDate': 'End date',diff --git a/src/app/robots.tsx b/src/app/robots.tsxindex 5d386d8b03f..b0df32977be 100644--- a/src/app/robots.tsx+++ b/src/app/robots.tsx@@ -24,9 +24,10 @@ const robots = (): MetadataRoute.Robots => {},{allow: ['/'],- // `/agent/*` also hosts Agent Share visitor pages (`/agent/:slugOrId`):- // link-visible, creator-owned content that must never be indexed.- disallow: ['/api/*', '/signin', '/signup', '/knowledge/*', '/share/*', '/agent/*'],+ // `/a/*` is the Agent Share visitor page: link-visible, creator-owned+ // content that must never be indexed. `/agent/*` is the creator's own+ // agent pages (and still forwards legacy share links).+ disallow: ['/api/*', '/signin', '/signup', '/knowledge/*', '/share/*', '/agent/*', '/a/*'],userAgent: '*',},],diff --git a/src/business/client/features/AgentShareSpendDetail.tsx b/src/business/client/features/AgentShareSpendDetail.tsxnew file mode 100644index 00000000000..8bdd01bb694--- /dev/null+++ b/src/business/client/features/AgentShareSpendDetail.tsx@@ -0,0 +1,14 @@+export interface AgentShareSpendDetailProps {+ agentId: string;+}++/**+ * Business slot for the per-call spend table under the share stats tab.+ *+ * The default renders nothing: a deployment that does not meter share spend+ * has nothing to list. Deployments that do override the slot with their own+ * per-call table.+ */+const AgentShareSpendDetail = (_props: AgentShareSpendDetailProps) => null;++export default AgentShareSpendDetail;diff --git a/src/components/Skeleton/AgentShare.tsx b/src/components/Skeleton/AgentShare.tsxindex 0754d8f707a..c89d3908ec9 100644--- a/src/components/Skeleton/AgentShare.tsx+++ b/src/components/Skeleton/AgentShare.tsx@@ -18,6 +18,9 @@ const styles = createStaticStyles(({ css }) => ({border-radius: ${cssVar.borderRadiusLG};background: ${cssVar.colorFillQuaternary};`,+ tabs: css`+ border-block-end: 1px solid ${cssVar.colorBorder};+ `,}));/** Breadcrumb on the left, the profile tab switcher centred — same as `NavHeader` on the page. */@@ -75,10 +78,12 @@ const SectionSkeleton = ({);/**- * Body of the share settings page: the warning notice, then the outlined- * sections (`Section` in `AgentShareSettings/SectionLayout.tsx`) — link,- * usage stats, permissions, limits. Reused by the page's own data-loading- * state so the layout does not jump between route load and share fetch.+ * Body of the share settings page: the warning notice, the link card, the+ * access/stats tab strip, then the outlined sections of the default (access)+ * tab — permissions and limits (`Section` in+ * `AgentShareSettings/SectionLayout.tsx`). Reused by the page's own+ * data-loading state so the layout does not jump between route load and share+ * fetch.*/export const AgentShareSettingsBodySkeleton = () => (<Flexbox aria-busy gap={16} paddingBlock={16}>@@ -99,16 +104,11 @@ export const AgentShareSettingsBodySkeleton = () => (<SettingRowSkeleton control={'switch'} index={0} /><SkeletonBar height={36} width={'100%'} /></SectionSkeleton>- <SectionSkeleton descWidth={200} titleWidth={72}>- <Flexbox horizontal gap={16}>- {Array.from({ length: 3 }).map((_, index) => (- <Flexbox flex={1} gap={8} key={index}>- <SkeletonBar height={12} width={64} />- <SkeletonBar height={24} width={48 + index * 12} />- </Flexbox>- ))}- </Flexbox>- </SectionSkeleton>+ {/* Mirrors `ShareTabs`: two underline tabs on a hairline. */}+ <Flexbox horizontal className={styles.tabs} gap={24} paddingBlock={10}>+ <SkeletonBar height={14} width={64} />+ <SkeletonBar height={14} width={64} />+ </Flexbox><SectionSkeleton titleWidth={104}><SettingRowSkeleton control={'switch'} index={1} /><SettingRowSkeleton control={'switch'} index={2} />diff --git a/src/components/Skeleton/AgentShareVisitor.tsx b/src/components/Skeleton/AgentShareVisitor.tsxnew file mode 100644index 00000000000..37738bb4f04--- /dev/null+++ b/src/components/Skeleton/AgentShareVisitor.tsx@@ -0,0 +1,95 @@+'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/components/Skeleton/Conversation/List.tsx b/src/components/Skeleton/Conversation/List.tsxindex 19e0532a1d2..6bc8053e0c6 100644--- a/src/components/Skeleton/Conversation/List.tsx+++ b/src/components/Skeleton/Conversation/List.tsx@@ -3,8 +3,8 @@import { Flexbox } from '@lobehub/ui';import { Skeleton } from '@lobehub/ui/base-ui';-import { ArticleSkeleton } from '@/components/Skeleton';-+/** Avoid importing the skeleton barrel from a component it re-exports. */+import ArticleSkeleton from '../Article';import ConversationSkeletonContainer from './Container';const ConversationListSkeleton = () => (diff --git a/src/features/AgentRoute/AgentRouteSwitch.tsx b/src/features/AgentRoute/AgentRouteSwitch.tsxdeleted file mode 100644index db790053a67..00000000000--- a/src/features/AgentRoute/AgentRouteSwitch.tsx+++ /dev/null@@ -1,55 +0,0 @@-'use client';--import { memo, type ReactElement, type ReactNode } from 'react';-import { Navigate, useParams } from 'react-router';--import { resolveAgentRouteBranch, useAgentRouteResolution } from './useAgentRouteResolution';--interface AgentRouteSwitchProps {- /** Shown while a slug is still being resolved, to avoid a not-found flash. */- fallback?: ReactNode;- /** The creator's own agent shell (layout + nested routes). */- ownElement: ReactElement;- /**- * Where the creator lands when they open their OWN share link. Defaults to- * the agent's share settings; a platform without that page (mobile) points- * at the agent itself.- */- ownShareRedirect?: (agentId: string) => string;- /** The agent-share visitor surface. */- shareElement: ReactElement;-}--const defaultOwnShareRedirect = (agentId: string) => `/agent/${agentId}/share`;--/**- * `/agent/:slugOrId` serves two surfaces: the creator's own agent (by id or by- * agent slug) and the agent-share visitor page (by share slug or share id).- * React Router cannot tell them apart from the pattern alone, so the branch is- * decided here, after the param is resolved server-side.- *- * A not-found param renders the own-agent shell, which already owns the agent- * not-found card — the visitor page has no better story for an unknown link.- * The share branch does not render an `Outlet`, so the nested creator routes- * (`/agent/:aid/docs` …) stay unmounted for a visitor.- */-const AgentRouteSwitch = memo<AgentRouteSwitchProps>(- ({ fallback, ownElement, ownShareRedirect = defaultOwnShareRedirect, shareElement }) => {- const { aid } = useParams<{ aid?: string }>();- const { error, isLoading, kind, resolvedAgentId } = useAgentRouteResolution(aid);- const branch = resolveAgentRouteBranch({ error, isLoading, kind });-- if (branch === 'loading') return <>{fallback ?? null}</>;-- // The creator is never a visitor of their own share: `/agent/<share-slug>`- // is what they copied from the share settings, so send them back there.- if (branch === 'ownShare' && resolvedAgentId)- return <Navigate replace to={ownShareRedirect(resolvedAgentId)} />;-- return branch === 'share' ? shareElement : ownElement;- },-);--AgentRouteSwitch.displayName = 'AgentRouteSwitch';--export default AgentRouteSwitch;diff --git a/src/features/AgentRoute/useAgentRouteResolution.test.ts b/src/features/AgentRoute/useAgentRouteResolution.test.tsdeleted file mode 100644index cd9b1f30aa5..00000000000--- a/src/features/AgentRoute/useAgentRouteResolution.test.ts+++ /dev/null@@ -1,68 +0,0 @@-import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';-import { describe, expect, it } from 'vitest';--import { needsAgentRouteLookup, resolveAgentRouteBranch } from './useAgentRouteResolution';--describe('needsAgentRouteLookup', () => {- it('skips the lookup for id-shaped params', () => {- expect(needsAgentRouteLookup('agt_123')).toBe(false);- expect(needsAgentRouteLookup('agent_123')).toBe(false);- });-- it('skips the lookup for builtin slugs, which the store already knows', () => {- for (const slug of Object.values(BUILTIN_AGENT_SLUGS)) {- expect([slug, needsAgentRouteLookup(slug)]).toEqual([slug, false]);- }- });-- it('looks up a user-chosen slug, which may be an agent or a share', () => {- expect(needsAgentRouteLookup('my-bot')).toBe(true);- });-- it('skips the lookup when there is no param at all', () => {- expect(needsAgentRouteLookup()).toBe(false);- expect(needsAgentRouteLookup('')).toBe(false);- });-});--describe('resolveAgentRouteBranch', () => {- it('waits instead of guessing a surface while the slug resolves', () => {- expect(resolveAgentRouteBranch({ isLoading: true })).toBe('loading');- // Even with a stale kind in hand, an in-flight resolution wins.- expect(resolveAgentRouteBranch({ isLoading: true, kind: 'share' })).toBe('loading');- });-- it('renders the creator surface for an own agent', () => {- expect(resolveAgentRouteBranch({ isLoading: false, kind: 'own' })).toBe('own');- });-- it('renders the visitor surface for a share', () => {- expect(resolveAgentRouteBranch({ isLoading: false, kind: 'share' })).toBe('share');- });-- it("redirects the creator's own share link instead of rendering the visitor surface", () => {- expect(resolveAgentRouteBranch({ isLoading: false, kind: 'ownShare' })).toBe('ownShare');- });-- it('falls back to the creator surface, which owns the not-found card', () => {- expect(resolveAgentRouteBranch({ isLoading: false, kind: 'notFound' })).toBe('own');- expect(resolveAgentRouteBranch({ isLoading: false })).toBe('own');- });-- it('routes an UNAUTHORIZED lookup to the share surface, which owns the sign-in CTA', () => {- const unauthorized = { data: { code: 'UNAUTHORIZED' } };-- expect(resolveAgentRouteBranch({ error: unauthorized, isLoading: false })).toBe('share');- // Even with a stale/unset kind, an UNAUTHORIZED error wins over the fallback.- expect(- resolveAgentRouteBranch({ error: unauthorized, isLoading: false, kind: 'notFound' }),- ).toBe('share');- });-- it('keeps the creator fallback for a non-401 lookup failure', () => {- const notFound = { data: { code: 'NOT_FOUND' } };-- expect(resolveAgentRouteBranch({ error: notFound, isLoading: false })).toBe('own');- expect(resolveAgentRouteBranch({ error: new Error('network'), isLoading: false })).toBe('own');- });-});diff --git a/src/features/AgentRoute/useAgentRouteResolution.ts b/src/features/AgentRoute/useAgentRouteResolution.tsdeleted file mode 100644index f7fb19e97f6..00000000000--- a/src/features/AgentRoute/useAgentRouteResolution.ts+++ /dev/null@@ -1,93 +0,0 @@-import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';-import useSWR from 'swr';--import type { AgentRouteResolution } from '@/server/routers/lambda/agent';-import { agentService } from '@/services/agent';-import { isTrpcErrorCode } from '@/utils/trpcError';--type AgentRouteResolutionKind = AgentRouteResolution['kind'];--const builtinAgentSlugs = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));--/**- * Every generated agent id carries an underscore (`agt_…`, `agent_…`) and no- * generated slug does (`randomSlug` joins words with hyphens, and rename rejects- * underscores). So the absence of one is what tells a slug route from an id- * route — and a wrong guess only costs a lookup that resolves to nothing.- */-export const looksLikeSlug = (routeAgentId?: string) =>- !!routeAgentId && !routeAgentId.includes('_');--/** Builtin agents are addressed by a fixed slug that the store already knows. */-export const isBuiltinAgentSlug = (routeAgentId?: string) =>- !!routeAgentId && builtinAgentSlugs.has(routeAgentId);--/**- * A param only needs a server round trip when its shape leaves the answer open:- * ids and builtin slugs are decided locally.- */-export const needsAgentRouteLookup = (routeAgentId?: string) =>- !isBuiltinAgentSlug(routeAgentId) && looksLikeSlug(routeAgentId);--export type AgentRouteBranch = 'loading' | 'own' | 'ownShare' | 'share';--/**- * Which surface `/agent/:slugOrId` renders for a given resolution state.- *- * A not-found param falls back to the creator surface, which already owns the- * agent not-found card — the visitor page has no better story for a dead link.- *- * An UNAUTHORIZED lookup is different: `resolveAgentRoute` is auth-gated, so- * an anonymous visitor on a share URL fails the lookup itself, before `kind`- * is ever known. Falling back to 'own' would show the creator's not-found- * shell instead of a sign-in prompt, so this routes straight to 'share' and- * lets `AgentShareVisitor`'s own `getSharedAgent` call (and its `signIn`- * branch in `resolveShareAccessState`) render the CTA. Any other error keeps- * the existing not-found fallback.- */-export const resolveAgentRouteBranch = ({- error,- isLoading,- kind,-}: {- error?: unknown;- isLoading: boolean;- kind?: AgentRouteResolutionKind;-}): AgentRouteBranch => {- if (isLoading) return 'loading';-- if (isTrpcErrorCode(error, 'UNAUTHORIZED')) return 'share';-- if (kind === 'share' || kind === 'ownShare') return kind;-- return 'own';-};--/**- * Resolve a `/agent/:slugOrId` param, which serves two surfaces: the creator's- * own agent and the agent-share visitor page.- *- * Id-shaped params and builtin slugs are decided locally, so an ordinary- * `/agent/<id>` route never pays for a request. Only a user-chosen slug asks- * the server, and that answer is shared with `useResolvedAgentRouteId` through- * the same SWR key, so the switch and the layout resolve it exactly once.- */-export const useAgentRouteResolution = (routeAgentId?: string) => {- const needsLookup = needsAgentRouteLookup(routeAgentId);-- const { data, error, isLoading } = useSWR(- needsLookup ? ['agent-route', routeAgentId] : null,- () => agentService.resolveAgentRoute(routeAgentId!),- { revalidateOnFocus: false },- );-- return {- /** The lookup's failure, if any — see `resolveAgentRouteBranch` for how UNAUTHORIZED is handled. */- error: needsLookup ? error : undefined,- /** True only while a slug lookup is in flight, i.e. the kind is unknown yet. */- isLoading: needsLookup && isLoading,- kind: needsLookup ? data?.kind : ('own' as const),- /** The id behind a user-chosen agent slug (or the caller's own share slug), once known. */- resolvedAgentId: data?.kind === 'own' || data?.kind === 'ownShare' ? data.agentId : undefined,- };-};diff --git a/src/features/AgentRoute/useAgentShareVisitorRoute.test.ts b/src/features/AgentRoute/useAgentShareVisitorRoute.test.tsdeleted file mode 100644index 9cbd0dcc4f4..00000000000--- a/src/features/AgentRoute/useAgentShareVisitorRoute.test.ts+++ /dev/null@@ -1,30 +0,0 @@-import { describe, expect, it } from 'vitest';--import { resolveAgentRouteParam } from './useAgentShareVisitorRoute';--describe('resolveAgentRouteParam', () => {- it('reads the aid of a personal agent route', () => {- expect(resolveAgentRouteParam('/agent/my-agent', null)).toBe('my-agent');- });-- it('reads the aid of the workspace mirror', () => {- expect(resolveAgentRouteParam('/acme/agent/my-agent', 'acme')).toBe('my-agent');- });-- it('ignores nested creator routes, which never render the visitor surface', () => {- expect(resolveAgentRouteParam('/agent/my-agent/docs', null)).toBeUndefined();- expect(resolveAgentRouteParam('/acme/agent/my-agent/docs', 'acme')).toBeUndefined();- });-- it('does not mistake a sibling three-segment route for the workspace mirror', () => {- // `/community/agent/:slug` is a discover detail page, not an agent route.- expect(resolveAgentRouteParam('/community/agent/some-slug', null)).toBeUndefined();- expect(resolveAgentRouteParam('/community/agent/some-slug', 'acme')).toBeUndefined();- });-- it('returns undefined for unrelated routes', () => {- expect(resolveAgentRouteParam('/', null)).toBeUndefined();- expect(resolveAgentRouteParam('/agent', null)).toBeUndefined();- expect(resolveAgentRouteParam('/settings/common', null)).toBeUndefined();- });-});diff --git a/src/features/AgentRoute/useAgentShareVisitorRoute.ts b/src/features/AgentRoute/useAgentShareVisitorRoute.tsdeleted file mode 100644index 2a0874b831a..00000000000--- a/src/features/AgentRoute/useAgentShareVisitorRoute.ts+++ /dev/null@@ -1,54 +0,0 @@-'use client';--import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';-import { useActiveLocation } from '@/hooks/useActiveLocation';--import { resolveAgentRouteBranch, useAgentRouteResolution } from './useAgentRouteResolution';--/**- * The `aid` of `/agent/:aid` — and of its workspace mirror- * `/:workspaceSlug/agent/:aid` — read straight from the pathname, because the- * main layout sits above that route and therefore has no `useParams` access to- * it.- *- * Only the exact two-segment route counts: the nested creator routes- * (`/agent/:aid/docs` …) never render the visitor surface. The workspace prefix- * is stripped only when it equals the active slug, so sibling routes such as- * `/community/agent/:slug` are not mistaken for an agent route — the same rule- * `resolveNavPanelKey` uses.- */-export const resolveAgentRouteParam = (- pathname: string,- activeWorkspaceSlug: string | null,-): string | undefined => {- const segments = pathname.split('/').filter(Boolean);- const routeSegments =- !!activeWorkspaceSlug && segments[0] === activeWorkspaceSlug ? segments.slice(1) : segments;-- if (routeSegments.length !== 2 || routeSegments[0] !== 'agent') return undefined;-- return routeSegments[1];-};--/**- * Whether the current route renders the agent-share visitor surface, i.e. the- * `share` branch of `AgentRouteSwitch`.- *- * A visitor is not signed into the creator's workspace, so the main nav has no- * data to show and would sit on a grey skeleton forever — the layout unmounts- * it entirely for this branch. The branch is derived from the very same SWR key- * as the switch itself, so this costs no extra request.- *- * While a slug lookup is still in flight the answer is `false`: nearly all- * `/agent/:aid` traffic is the creator's own agent, and keeping the nav mounted- * until proven otherwise avoids a flash on the common path.- */-export const useIsAgentShareVisitorRoute = (): boolean => {- const { pathname } = useActiveLocation();- const activeWorkspaceSlug = useActiveWorkspaceSlug();- const { error, isLoading, kind } = useAgentRouteResolution(- resolveAgentRouteParam(pathname, activeWorkspaceSlug),- );-- return resolveAgentRouteBranch({ error, isLoading, kind }) === 'share';-};diff --git a/src/features/AgentRoute/useResolvedAgentRouteId.ts b/src/features/AgentRoute/useResolvedAgentRouteId.tsindex 283a9716d60..438fa952752 100644--- a/src/features/AgentRoute/useResolvedAgentRouteId.ts+++ b/src/features/AgentRoute/useResolvedAgentRouteId.ts@@ -1,13 +1,19 @@import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';+import useSWR from 'swr';+import { agentService } from '@/services/agent';import { useAgentStore } from '@/store/agent';import { builtinAgentSelectors } from '@/store/agent/selectors';-import {- isBuiltinAgentSlug,- looksLikeSlug,- useAgentRouteResolution,-} from './useAgentRouteResolution';+const builtinAgentSlugs = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));++/**+ * Every generated agent id carries an underscore (`agt_…`, `agent_…`) and no+ * generated slug does (`randomSlug` joins words with hyphens, and rename rejects+ * underscores). So the absence of one is what tells a slug route from an id+ * route — and a wrong guess only costs a lookup that resolves to null.+ */+const looksLikeSlug = (routeAgentId?: string) => !!routeAgentId && !routeAgentId.includes('_');/*** Keep the inbox route valid while its persisted agent ID is still loading.@@ -17,18 +23,22 @@ export const resolveInboxAgentRouteId = (inboxAgentId?: string) =>inboxAgentId ?? BUILTIN_AGENT_SLUGS.inbox;export const useResolvedAgentRouteId = (routeAgentId?: string) => {- const isBuiltinSlug = isBuiltinAgentSlug(routeAgentId);+ const isBuiltinSlug = !!routeAgentId && builtinAgentSlugs.has(routeAgentId);const builtinAgentId = useAgentStore(builtinAgentSelectors.getBuiltinAgentId(isBuiltinSlug ? routeAgentId! : ''),);// A user-chosen slug needs a server lookup; builtin slugs already resolve from- // the store. The lookup is shared with `AgentRouteSwitch`, which asks the same- // question one level up in the tree.+ // the store. Gated on the shape check so an ordinary `/agent/<id>` route never+ // pays for a request.const isCustomSlug = !isBuiltinSlug && looksLikeSlug(routeAgentId);- const { resolvedAgentId: slugAgentId } = useAgentRouteResolution(routeAgentId);+ const { data: slugAgentId } = useSWR(+ isCustomSlug ? ['agent-id-by-slug', routeAgentId] : null,+ () => agentService.resolveAgentIdBySlug(routeAgentId!),+ { revalidateOnFocus: false },+ );- const resolvedAgentId = isBuiltinSlug ? builtinAgentId : slugAgentId;+ const resolvedAgentId = isBuiltinSlug ? builtinAgentId : (slugAgentId ?? undefined);return {agentId: resolvedAgentId || routeAgentId,diff --git a/src/features/AgentShareSettings/Content.tsx b/src/features/AgentShareSettings/Content.tsxindex f1ebe233744..1193d1ce7c5 100644--- a/src/features/AgentShareSettings/Content.tsx+++ b/src/features/AgentShareSettings/Content.tsx@@ -5,16 +5,29 @@ 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;@@ -24,12 +37,28 @@ interface AgentShareSettingsContentProps {* 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) => {@@ -48,13 +77,17 @@ const AgentShareSettingsContent = memo<AgentShareSettingsContentProps>(({ agentIreturn (<Flexbox gap={16} paddingBlock={16}>- {/* Sharing grants real execution on the creator's account — say so plainly. */}- <Alert- showIcon- description={t('share.settings.notice.desc')}- title={t('share.settings.notice.title')}- type={'warning'}- />+ {/* 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()} />) : (@@ -73,21 +106,35 @@ const AgentShareSettingsContent = memo<AgentShareSettingsContentProps>(({ agentIexisting link holders regain access. */}{share && (<>- <UsageSection- agentId={agentId}- monthlySpendLimit={share.shareConfig.monthlySpendLimit}- />- <PermissionsSection shareConfig={share.shareConfig} onChange={handleConfigChange} />- <ToolsSection- agentId={agentId}- shareConfig={share.shareConfig}- onChange={handleConfigChange}- />- <LimitsSection- agentId={agentId}- shareConfig={share.shareConfig}- onChange={handleConfigChange}- />+ <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} />+ </>+ )}</>)}</>diff --git a/src/features/AgentShareSettings/LinkSection.tsx b/src/features/AgentShareSettings/LinkSection.tsxindex 3c6ae3cf978..bc0e5293792 100644--- a/src/features/AgentShareSettings/LinkSection.tsx+++ b/src/features/AgentShareSettings/LinkSection.tsx@@ -6,6 +6,7 @@ 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';@@ -173,40 +174,45 @@ const LinkSection = memo<LinkSectionProps>((props) => {>{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 readOnly style={{ flex: 1 }} value={shareUrl} variant={'filled'} />- <Button icon={CopyIcon} type={'primary'} onClick={handleCopy}>- {t('share.settings.link.copy')}- </Button>- </Flexbox>-- <Flexbox gap={4}>- <Text fontSize={12} type={'secondary'}>- {t('share.settings.link.slugLabel')}- </Text>- <Flexbox horizontal align={'center'} gap={8}>- <Input- disabled={savingSlug}- placeholder={t('share.settings.link.slugPlaceholder')}- prefix={`${appOrigin}/agent/`}- status={slugError ? 'error' : undefined}- style={{ flex: 1 }}- value={slugDraft}- variant={'filled'}- onPressEnter={handleSaveSlug}- onChange={(e) => {- setSlugDraft(e.target.value);- setSlugError('');- }}- />- <Button disabled={!slugDirty} loading={savingSlug} onClick={handleSaveSlug}>+ <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>- </Flexbox>- <Text fontSize={12} type={slugError ? 'danger' : 'secondary'}>- {slugError || t('share.settings.link.slugHint')}- </Text>+ ) : (+ <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) })}diff --git a/src/features/AgentShareSettings/ShareTabs.tsx b/src/features/AgentShareSettings/ShareTabs.tsxnew file mode 100644index 00000000000..388b56f1cae--- /dev/null+++ b/src/features/AgentShareSettings/ShareTabs.tsx@@ -0,0 +1,57 @@+'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.tsxindex 3488608da8a..cb902806df7 100644--- a/src/features/AgentShareSettings/ToolRow.tsx+++ b/src/features/AgentShareSettings/ToolRow.tsx@@ -1,11 +1,11 @@'use client';-import { Flexbox, Icon, Tooltip } from '@lobehub/ui';-import { Checkbox, Text } from '@lobehub/ui/base-ui';-import { cssVar } from 'antd-style';+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 { ChevronDown, ChevronRight } from 'lucide-react';-import { memo, useState } from 'react';+import { SlidersHorizontalIcon } from 'lucide-react';+import { Fragment, memo, useState } from 'react';import { useTranslation } from 'react-i18next';import PluginTag from '@/features/ProfileEditor/PluginTag';@@ -16,11 +16,37 @@ 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;@@ -33,18 +59,29 @@ interface ToolRowProps {* 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 an expand chevron- * — shown only when the tool has more than one visitor-grantable API — that- * reveals a per-API checkbox list underneath.+ * {@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 expands rather than- * offering stale/guessed entries.+ * 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 [expanded, setExpanded] = useState(false);+ const [open, setOpen] = useState(false);const builtinManifest = useToolStore((s) => s.builtinTools.find((tool) => tool.identifier === toolId)?.manifest,@@ -52,6 +89,7 @@ const ToolRow = memo<ToolRowProps>(({ agentId, toolId, selected, shareConfig, on);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,@@ -66,9 +104,28 @@ const ToolRow = memo<ToolRowProps>(({ agentId, toolId, selected, shareConfig, on(api) => getShareApiAvailability(toolId, api.name, api.humanIntervention) === 'available',).map((api) => api.name);- const canExpand = !blocked && grantableApiNames.length > 1;+ 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) => ({@@ -82,52 +139,38 @@ const ToolRow = memo<ToolRowProps>(({ agentId, toolId, selected, shareConfig, on}));};- return (- <Flexbox gap={2}>- <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>- {canExpand && (- <Icon- icon={expanded ? ChevronDown : ChevronRight}- size={14}- style={{ color: cssVar.colorTextTertiary, cursor: 'pointer' }}- onClick={() => setExpanded((prev) => !prev)}- />- )}+ 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>- {expanded && canExpand && (- <Flexbox gap={4} style={{ paddingInlineStart: 24 }}>- {apis.map((api) => {- const apiAvailability = getShareApiAvailability(- toolId,- api.name,- api.humanIntervention,- );- const apiBlocked = apiAvailability !== 'available';- const apiSelected = grant === 'all' || (grant instanceof Set && grant.has(api.name));-- return (+ <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- key={api.name}+ placement={'left'}title={apiAvailability === 'writesOwnerData'? t('share.settings.tools.apiWritesOwnerData')@@ -136,24 +179,82 @@ const ToolRow = memo<ToolRowProps>(({ agentId, toolId, selected, shareConfig, on: undefined}>- <Checkbox- checked={!apiBlocked && apiSelected}- disabled={blocked || apiBlocked}- onChange={() => toggleApi(api.name)}- >- <Flexbox gap={0}>- <Text fontSize={12}>{api.name}</Text>- {api.description && (- <Text ellipsis={{ rows: 1, tooltip: true }} fontSize={11} type={'secondary'}>- {api.description}+ <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>- )}- </Flexbox>- </Checkbox>+ {api.description && (+ <Text ellipsis={{ rows: 2 }} fontSize={12} type={'secondary'}>+ {api.description}+ </Text>+ )}+ </Flexbox>+ </Checkbox>+ </Flexbox></Tooltip>- );- })}- </Flexbox>+ </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>);diff --git a/src/features/AgentShareSettings/ToolsSection.tsx b/src/features/AgentShareSettings/ToolsSection.tsxindex 9c99b4eb8e3..b1a94d5447b 100644--- a/src/features/AgentShareSettings/ToolsSection.tsx+++ b/src/features/AgentShareSettings/ToolsSection.tsx@@ -36,22 +36,23 @@ const ToolsSection = memo<ToolsSectionProps>(({ agentId, onChange, shareConfig }const { t } = useTranslation('agent');const agentConfig = useAgentStore(agentSelectors.getAgentConfigById(agentId), isEqual);- const candidateToolIds = getShareToolCandidateIds(getActivePluginIds(agentConfig?.plugins));+ // 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) &&- getShareToolAvailability(toolId, { allowReadMemory: shareConfig.allowReadMemory }) ===- 'available',- );- // Includes tools the gate always refuses: they still render below as- // disabled chips (so the owner learns why a configured tool cannot be- // shared), and the group's count must match the chips actually rendered in- // it — a smaller "grantable only" count reads as a rendering bug.+ const enabledIds = candidateToolIds.filter((toolId) => selectedToolIds.includes(toolId));const availableIds = candidateToolIds.filter((toolId) => !enabledIds.includes(toolId));const renderTool = (toolId: string, selected: boolean) => (diff --git a/src/features/AgentShareSettings/shareLink.test.ts b/src/features/AgentShareSettings/shareLink.test.tsindex 853cf8a48c0..1ff99eff3ec 100644--- a/src/features/AgentShareSettings/shareLink.test.ts+++ b/src/features/AgentShareSettings/shareLink.test.ts@@ -39,8 +39,9 @@ describe('validateAgentShareSlug', () => {expect(validateAgentShareSlug('share')).toBe('reserved');});- // Shares live at `/agent/<slug>`, where the creator's own agents always win- // the lookup, so a share on a builtin slug would be unreachable forever.+ // 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']);@@ -53,16 +54,16 @@ describe('buildAgentShareUrl', () => {it('prefers the custom slug', () => {expect(buildAgentShareUrl({ origin, shareId: 'share-id', slug: 'my-bot' })).toBe(- 'https://app.lobehub.com/agent/my-bot',+ '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/agent/share-id',+ 'https://app.lobehub.com/a/share-id',);expect(buildAgentShareUrl({ origin, shareId: 'share-id', slug: '' })).toBe(- 'https://app.lobehub.com/agent/share-id',+ 'https://app.lobehub.com/a/share-id',);});});diff --git a/src/features/AgentShareSettings/shareLink.ts b/src/features/AgentShareSettings/shareLink.tsindex 57a6002cc07..54956f648b1 100644--- a/src/features/AgentShareSettings/shareLink.ts+++ b/src/features/AgentShareSettings/shareLink.ts@@ -1,5 +1,7 @@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@@ -43,4 +45,4 @@ export const buildAgentShareUrl = ({origin: string;shareId: string;slug?: string;-}): string => `${origin}/agent/${slug || shareId}`;+}): string => `${origin}${buildAgentShareVisitorPath(slug || shareId)}`;diff --git a/src/features/AgentShareSettings/toolVisitorAvailability.test.ts b/src/features/AgentShareSettings/toolVisitorAvailability.test.tsindex 99ed457bece..fac3f768209 100644--- a/src/features/AgentShareSettings/toolVisitorAvailability.test.ts+++ b/src/features/AgentShareSettings/toolVisitorAvailability.test.ts@@ -10,6 +10,7 @@ import {getVisitorVisibleGrantedToolIds,runtimeManagedShareCandidateToolIds,setShareToolGrant,+ sortBlockedLast,toggleShareToolApi,toggleShareToolsetGrant,} from './toolVisitorAvailability';@@ -47,6 +48,34 @@ describe('runtimeManagedShareCandidateToolIds', () => {});});+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(diff --git a/src/features/AgentShareSettings/toolVisitorAvailability.ts b/src/features/AgentShareSettings/toolVisitorAvailability.tsindex 64b5676915d..c1a3f9d0e5f 100644--- a/src/features/AgentShareSettings/toolVisitorAvailability.ts+++ b/src/features/AgentShareSettings/toolVisitorAvailability.ts@@ -238,3 +238,22 @@ export const runtimeManagedShareCandidateToolIds: string[] = runtimeManagedToolI*/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/useShareSettingsTab.test.ts b/src/features/AgentShareSettings/useShareSettingsTab.test.tsnew file mode 100644index 00000000000..827ad37cbf0--- /dev/null+++ b/src/features/AgentShareSettings/useShareSettingsTab.test.ts@@ -0,0 +1,16 @@+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.tsnew file mode 100644index 00000000000..a983cafb1e3--- /dev/null+++ b/src/features/AgentShareSettings/useShareSettingsTab.ts@@ -0,0 +1,41 @@+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/AgentShareVisitor/LegacyRedirect.tsx b/src/features/AgentShareVisitor/LegacyRedirect.tsxdeleted file mode 100644index 8ad6c37275c..00000000000--- a/src/features/AgentShareVisitor/LegacyRedirect.tsx+++ /dev/null@@ -1,21 +0,0 @@-'use client';--import { memo } from 'react';-import { Navigate, useLocation, useParams } from 'react-router';--/**- * The agent-share visitor surface moved from `/share/agent/:slugOrId` to- * `/agent/:slugOrId`. Links handed out before the move are permanent, so the- * old pattern stays registered and forwards in-app navigations; the edge- * middleware issues the equivalent 301 for cold loads.- */-const AgentShareLegacyRedirect = memo(() => {- const { slugOrId } = useParams<{ slugOrId: string }>();- const { hash, search } = useLocation();-- return <Navigate replace to={`/agent/${slugOrId ?? ''}${search}${hash}`} />;-});--AgentShareLegacyRedirect.displayName = 'AgentShareLegacyRedirect';--export default AgentShareLegacyRedirect;diff --git a/src/features/AgentShareVisitor/Page.tsx b/src/features/AgentShareVisitor/Page.tsxindex 97345830c8a..ee683dec36b 100644--- a/src/features/AgentShareVisitor/Page.tsx+++ b/src/features/AgentShareVisitor/Page.tsx@@ -1,65 +1,100 @@'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, useState } from 'react';+import { memo, type PropsWithChildren, useState } from 'react';import { useTranslation } from 'react-i18next';-import { useNavigate, useParams } from 'react-router';+import { Navigate, useNavigate, useParams } from 'react-router';import AsyncError from '@/components/AsyncError';-import CircleLoading from '@/components/Loading/CircleLoading';+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;/**- * Visitor landing page of an agent share (`/agent/:slugOrId`): 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.+ * 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.*- * The share surface shares its route with the creator's own agent page, so the- * param is the agent route's `aid`; `AgentRouteSwitch` decides which of the two- * a given value belongs to.+ * 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 { aid: slugOrId } = useParams<{ aid: string }>();+ const { slugOrId } = useParams<{ slugOrId: string }>();const navigate = useNavigate();const isMobile = useIsMobile();+ const RouteSkeleton = useRouteSkeleton();const [drawerOpen, setDrawerOpen] = useState(false);const { data, error, isLoading, mutate } = useSharedAgent(slugOrId);- if (isLoading && !data) return <CircleLoading />;+ /**+ * 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 = `/signin?callbackUrl=${encodeURIComponent(`/agent/${slugOrId ?? ''}`)}`;+ const signInUrl = buildAgentShareSignInUrl(slugOrId ?? '');return (- <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 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>);}@@ -69,31 +104,39 @@ const AgentShareVisitorPage = memo(() => {: t(SHARE_ACCESS_ERROR_KEYS[state] as 'share.visitor.access.notFound');return (- <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 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 (- <Flexbox horizontal flex={1} height={'100%'} style={{ overflow: 'hidden' }} width={'100%'}>+ <VisitorShell horizontal slugOrId={slugOrId}>{!isMobile && (<Flexboxstyle={{ borderInlineEnd: `1px solid ${cssVar.colorBorderSecondary}` }}@@ -118,7 +161,9 @@ const AgentShareVisitorPage = memo(() => {/>)}<Avatar- avatar={data.agentMeta.avatar ?? undefined}+ // 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}/>@@ -164,7 +209,7 @@ const AgentShareVisitorPage = memo(() => {/></Drawer>)}- </Flexbox>+ </VisitorShell>);});diff --git a/src/features/AgentShareVisitor/VisitorComposer.tsx b/src/features/AgentShareVisitor/VisitorComposer.tsxindex 823ff78a1e6..05c070cc753 100644--- a/src/features/AgentShareVisitor/VisitorComposer.tsx+++ b/src/features/AgentShareVisitor/VisitorComposer.tsx@@ -1,23 +1,64 @@'use client';import { SHARE_VISITOR_PROMPT_MAX_LENGTH } from '@lobechat/const';-import { Flexbox, TextArea } from '@lobehub/ui';-import { ActionIcon, Text } from '@lobehub/ui/base-ui';-import { cssVar } from 'antd-style';-import { CircleStop, SendHorizonal } from 'lucide-react';-import { memo, useEffect, useState } from 'react';+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 { useIMECompositionEvent } from '@/hooks/useIMECompositionEvent';+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 { shouldSubmitOnEnter } from './composerEnterGuard';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;/**@@ -33,19 +74,26 @@ interface VisitorComposerProps {}/**- * Lean visitor composer for shared agents. Intentionally NOT the owner- * composer graph: no uploads (v1 rejects them server-side anyway), no- * mentions, no model switcher, no device targets — just text in,- * gateway-streamed answer out.+ * 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 [value, setValue] = useState('');const [errorKey, setErrorKey] = useState<string>();const [sending, setSending] = useState(false);const { stopError, stopping, stopSharedRun } = useShareRunStop(shareId, agentId, topicId);- const { compositionProps, isComposingRef } = useIMECompositionEvent();const isStreaming = useChatStore(// messageMapKey ignores agentShareId — the running check keys off the@@ -72,13 +120,46 @@ const VisitorComposer = memo<VisitorComposerProps>(blockedKey ?? (errorKey && isTerminalVisitorError(errorKey) ? errorKey : undefined);const displayedErrorKey = blocked ?? errorKey;- const send = async () => {- const message = value.trim();- if (!message || busy || blocked) return;+ // `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);- setValue('');+ clearContent();try {const result = await sendVisitorMessage({ agentId, message, shareId, topicId });if (result.topicId && !topicId) onTopicCreated?.(result.topicId);@@ -86,14 +167,17 @@ const VisitorComposer = memo<VisitorComposerProps>(console.error('[AgentShareVisitor] send failed:', error);setErrorKey(resolveVisitorErrorKey(error));// Give the rejected input back so the visitor can retry / edit.- setValue(message);+ editor.setDocument('markdown', message);} finally {setSending(false);}};return (- <Flexbox gap={4} paddingBlock={8} paddingInline={12}>+ // 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, {@@ -114,71 +198,58 @@ const VisitorComposer = memo<VisitorComposerProps>(onRetry={() => void stopSharedRun()}/>)}- <Flexbox- horizontal- // Center the single-line state (the textarea is shorter than the send- // button, so the text would otherwise hug the bottom edge); once the- // textarea grows it becomes the tallest child and the button pins to- // the bottom via its own alignSelf.- align={'center'}- gap={8}- style={{- background: cssVar.colorFillQuaternary,- border: `1px solid ${cssVar.colorBorderSecondary}`,- borderRadius: 12,- padding: '6px 6px 6px 12px',- }}- >- <TextArea- autoSize={{ maxRows: 6, minRows: 1 }}- disabled={!!blocked}- // Mirrors `SHARE_VISITOR_PROMPT_MAX_LENGTH` (the server-side gate in- // `apps/server/src/routers/lambda/shareChat.ts`) so a legitimate- // long paste is capped up front instead of round-tripping to a- // rejection. Convenience only — a direct RPC caller still hits the- // server bound, handled by `resolveVisitorErrorKey`.- maxLength={SHARE_VISITOR_PROMPT_MAX_LENGTH}- placeholder={t('share.visitor.input.placeholder')}- style={{ border: 'none', boxShadow: 'none', padding: 0 }}- value={value}- variant={'borderless'}- onChange={(e) => setValue(e.target.value)}- {...compositionProps}- onPressEnter={(e) => {- if (!shouldSubmitOnEnter(e, isComposingRef.current)) return;- e.preventDefault();- void send();- }}- />- {isStreaming || stopping ? (- // A run is actually streaming (as opposed to `sending`, the brief- // window before the server has even created the operation) — show- // Stop instead of a plain spinner 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 actually resolved — keep showing Stop (loading)- // through `stopping` so the button doesn't flicker back to Send.- <ActionIcon- disabled={stopping}- icon={CircleStop}- loading={stopping}- style={{ alignSelf: 'flex-end' }}- title={t('share.visitor.input.stop')}- onClick={() => void stopSharedRun()}- />- ) : (- <ActionIcon- disabled={busy || !!blocked || !value.trim()}- icon={SendHorizonal}- loading={busy}- style={{ alignSelf: 'flex-end' }}- title={t('share.visitor.input.send')}- onClick={() => void send()}- />- )}- </Flexbox>- </Flexbox>+ {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>);},);diff --git a/src/features/AgentShareVisitor/VisitorTopBar.tsx b/src/features/AgentShareVisitor/VisitorTopBar.tsxnew file mode 100644index 00000000000..b92428c48a6--- /dev/null+++ b/src/features/AgentShareVisitor/VisitorTopBar.tsx@@ -0,0 +1,100 @@+'use client';++import { Flexbox } from '@lobehub/ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';+import { Link } 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 homePath = isSignedIn ? '/' : buildAgentShareSignInUrl(slugOrId ?? '');++ 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/composerEnterGuard.test.ts b/src/features/AgentShareVisitor/composerEnterGuard.test.tsdeleted file mode 100644index 37817c1a767..00000000000--- a/src/features/AgentShareVisitor/composerEnterGuard.test.ts+++ /dev/null@@ -1,18 +0,0 @@-import { describe, expect, it } from 'vitest';--import { shouldSubmitOnEnter } from './composerEnterGuard';--describe('shouldSubmitOnEnter', () => {- it('submits on a plain Enter', () => {- expect(shouldSubmitOnEnter({ shiftKey: false }, false)).toBe(true);- });-- it('inserts a newline on Shift+Enter', () => {- expect(shouldSubmitOnEnter({ shiftKey: true }, false)).toBe(false);- });-- it('never submits the partial text of an in-flight IME composition', () => {- expect(shouldSubmitOnEnter({ shiftKey: false }, true)).toBe(false);- expect(shouldSubmitOnEnter({ shiftKey: true }, true)).toBe(false);- });-});diff --git a/src/features/AgentShareVisitor/composerEnterGuard.ts b/src/features/AgentShareVisitor/composerEnterGuard.tsdeleted file mode 100644index 69013e55011..00000000000--- a/src/features/AgentShareVisitor/composerEnterGuard.ts+++ /dev/null@@ -1,13 +0,0 @@-/**- * Decide whether a keyboard `Enter` press should submit the visitor composer.- *- * Extracted so the IME-composition guard is unit-testable without rendering- * `VisitorComposer` — see `composerEnterGuard.test.ts`.- *- * rc-textarea's `onPressEnter` (which `@lobehub/ui`'s `TextArea` forwards)- * fires on every `Enter` keydown with NO built-in IME-composing check — so an- * Enter that only confirms an IME candidate (e.g. picking a Chinese/Japanese- * character) would otherwise submit the partial composition text.- */-export const shouldSubmitOnEnter = (event: { shiftKey: boolean }, isComposing: boolean): boolean =>- !event.shiftKey && !isComposing;diff --git a/src/features/AgentShareVisitor/routeMeta.ts b/src/features/AgentShareVisitor/routeMeta.tsindex bd51f8e8bf4..d8086407c0b 100644--- a/src/features/AgentShareVisitor/routeMeta.ts+++ b/src/features/AgentShareVisitor/routeMeta.ts@@ -1,15 +1,15 @@import { MessageSquareShareIcon } from 'lucide-react';-import ConversationLayoutSkeleton from '@/components/Skeleton/Conversation/Layout';+import AgentShareVisitorSkeleton from '@/components/Skeleton/AgentShareVisitor';import { routeMeta } from '@/spa/router/routeMeta';/**- * Agent-share visitor surface (`/agent/:slugOrId`). The shared agent's- * name only becomes known after `getSharedAgent` resolves, so the tab title- * stays on the generic share label rather than flashing a placeholder name.+ * Agent-share visitor surface (`/a/:slugOrId`). The shared agent's name only+ * becomes known after `getSharedAgent` resolves, so the tab title stays on the+ * generic share label rather than flashing a placeholder name.*/export const agentShareVisitorRouteMeta = routeMeta({icon: MessageSquareShareIcon,- Skeleton: ConversationLayoutSkeleton,+ Skeleton: AgentShareVisitorSkeleton,titleKey: 'navigation.sharedAgent',});diff --git a/src/features/AgentShareVisitor/visitorPath.test.ts b/src/features/AgentShareVisitor/visitorPath.test.tsnew file mode 100644index 00000000000..fcbbbfc1477--- /dev/null+++ b/src/features/AgentShareVisitor/visitorPath.test.ts@@ -0,0 +1,27 @@+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');+ });++ 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.tsnew file mode 100644index 00000000000..73adbe72298--- /dev/null+++ b/src/features/AgentShareVisitor/visitorPath.ts@@ -0,0 +1,27 @@+/**+ * 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) =>+ `${AGENT_SHARE_VISITOR_PATH}/${slugOrId}`;++/**+ * Sign-in URL that returns the visitor to the same share once signed in.+ * `/signin` is an auth shell outside the SPA router, so callers navigate to it+ * with a full document load.+ */+export const buildAgentShareSignInUrl = (slugOrId: string) =>+ `/signin?callbackUrl=${encodeURIComponent(buildAgentShareVisitorPath(slugOrId))}`;++/**+ * 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/features/Workspace/useWorkspaceUrlSync.ts b/src/features/Workspace/useWorkspaceUrlSync.tsindex ec615a126b8..0e4b0a0b3ae 100644--- a/src/features/Workspace/useWorkspaceUrlSync.ts+++ b/src/features/Workspace/useWorkspaceUrlSync.ts@@ -32,6 +32,7 @@ const RESERVED_FIRST_SEGMENTS = new Set(['tasks','task',// Personal-only:+ 'a','apps','settings','onboarding',diff --git a/src/layout/GlobalProvider/useUserStateRedirect.ts b/src/layout/GlobalProvider/useUserStateRedirect.tsindex 7bc508d2cc2..5a1c29b25fe 100644--- a/src/layout/GlobalProvider/useUserStateRedirect.ts+++ b/src/layout/GlobalProvider/useUserStateRedirect.ts@@ -9,6 +9,9 @@ import { buildOnboardingRedirectUrl } from '@/utils/onboardingRedirect';const DEFER_REDIRECT_PREFIXES = ['/invite'];+// `/a/:slugOrId` (agent-share visitor page) is deliberately NOT listed: a+// user who followed a share link should reach the shared agent, not be+// bounced into onboarding first.const RESERVED_FIRST_SEGMENTS = new Set(['agent','apps',diff --git a/src/proxy.test.ts b/src/proxy.test.tsnew file mode 100644index 00000000000..5ccf11cb98f--- /dev/null+++ b/src/proxy.test.ts@@ -0,0 +1,29 @@+/** @vitest-environment node */+import { unstable_doesMiddlewareMatch } from 'next/experimental/testing/server';+import { describe, expect, it, vi } from 'vitest';++import { config } from './proxy';++vi.mock('@/libs/next/proxy/define-config', () => ({+ defineConfig: () => ({ middleware: vi.fn() }),+}));++describe('SPA proxy route matching', () => {+ it.each(['/a/shared-agent', '/a/e2e-missing-share', '/a/shared-agent?hl=en-US'])(+ 'routes %s through the SPA proxy',+ (pathname) => {+ expect(+ unstable_doesMiddlewareMatch({ config, url: `http://localhost:3010${pathname}` }),+ ).toBe(true);+ },+ );++ it.each(['/api/chat', '/trpc/lambda/share.getSharedAgent', '/webapi/chat'])(+ 'keeps backend authentication in the handler for %s',+ (pathname) => {+ expect(+ unstable_doesMiddlewareMatch({ config, url: `http://localhost:3010${pathname}` }),+ ).toBe(false);+ },+ );+});diff --git a/src/proxy.ts b/src/proxy.tsindex 25d116ad87a..027e71fb212 100644--- a/src/proxy.ts+++ b/src/proxy.ts@@ -24,6 +24,9 @@ export const config = {'/labs','/eval','/eval(.*)',+ /** Shared-agent pages need the same SPA rewrite as the other client routes. */+ '/a',+ '/a/(.*)','/agent','/agent(.*)','/group',diff --git a/src/routes/(main)/_layout/index.desktop.tsx b/src/routes/(main)/_layout/index.desktop.tsxindex 1d4742c7303..fa47b50993f 100644--- a/src/routes/(main)/_layout/index.desktop.tsx+++ b/src/routes/(main)/_layout/index.desktop.tsx@@ -9,7 +9,6 @@ import { Suspense } from 'react';import { HotkeysProvider } from 'react-hotkeys-hook';import WorkspaceContextSlot from '@/business/client/WorkspaceContextSlot';-import { useIsAgentShareVisitorRoute } from '@/features/AgentRoute/useAgentShareVisitorRoute';import DesktopBrowserGatewayBridge from '@/features/DesktopBrowserGatewayBridge';import DesktopFileMenuBridge from '@/features/DesktopFileMenuBridge';import DesktopLayoutContainer from '@/features/DesktopLayoutContainer';@@ -49,12 +48,6 @@ const Layout: FC = () => {const { isPWA } = usePlatform();const { showCloudPromotion } = useServerConfigStore(featureFlagsSelectors);- // The nav lives outside `TabHost`, so it reads the active tab's location- // (mirrored into the electron store) rather than the root router's — see- // `useActiveLocation.desktop`. A visitor has no nav data, so the panel would- // stay a grey skeleton; unmount it for that branch of `/agent/:aid`.- const isShareVisitor = useIsAgentShareVisitorRoute();-useSeedTabsOnBoot();useWindowUrlMirror();useLastWorkspaceSlugSync();@@ -88,7 +81,7 @@ const Layout: FC = () => {height={`calc(100% - ${TITLE_BAR_HEIGHT}px)`}width={'100%'}>- {!isShareVisitor && <NavPanelShell />}+ <NavPanelShell /><DesktopLayoutContainer><Flexbox height={'100%'} style={tabHostContainer} width={'100%'}><TabHost />diff --git a/src/routes/(main)/_layout/index.tsx b/src/routes/(main)/_layout/index.tsxindex ea91a674213..3ab59dd3dae 100644--- a/src/routes/(main)/_layout/index.tsx+++ b/src/routes/(main)/_layout/index.tsx@@ -12,7 +12,6 @@ import { Outlet } from 'react-router';import WorkspaceContextSlot from '@/business/client/WorkspaceContextSlot';import RouteSegmentSkeleton from '@/components/Skeleton/RouteSegment';import { isDesktop } from '@/const/version';-import { useIsAgentShareVisitorRoute } from '@/features/AgentRoute/useAgentShareVisitorRoute';import { BANNER_HEIGHT } from '@/features/AlertBanner/CloudBanner';import DesktopBrowserGatewayBridge from '@/features/DesktopBrowserGatewayBridge';import DesktopFileMenuBridge from '@/features/DesktopFileMenuBridge';@@ -46,9 +45,6 @@ const GlobalApprovalNotification = dynamic(() => import('@/features/GlobalApprovconst Layout: FC = () => {const { isPWA } = usePlatform();const { showCloudPromotion } = useServerConfigStore(featureFlagsSelectors);- // An agent-share visitor has no access to the nav's data, so the panel would- // stay a grey skeleton — unmount it for that branch of `/agent/:aid`.- const isShareVisitor = useIsAgentShareVisitorRoute();return (<HotkeysProvider initiallyActiveScopes={[HotkeyScopeEnum.Global]}>@@ -82,7 +78,7 @@ const Layout: FC = () => {: '100%'}>- {!isShareVisitor && <NavPanelShell />}+ <NavPanelShell /><DesktopLayoutContainer><DesktopHomeLayout><DesktopHome />diff --git a/src/services/agent.ts b/src/services/agent.tsindex 2a9897d3a3b..60c742bfd72 100644--- a/src/services/agent.ts+++ b/src/services/agent.ts@@ -264,20 +264,12 @@ class AgentService {};/**- * Resolve what a `/agent/:slugOrId` param points at: one of the caller's own- * agents (by id or slug), an agent share, or nothing. See the- * `resolveAgentRoute` procedure for the resolution order and its privacy- * properties.+ * Resolve a url slug to its agent id. Returns `null` for an unknown slug and+ * for one the caller can't see — the two are deliberately indistinguishable.*/- resolveAgentRoute = async (slugOrId: string) => {- // An anonymous visitor on a share URL gets UNAUTHORIZED here (the- // resolver is auth-gated); opt out of the global 401 handler so it does- // not hard-redirect them to /signin before the share surface's own- // sign-in prompt can render (mirrors `agentShareService.getSharedAgent`).- return lambdaClient.agent.resolveAgentRoute.query(- { slugOrId },- { context: { showNotification: false } },- );+ resolveAgentIdBySlug = async (slug: string): Promise<string | null> => {+ const { agentId } = await lambdaClient.agent.resolveAgentIdBySlug.query({ slug });+ return agentId;};/** Rename an agent's url slug (validated server-side; see `updateAgentSlug`). */diff --git a/src/spa/BootShell/routeScope.test.ts b/src/spa/BootShell/routeScope.test.tsindex dc5c054ee0d..0dc4d0fe8ae 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']],- ['Electron', electronDesktopRoutes, ['/desktop-onboarding']],+ ['Web', webDesktopRoutes, ['/onboarding', '/verify-im', '/a/my-bot']],+ ['Electron', electronDesktopRoutes, ['/desktop-onboarding', '/a/my-bot']],])('%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.tsxindex 623fbb380ba..8f3fe9547f2 100644--- a/src/spa/router/desktopRouter.shared.tsx+++ b/src/spa/router/desktopRouter.shared.tsx@@ -32,6 +32,7 @@ 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 CommunityListSkeleton from '@/components/Skeleton/CommunityList';import ConversationLayoutSkeleton from '@/components/Skeleton/Conversation/Layout';@@ -45,9 +46,8 @@ 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 AgentRouteSwitch from '@/features/AgentRoute/AgentRouteSwitch';-import AgentShareLegacyRedirect from '@/features/AgentShareVisitor/LegacyRedirect';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';@@ -346,25 +346,10 @@ export const sharedMainAreaChildren: RouteObject[] = [path: 'task/:taskId',},],- // `/agent/:aid` serves both the creator's own agent and the agent-share- // visitor surface; the param decides which — see `AgentRouteSwitch`.- // The switch is not a `Suspense`, so `withSegmentFallback` cannot swap- // the branding loader for a segment skeleton here — both branches (and- // the switch's own resolving state) carry it explicitly instead.- element: (- <AgentRouteSwitch- fallback={<RouteSegmentSkeleton />}- ownElement={dynamicLayout(- () => import('@/routes/(main)/agent/_layout'),- 'Desktop > Chat > Layout',- { fallback: <RouteSegmentSkeleton />, preloadId: 'agent' },- )}- shareElement={dynamicElement(- () => import('@/features/AgentShareVisitor/Page'),- 'Desktop > Share > Agent',- { fallback: delayed(<ConversationLayoutSkeleton />) },- )}- />+ element: dynamicLayout(+ () => import('@/routes/(main)/agent/_layout'),+ 'Desktop > Chat > Layout',+ { preloadId: 'agent' },),errorElement: <ErrorBoundary />,path: ':aid',@@ -1568,12 +1553,19 @@ export const createSharedDesktopRoutes = ({path: '/',},{- // Legacy agent-share visitor links: the surface now lives at- // `/agent/:slugOrId`, next to the creator's own agent page.- element: <AgentShareLegacyRedirect />,+ // 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: '/share/agent/:slugOrId',+ path: `${AGENT_SHARE_VISITOR_PATH}/:slugOrId`,},...BusinessDesktopRoutesWithoutMainLayout,...platformRoutes,diff --git a/src/spa/router/desktopRouter.sync.test.tsx b/src/spa/router/desktopRouter.sync.test.tsxindex 35066709c94..0d99f175180 100644--- a/src/spa/router/desktopRouter.sync.test.tsx+++ b/src/spa/router/desktopRouter.sync.test.tsx@@ -282,11 +282,11 @@ 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 moved to `/agent/:aid`, so the old- // pattern stays registered on every platform only to redirect legacy links- // (Web, Electron, and the mobile router — see mobileRouter.test.tsx).- expect(webPaths).toContain('/share/agent/:slugOrId');- expect(electronPaths).toContain('/share/agent/:slugOrId');+ // …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');+ expect(electronPaths).toContain('/a/:slugOrId');expect(webPaths).not.toContain('/verify');expect(webPaths).toContain('/acceptance');expect(webPaths).toContain('/onboarding');@@ -516,8 +516,6 @@ describe('desktop router shared definition', () => {(_, factory) => {const matches = matchRoutes(createMainAreaRoutes(factory), '/agent/agt_1');- // The agent-share visitor page now shares this route; the branch is- // decided by `AgentRouteSwitch`, not by a second route pattern.expect(matches?.some((match) => match.route.path === ':aid')).toBe(true);expect(matches?.at(-1)?.params).toMatchObject({ aid: 'agt_1' });},@@ -526,13 +524,16 @@ describe('desktop router shared definition', () => {it.each([['Web', webDesktopRoutes],['Electron', electronDesktopRoutes],- ])('%s redirects legacy /share/agent links to /agent', (_, routes) => {- const matches = matchRoutes(routes, '/share/agent/my-bot');- const element = matches?.at(-1)?.route.element as ReactElement;+ ])(+ '%s serves the agent-share visitor page on /a/:slugOrId outside the main layout',+ (_, routes) => {+ const matches = matchRoutes(routes, '/a/my-bot');- expect(matches?.at(-1)?.params).toMatchObject({ slugOrId: 'my-bot' });- expect((element.type as { displayName?: string }).displayName).toBe('AgentShareLegacyRedirect');- });+ expect(matches).toHaveLength(1);+ expect(matches?.[0]?.route.path).toBe('/a/:slugOrId');+ expect(matches?.[0]?.params).toMatchObject({ slugOrId: 'my-bot' });+ },+ );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.tsxindex e18ade83b61..ea26c5a12e5 100644--- a/src/spa/router/mobileRouter.config.tsx+++ b/src/spa/router/mobileRouter.config.tsx@@ -6,13 +6,12 @@ import {BusinessMobileRoutesWithMainLayout,BusinessMobileRoutesWithoutMainLayout,} from '@/business/client/BusinessMobileRoutes';+import AgentShareVisitorSkeleton from '@/components/Skeleton/AgentShareVisitor';import AppsSkeleton from '@/components/Skeleton/Apps';-import ConversationLayoutSkeleton from '@/components/Skeleton/Conversation/Layout';import { delayed } from '@/components/Skeleton/Delayed';import { acceptanceRouteMeta } from '@/features/Acceptance/routeMeta';-import AgentRouteSwitch from '@/features/AgentRoute/AgentRouteSwitch';-import AgentShareLegacyRedirect from '@/features/AgentShareVisitor/LegacyRedirect';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';@@ -59,24 +58,10 @@ export const sharedMainAreaChildren: RouteObject[] = [path: 'settings',},],- // `/agent/:aid` serves both the creator's own agent and the agent-share- // visitor surface; the param decides which — see `AgentRouteSwitch`.- element: (- <AgentRouteSwitch- fallback={<ConversationLayoutSkeleton />}- // Mobile has no share settings page; the agent itself is the closest stop.- ownShareRedirect={(agentId) => `/agent/${agentId}`}- ownElement={dynamicLayout(- () => import('@/routes/(mobile)/chat/_layout'),- 'Mobile > Chat > Layout',- { preloadId: 'mobile-agent' },- )}- shareElement={dynamicElement(- () => import('@/features/AgentShareVisitor/Page'),- 'Mobile > Share > Agent',- { fallback: delayed(<ConversationLayoutSkeleton />) },- )}- />+ element: dynamicLayout(+ () => import('@/routes/(mobile)/chat/_layout'),+ 'Mobile > Chat > Layout',+ { preloadId: 'mobile-agent' },),errorElement: <ErrorBoundary />,path: ':aid',@@ -625,16 +610,18 @@ export const mobileRoutes: RouteObject[] = [},...BusinessMobileRoutesWithoutMainLayout,- // `/share/*` is served by the standalone Share app (apps/share), not this- // router. The agent-share visitor surface moved to `/agent/:aid` (it needs- // the full chat runtime, so it stays in the main SPA on every platform), but- // old links must keep working: without this entry a phone opening one falls- // through to `*` and gets bounced home instead of redirected.+ // 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: <AgentShareLegacyRedirect />,+ element: dynamicElement(+ () => import('@/features/AgentShareVisitor/Page'),+ 'Mobile > Share > Agent',+ { fallback: delayed(<AgentShareVisitorSkeleton />) },+ ),errorElement: <ErrorBoundary />,handle: { meta: agentShareVisitorRouteMeta },- path: '/share/agent/:slugOrId',+ path: `${AGENT_SHARE_VISITOR_PATH}/:slugOrId`,},// Messenger verify route (outside main layout)diff --git a/src/spa/router/mobileRouter.test.tsx b/src/spa/router/mobileRouter.test.tsxindex cd8ed2ef542..821ab49ffe3 100644--- a/src/spa/router/mobileRouter.test.tsx+++ b/src/spa/router/mobileRouter.test.tsx@@ -1,28 +1,25 @@import { readFile } from 'node:fs/promises';import path from 'node:path';-import type { ReactElement } from 'react';import { matchRoutes } from 'react-router';import { describe, expect, it } from 'vitest';import { mobileRoutes } from './mobileRouter.config';describe('mobileRouter agent share route', () => {- it('serves the agent-share visitor surface on mobile through the shared /agent/:aid route', () => {- const matches = matchRoutes(mobileRoutes, '/agent/my-agent');+ it('serves the agent-share visitor page on /a/:slugOrId outside the main layout', () => {+ const matches = matchRoutes(mobileRoutes, '/a/my-agent');- // Visitor and creator surfaces share this route; `AgentRouteSwitch` picks.- expect(matches?.some((match) => match.route.path === ':aid')).toBe(true);- expect(matches?.at(-1)?.params).toMatchObject({ aid: 'my-agent' });+ expect(matches).toHaveLength(1);+ expect(matches?.[0]?.route.path).toBe('/a/:slugOrId');+ expect(matches?.[0]?.params).toMatchObject({ slugOrId: 'my-agent' });});- it('redirects legacy /share/agent links instead of bouncing to the catch-all', () => {- const matches = matchRoutes(mobileRoutes, '/share/agent/my-agent');- const element = matches?.at(-1)?.route.element as ReactElement;+ it('keeps the creator agent surface on /agent/:aid', () => {+ const matches = matchRoutes(mobileRoutes, '/agent/my-agent');- expect(matches?.at(-1)?.route.path).toBe('/share/agent/:slugOrId');- expect(matches?.at(-1)?.params).toMatchObject({ slugOrId: 'my-agent' });- expect((element.type as { displayName?: string }).displayName).toBe('AgentShareLegacyRedirect');+ expect(matches?.some((match) => match.route.path === ':aid')).toBe(true);+ expect(matches?.at(-1)?.params).toMatchObject({ aid: 'my-agent' });});});