🤯 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): choose visibility when creating in a workspace, explain no-access agents (#23528)
Rdmclin2fb17b58f63ba
diff --git a/apps/server/src/routers/lambda/__tests__/agent.test.ts b/apps/server/src/routers/lambda/__tests__/agent.test.tsindex dfb2ac315a6..d8f18e79120 100644--- a/apps/server/src/routers/lambda/__tests__/agent.test.ts+++ b/apps/server/src/routers/lambda/__tests__/agent.test.ts@@ -314,6 +314,19 @@ describe('agentRouter', () => {workspaceId: 'ws-1',};+ it('returns null from getAgentConfigById for an agent outside the caller scope', async () => {+ // Another member's private agent is filtered out by the scoped lookup.+ vi.mocked(resolveAgentReference).mockRejectedValueOnce(+ new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' }),+ );+ agentServiceMock.getAgentConfigById = vi.fn();++ const caller = agentRouter.createCaller({ ...mockCtx, serverDB: {}, workspaceId: 'ws-1' });++ await expect(caller.getAgentConfigById({ agentId: 'agt_private' })).resolves.toBeNull();+ expect(agentServiceMock.getAgentConfigById).not.toHaveBeenCalled();+ });+it('redacts getAgentConfigById for a member who can view but not edit', async () => {agentServiceMock.getAgentConfigById = vi.fn().mockResolvedValue(fullConfig);vi.mocked(canPerformResourceAction).mockResolvedValueOnce(false).mockResolvedValueOnce(true);diff --git a/apps/server/src/routers/lambda/__tests__/integration/sessionAgentCompat.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/sessionAgentCompat.integration.test.tsindex 0f2c8b40252..0246ecced3f 100644--- a/apps/server/src/routers/lambda/__tests__/integration/sessionAgentCompat.integration.test.ts+++ b/apps/server/src/routers/lambda/__tests__/integration/sessionAgentCompat.integration.test.ts@@ -347,13 +347,14 @@ describe('native Session to Agent compatibility', () => {it('fails closed for foreign, trashed, group and multi-agent contexts', async () => {const { agent, session } = await legacy();const caller = callers();+ // An out-of-scope id reads as "not found or no access": no config, no error.await expect(callers(undefined, otherUserId).agent.getAgentConfigById({ agentId: session.id }),- ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ ).resolves.toBeNull();const workspaceId = await workspace();await expect(callers(workspaceId).agent.getAgentConfigById({ agentId: agent.id }),- ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ ).resolves.toBeNull();const [otherAgent] = await db.insert(agents).values({ userId }).returning();expect(await resolveContext({ agentId: otherAgent.id, sessionId: session.id }, db, userId),@@ -378,9 +379,7 @@ describe('native Session to Agent compatibility', () => {await db.update(sessions).set({ type: 'agent' }).where(eq(sessions.id, session.id));await db.update(agents).set({ isDeleted: true }).where(eq(agents.id, agent.id));for (const id of [session.id, agent.id]) {- await expect(caller.agent.getAgentConfigById({ agentId: id })).rejects.toMatchObject({- code: 'NOT_FOUND',- });+ await expect(caller.agent.getAgentConfigById({ agentId: id })).resolves.toBeNull();await expect(caller.session.updateSession({ id, value: {} })).rejects.toMatchObject({code: 'NOT_FOUND',});@@ -401,14 +400,12 @@ describe('native Session to Agent compatibility', () => {});await expect(callers(undefined, otherUserId).agent.getAgentConfigById({ agentId: agent.id }),- ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ ).resolves.toBeNull();await expect(resolveAgentReference('agent_missing', db, userId)).rejects.toMatchObject({code: 'NOT_FOUND',});await db.update(agents).set({ isDeleted: true }).where(eq(agents.id, agent.id));- await expect(callers().agent.getAgentConfigById({ agentId: agent.id })).rejects.toMatchObject({- code: 'NOT_FOUND',- });+ await expect(callers().agent.getAgentConfigById({ agentId: agent.id })).resolves.toBeNull();});it.each(['agent', 'session'] as const)(diff --git a/apps/server/src/routers/lambda/agent/config.ts b/apps/server/src/routers/lambda/agent/config.tsindex d39c221f4a0..ef197276a9a 100644--- a/apps/server/src/routers/lambda/agent/config.ts+++ b/apps/server/src/routers/lambda/agent/config.ts@@ -110,12 +110,22 @@ export const configRouter = router({}),).query(async ({ input, ctx }) => {- const { agentId } = await resolveAgentReference(- input.agentId,- ctx.serverDB,- ctx.userId,- ctx.workspaceId ?? undefined,- );+ let agentId: string;+ try {+ ({ agentId } = await resolveAgentReference(+ input.agentId,+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ ));+ } catch (error) {+ // An id outside the caller's scope (deleted, or another member's+ // private agent) settles as `null`, the same "not found or no access"+ // answer `protectAgentConfig` gives. The client renders that as a+ // terminal 404 instead of a retryable load failure.+ if (error instanceof TRPCError && error.code === 'NOT_FOUND') return null;+ throw error;+ }const config = await ctx.agentService.getAgentConfigById(agentId);return protectAgentConfig(ctx, agentId, config);}),diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 76e3c4be043..21d878e48bc 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -43,8 +43,10 @@"agentDocument.portal.export": "Export","agentDocument.portal.titlePlaceholder": "Untitled document","agentDocument.portal.viewAll": "View all documents",- "agentNotFound.desc": "This agent does not exist or is no longer accessible — it may have been deleted or set to private by its owner.",- "agentNotFound.title": "Agent Unavailable",+ "agentNotFound.desc": "It may have been deleted, or it's another member's private agent. Ask its creator to publish it to the workspace.",+ "agentNotFound.descPersonal": "It may have been deleted, or the link is wrong.",+ "agentNotFound.title": "This agent doesn't exist or you don't have access",+ "agentNotFound.viewAgents": "View all agents","agentProfile.creator": "Creator","agentProfile.files_one": "{{count}} file","agentProfile.files_other": "{{count}} files",@@ -406,6 +408,13 @@"createTask.visibility.privateAgentDisabled": "Private agents can only run private tasks. Pick a workspace agent or switch this task to Private.","createTask.visibility.privateAgentLocked": "Private agents can only run private tasks.","createTask.visibility.workspace": "Workspace",+ "createVisibility.inheritedPrivate": "Follows its folder: only you can see it.",+ "createVisibility.inheritedPublic": "Follows its folder: everyone in the workspace can see it.",+ "createVisibility.label": "Visibility",+ "createVisibility.private": "Private",+ "createVisibility.privateHint": "Only you can see it. Other members can't open its link until you publish it to the workspace.",+ "createVisibility.public": "Workspace",+ "createVisibility.publicHint": "Everyone in the workspace can see and use it.","cursorInstallGuide.actions.openDocs": "Open Install Guide","cursorInstallGuide.actions.openSystemTools": "Open System Tools","cursorInstallGuide.afterInstall": "After installing, run `agent login`, then retry your message or click Re-detect in System Tools.",@@ -2133,6 +2142,8 @@"plus.search.off": "Off","plus.search.offDesc": "","plus.title": "Add",+ "privateAgentLink.desc": "This is your private agent, so other members can't open the link. Publish it to the workspace to share it.",+ "privateAgentLink.title": "Link copied, but only you can open it","processExplorer.copyPid": "Copy PID","processExplorer.filter": "Filter","processExplorer.gpu": "GPU",diff --git a/locales/en-US/common.json b/locales/en-US/common.jsonindex b37b51f7b2a..2a3d2a716f0 100644--- a/locales/en-US/common.json+++ b/locales/en-US/common.json@@ -363,7 +363,6 @@"navPanel.bottomDivider": "Items below anchor to bottom","navPanel.browseAllAgents": "All agents","navPanel.createPrivateFolder": "New private category",- "navPanel.createWorkspaceAgent": "New workspace agent","navPanel.customizeSidebar": "Customize Sidebar","navPanel.displayItems": "Display Items","navPanel.hidden": "Hidden",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex b2a30ee3292..236b9a92153 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -43,8 +43,10 @@"agentDocument.portal.export": "导出","agentDocument.portal.titlePlaceholder": "未命名文稿","agentDocument.portal.viewAll": "查看全部文稿",- "agentNotFound.desc": "该助理不存在或您已无权访问,可能已被删除或被其所有者设为私人。",- "agentNotFound.title": "助理不可用",+ "agentNotFound.desc": "它可能已被删除,或是其他成员的私人助理。可以请创建者把它发布到工作区。",+ "agentNotFound.descPersonal": "它可能已被删除,或者链接有误。",+ "agentNotFound.title": "助理不存在或你没有访问权限",+ "agentNotFound.viewAgents": "查看全部助理","agentProfile.creator": "创建者","agentProfile.files_one": "{{count}} 个文件","agentProfile.files_other": "{{count}} 个文件",@@ -406,6 +408,13 @@"createTask.visibility.privateAgentDisabled": "私人助理只能执行私人任务,请改用工作区助理或将该任务切回私人。","createTask.visibility.privateAgentLocked": "私人助理只能执行私人任务。","createTask.visibility.workspace": "工作区",+ "createVisibility.inheritedPrivate": "跟随所在文件夹:仅你可见。",+ "createVisibility.inheritedPublic": "跟随所在文件夹:工作区所有成员可见。",+ "createVisibility.label": "可见性",+ "createVisibility.private": "私人",+ "createVisibility.privateHint": "仅你可见。发布到工作区之前,其他成员打不开它的链接。",+ "createVisibility.public": "工作区",+ "createVisibility.publicHint": "工作区所有成员都能看到和使用。","cursorInstallGuide.actions.openDocs": "打开安装指南","cursorInstallGuide.actions.openSystemTools": "打开系统工具","cursorInstallGuide.afterInstall": "安装完成后,请运行 `agent login` 登录,然后重试刚才的消息,或在系统工具中点击“重新检测”。",@@ -2133,6 +2142,8 @@"plus.search.off": "关闭","plus.search.offDesc": "","plus.title": "添加",+ "privateAgentLink.desc": "这是你的私人助理,其他成员打不开这个链接。发布到工作区后就能分享。",+ "privateAgentLink.title": "链接已复制,但只有你能打开","processExplorer.copyPid": "复制 PID","processExplorer.filter": "筛选","processExplorer.gpu": "GPU",diff --git a/locales/zh-CN/common.json b/locales/zh-CN/common.jsonindex 493cfa58ba6..d229f5f619b 100644--- a/locales/zh-CN/common.json+++ b/locales/zh-CN/common.json@@ -363,7 +363,6 @@"navPanel.bottomDivider": "下方条目锚定到底部","navPanel.browseAllAgents": "全部助理","navPanel.createPrivateFolder": "新建私人分组",- "navPanel.createWorkspaceAgent": "新建工作区助理","navPanel.customizeSidebar": "自定义侧边栏","navPanel.displayItems": "显示条目","navPanel.hidden": "已隐藏",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex fa31fbf2f6b..8d6776f58c2 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -317,7 +317,7 @@ export default {'agentDocument.portal.titlePlaceholder': 'Untitled document','agentDocument.portal.export': 'Export','agentNotFound.desc':- 'This agent does not exist or is no longer accessible — it may have been deleted or set to private by its owner.',+ "It may have been deleted, or it's another member's private agent. Ask its creator to publish it to the workspace.",'permission.configAccess.agentChatOnly':'You can only use this Agent, not configure it. You were returned to chat.','permission.configAccess.agentManageRestricted':@@ -328,7 +328,9 @@ export default {'You can only use this Agent Group, not configure it. You were returned to chat.','permission.configAccess.groupRoleRestricted':'Your workspace role cannot configure Agent Groups. You were returned to chat.',- 'agentNotFound.title': 'Agent Unavailable',+ 'agentNotFound.descPersonal': 'It may have been deleted, or the link is wrong.',+ 'agentNotFound.title': "This agent doesn't exist or you don't have access",+ 'agentNotFound.viewAgents': 'View all agents','agentSkillModal.frontmatterInvalid':"This skill's SKILL.md has malformed frontmatter, so its name and description come from the last saved version. Open the document to fix it.",'agentSkillModal.loadFailed': "Couldn't load this skill",@@ -1340,6 +1342,17 @@ export default {'minimap.senderAssistant': 'Agent','minimap.senderUser': 'You','modelSelector.model': 'Model',+ 'privateAgentLink.desc':+ "This is your private agent, so other members can't open the link. Publish it to the workspace to share it.",+ 'privateAgentLink.title': 'Link copied, but only you can open it',+ 'createVisibility.inheritedPrivate': 'Follows its folder: only you can see it.',+ 'createVisibility.inheritedPublic': 'Follows its folder: everyone in the workspace can see it.',+ 'createVisibility.label': 'Visibility',+ 'createVisibility.private': 'Private',+ 'createVisibility.privateHint':+ "Only you can see it. Other members can't open its link until you publish it to the workspace.",+ 'createVisibility.public': 'Workspace',+ 'createVisibility.publicHint': 'Everyone in the workspace can see and use it.','createModal.createBlank': 'Start Blank','createModal.groupPlaceholder': 'Describe what this Group should do...','createModal.groupTitle': 'What should this Group do?',diff --git a/packages/locales/src/default/common.ts b/packages/locales/src/default/common.tsindex 6c1a4d90f8d..d3fb862dd1e 100644--- a/packages/locales/src/default/common.ts+++ b/packages/locales/src/default/common.ts@@ -449,7 +449,6 @@ export default {'more': 'More','navPanel.agent': 'Agents','navPanel.createPrivateFolder': 'New private category',- 'navPanel.createWorkspaceAgent': 'New workspace agent','navPanel.managePrivateFolders': 'Manage private categories','navPanel.myPinned': 'Pinned','navPanel.newChat': 'New chat',diff --git a/src/components/404/index.tsx b/src/components/404/index.tsxindex 6f3ebd69d62..e3f1b8a158b 100644--- a/src/components/404/index.tsx+++ b/src/components/404/index.tsx@@ -10,10 +10,12 @@ import { MAX_WIDTH } from '@/const/layoutTokens';const NotFound = memo<{desc?: string;extra?: ReactNode;+ /** Drop the "check your URL" line when the URL is known to be right (e.g. no access). */+ hideCheck?: boolean;hideWatermark?: boolean;status?: number | string;title?: string;-}>(({ extra, hideWatermark, status = 404, title, desc }) => {+}>(({ extra, hideCheck, hideWatermark, status = 404, title, desc }) => {const { t } = useTranslation('error');return (<Flexbox align={'center'} justify={'center'} style={{ minHeight: '100%', width: '100%' }}>@@ -38,7 +40,7 @@ const NotFound = memo<{</h2><div style={{ lineHeight: '1.8', marginBottom: '2em', textAlign: 'center' }}><div>{desc || t('notFound.desc')}</div>- <div style={{ marginTop: '0.5em' }}>{t('notFound.check')}</div>+ {!hideCheck && <div style={{ marginTop: '0.5em' }}>{t('notFound.check')}</div>}</div>{extra || (<Button type={'primary'} onClick={() => (window.location.href = '/')}>diff --git a/src/features/AgentIdentityModal/CreateContent.tsx b/src/features/AgentIdentityModal/CreateContent.tsxindex 58c48bb26b4..2b96e03e1fd 100644--- a/src/features/AgentIdentityModal/CreateContent.tsx+++ b/src/features/AgentIdentityModal/CreateContent.tsx@@ -6,6 +6,7 @@ import { useTranslation } from 'react-i18next';import AgentAvatar from '@/components/AgentAvatar';import EmojiPicker from '@/components/EmojiPicker';+import CreateVisibilityField, { useCreateVisibility } from '@/features/CreateVisibilityField';import { useGlobalStore } from '@/store/global';import { globalGeneralSelectors } from '@/store/global/selectors';@@ -28,13 +29,16 @@ const CreateAgentIdentityContent = memo<CreateAgentIdentityContentProps>(const { t } = useTranslation(['setting', 'common']);const { close } = useModalContext();const locale = useGlobalStore(globalGeneralSelectors.currentLanguage);+ // `visibility` is only the starting point; in a workspace the user sees and+ // can change who the agent is for before it exists.+ const visibilityState = useCreateVisibility({ groupId, visibility });const form = useCreateAgentIdentityForm({groupId,onCreated: (agentId) => {close();onCreated(agentId);},- visibility,+ visibility: visibilityState.value,});return (@@ -77,6 +81,7 @@ const CreateAgentIdentityContent = memo<CreateAgentIdentityContentProps>(form={form}slugPlaceholder={t('settingAgent.slug.autoPlaceholder', { ns: 'setting' })}/>+ <CreateVisibilityField state={visibilityState} /><Flexbox horizontal gap={8} justify={'flex-end'}><Button disabled={form.saving} onClick={() => close()}>{t('cancel', { ns: 'common' })}diff --git a/src/features/AgentIdentityModal/useCreateAgentIdentityForm.test.ts b/src/features/AgentIdentityModal/useCreateAgentIdentityForm.test.tsindex 1de897a6415..07eb8b64f21 100644--- a/src/features/AgentIdentityModal/useCreateAgentIdentityForm.test.ts+++ b/src/features/AgentIdentityModal/useCreateAgentIdentityForm.test.ts@@ -8,6 +8,7 @@ const mocks = vi.hoisted(() => ({createAgent: vi.fn(),refreshAgentConfig: vi.fn(),refreshAgentList: vi.fn(),+ setAgentVisibility: vi.fn(),updateAgentMeta: vi.fn(),updateAgentSlug: vi.fn(),uploadWithProgress: vi.fn(),@@ -44,6 +45,7 @@ vi.mock('@/store/file', () => ({vi.mock('@/services/agent', () => ({agentService: {+ setAgentVisibility: (...args: unknown[]) => mocks.setAgentVisibility(...args),updateAgentSlug: (...args: unknown[]) => mocks.updateAgentSlug(...args),},}));@@ -153,6 +155,36 @@ describe('useCreateAgentIdentityForm', () => {expect(onCreated).toHaveBeenCalledExactlyOnceWith('agent-new');});+ it('applies a visibility changed while the form stayed open for a rejected slug', async () => {+ mocks.updateAgentSlug+ .mockResolvedValueOnce({ reason: 'taken', success: false })+ .mockResolvedValueOnce({ success: true });+ let visibility: 'private' | 'public' = 'public';+ const onCreated = vi.fn();+ const { result, rerender } = renderHook(() =>+ useCreateAgentIdentityForm({ onCreated, visibility }),+ );++ act(() => result.current.setSlug('taken'));+ await act(async () => {+ await result.current.submit();+ });+ expect(mocks.createAgent).toHaveBeenCalledWith(+ expect.objectContaining({ visibility: 'public' }),+ );++ visibility = 'private';+ rerender();+ act(() => result.current.setSlug('free'));+ await act(async () => {+ await result.current.submit();+ });++ expect(mocks.createAgent).toHaveBeenCalledTimes(1);+ expect(mocks.setAgentVisibility).toHaveBeenCalledWith('agent-new', 'private');+ expect(onCreated).toHaveBeenCalledWith('agent-new');+ });+it('shows a reason instead of closing when the create fails', async () => {mocks.createAgent.mockRejectedValueOnce(new Error('boom'));const { result, onCreated } = setup();diff --git a/src/features/AgentIdentityModal/useCreateAgentIdentityForm.ts b/src/features/AgentIdentityModal/useCreateAgentIdentityForm.tsindex 7a0093aac9a..340e2db6ceb 100644--- a/src/features/AgentIdentityModal/useCreateAgentIdentityForm.ts+++ b/src/features/AgentIdentityModal/useCreateAgentIdentityForm.ts@@ -60,6 +60,7 @@ export const useCreateAgentIdentityForm = ({const [description, setDescription] = useState('');const [slug, setSlug] = useState('');const [createdAgentId, setCreatedAgentId] = useState<string>();+ const [createdVisibility, setCreatedVisibility] = useState<'private' | 'public'>();const [error, setError] = useState<string | undefined>();const [saving, setSaving] = useState(false);const [uploading, setUploading] = useState(false);@@ -90,9 +91,16 @@ export const useCreateAgentIdentityForm = ({let agentId = createdAgentId;if (agentId) {await updateAgentMeta(agentId, meta);+ // The visibility may have changed while the form stayed open for a+ // rejected slug; the retry must not keep the first choice.+ if (visibility && visibility !== createdVisibility) {+ await agentService.setAgentVisibility(agentId, visibility);+ setCreatedVisibility(visibility);+ }} else {({ agentId } = await createAgent({ config: meta, groupId, visibility }));setCreatedAgentId(agentId);+ setCreatedVisibility(visibility);}const nextSlug = slug.trim().toLowerCase();diff --git a/src/features/AgentNotFound/index.test.tsx b/src/features/AgentNotFound/index.test.tsxnew file mode 100644index 00000000000..5b324609876--- /dev/null+++ b/src/features/AgentNotFound/index.test.tsx@@ -0,0 +1,44 @@+import { fireEvent, render, screen } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { AgentNotFound } from './index';++const mocks = vi.hoisted(() => ({+ navigate: vi.fn(),+ workspaceId: 'ws-1' as string | undefined,+}));++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ useActiveWorkspaceId: () => mocks.workspaceId,+}));++vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({+ useWorkspaceAwareNavigate: () => mocks.navigate,+}));++describe('AgentNotFound', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.workspaceId = 'ws-1';+ });++ it('explains private access in a workspace and leads to the agent list instead of retrying', () => {+ render(<AgentNotFound showAgentList />);++ expect(screen.getByText('agentNotFound.title')).toBeInTheDocument();+ expect(screen.getByText('agentNotFound.desc')).toBeInTheDocument();+ expect(screen.queryByText('notFound.check')).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: /retry|notFound.backHome/i })).toBeNull();++ fireEvent.click(screen.getByRole('button', { name: 'agentNotFound.viewAgents' }));+ expect(mocks.navigate).toHaveBeenCalledWith('/agents');+ });++ it('uses the personal copy and no navigation for hosts that must stay put', () => {+ mocks.workspaceId = undefined;+ render(<AgentNotFound />);++ expect(screen.getByText('agentNotFound.descPersonal')).toBeInTheDocument();+ expect(screen.queryByRole('button')).toBeNull();+ });+});diff --git a/src/features/AgentNotFound/index.tsx b/src/features/AgentNotFound/index.tsxindex 1fc8b56c05d..b67df42823d 100644--- a/src/features/AgentNotFound/index.tsx+++ b/src/features/AgentNotFound/index.tsx@@ -1,25 +1,57 @@'use client';import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';+import { Button } from '@lobehub/ui';import { type FC, memo, type PropsWithChildren } from 'react';import { useTranslation } from 'react-i18next';import { useParams } from 'react-router';+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import NotFound from '@/components/404';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';const BUILTIN_SLUG_SET = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));+interface AgentNotFoundProps {+ /**+ * Offer a way out to the Agent list. Off for hosts that must not navigate+ * the page away (popup windows, side panels).+ */+ showAgentList?: boolean;+}+/**- * Terminal 404 card for an agent whose config fetch settled on `null` — it- * doesn't exist or the viewer lost access (e.g. a workspace agent switched- * back to private by its owner).+ * Terminal card for an agent whose config fetch settled on `null` — it+ * doesn't exist or the viewer has no access (e.g. another member's private+ * agent). Both cases share one message so the card never reveals that a+ * private id exists. Nothing here is retryable, so the only action leaves.*/-export const AgentNotFound = memo(() => {+export const AgentNotFound = memo<AgentNotFoundProps>(({ showAgentList }) => {const { t } = useTranslation('chat');+ const navigate = useWorkspaceAwareNavigate();+ // Only a workspace has other members' private agents to ask about.+ const inWorkspace = !!useActiveWorkspaceId();- return <NotFound hideWatermark desc={t('agentNotFound.desc')} title={t('agentNotFound.title')} />;+ return (+ <NotFound+ hideCheck+ hideWatermark+ desc={t(inWorkspace ? 'agentNotFound.desc' : 'agentNotFound.descPersonal')}+ title={t('agentNotFound.title')}+ extra={+ showAgentList ? (+ <Button type={'primary'} onClick={() => navigate('/agents')}>+ {t('agentNotFound.viewAgents')}+ </Button>+ ) : (+ // An empty fragment suppresses NotFound's default full-page "Back to Home" reload.+ <></>+ )+ }+ />+ );});AgentNotFound.displayName = 'AgentNotFound';@@ -33,14 +65,16 @@ AgentNotFound.displayName = 'AgentNotFound';* The not-found flag is cleared by any later successful fetch (e.g. the agent* is made public again), so the guard recovers without a manual refresh.*/-export const AgentNotFoundGuard: FC<PropsWithChildren> = memo(({ children }) => {- const params = useParams<{ aid?: string }>();- const aid = params.aid && !BUILTIN_SLUG_SET.has(params.aid) ? params.aid : '';- const isNotFound = useAgentStore(agentByIdSelectors.isAgentNotFoundById(aid));+export const AgentNotFoundGuard: FC<PropsWithChildren<AgentNotFoundProps>> = memo(+ ({ children, showAgentList }) => {+ const params = useParams<{ aid?: string }>();+ const aid = params.aid && !BUILTIN_SLUG_SET.has(params.aid) ? params.aid : '';+ const isNotFound = useAgentStore(agentByIdSelectors.isAgentNotFoundById(aid));- if (isNotFound) return <AgentNotFound />;+ if (isNotFound) return <AgentNotFound showAgentList={showAgentList} />;- return children;-});+ return children;+ },+);AgentNotFoundGuard.displayName = 'AgentNotFoundGuard';diff --git a/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.tsx b/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.tsxindex f3605e03c2d..36a80c8c4a5 100644--- a/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.tsx+++ b/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.tsx@@ -35,6 +35,7 @@ import { createMoveTopicsModal } from '@/features/AgentTopicManager/MoveTopicsMoimport { createTopicForwardModal } from '@/features/Conversation/MessageForward/TopicForwardModal';import { confirmRemoveTopic } from '@/features/DeleteTopicConfirm';import { useFavoriteMenuItem } from '@/features/Favorites';+import { usePrivateAgentLinkNotice } from '@/features/PrivateAgentLinkNotice';import { getProjectTopicPath } from '@/features/Projects/Layout/navigation';import { openShareModal } from '@/features/ShareModal';import { openTopicDoctorModal } from '@/features/TopicDoctorModal';@@ -82,6 +83,7 @@ export const useTopicItemDropdownMenu = ({const routeTopicIdRef = useLatest(routeTopicId);const unmountedRef = useUnmountedRef();const activeWorkspaceSlug = useActiveWorkspaceSlug();+ const notifyPrivateAgentLink = usePrivateAgentLinkNotice();const { allowed: canCreateTopic } = usePermission('create_content');const { allowed: canEditTopic } = usePermission('edit_own_content');@@ -295,7 +297,9 @@ export const useTopicItemDropdownMenu = ({activeWorkspaceSlug,)}`;await copyToClipboard(url);- toast.success(t('actions.copyLinkSuccess'));+ // A private agent's topic link opens for nobody else in the workspace.+ if (!(await notifyPrivateAgentLink(activeAgentId)))+ toast.success(t('actions.copyLinkSuccess'));},},{@@ -433,6 +437,7 @@ export const useTopicItemDropdownMenu = ({openTopicInPortal,addTab,navigate,+ notifyPrivateAgentLink,t,handleOpenShareModal,]);diff --git a/src/features/AgentViewAll/AgentViewAllPage.tsx b/src/features/AgentViewAll/AgentViewAllPage.tsxindex 35d621bf6fe..38f25658de9 100644--- a/src/features/AgentViewAll/AgentViewAllPage.tsx+++ b/src/features/AgentViewAll/AgentViewAllPage.tsx@@ -542,11 +542,14 @@ const AgentViewAllPage = memo(() => {createMarketAgentMenuItem,} = useCreateMenuItems();- // Creating from the Private tab lands the item in the private bucket, so- // the new row appears in the list the user is currently looking at.+ // Each tab starts creation in its own bucket, so the new row appears in the+ // list the user is currently looking at. The create dialogs still show the+ // choice and let the user change it.const createOptions = useMemo(() =>- activeWorkspaceId && segment === 'private' ? { visibility: 'private' as const } : undefined,+ activeWorkspaceId+ ? { visibility: segment === 'private' ? ('private' as const) : ('public' as const) }+ : undefined,[activeWorkspaceId, segment],);diff --git a/src/features/ConnectAgent/index.tsx b/src/features/ConnectAgent/index.tsxindex bacbffda627..dd457e99566 100644--- a/src/features/ConnectAgent/index.tsx+++ b/src/features/ConnectAgent/index.tsx@@ -43,6 +43,10 @@ import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceimport AsyncError from '@/components/AsyncError';import CommandLine from '@/components/CommandLine';import { DOWNLOAD_URL } from '@/const/url';+import CreateVisibilityField, {+ type CreateVisibility,+ useCreateVisibility,+} from '@/features/CreateVisibilityField';import { getDeviceIcon } from '@/features/DeviceManager/getDeviceIcon';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { deviceService } from '@/services/device';@@ -393,8 +397,18 @@ interface ConnectAgentContentProps {}const ConnectAgentContent = memo<ConnectAgentContentProps>(- ({ groupId, initialDevice, onTitleChange, showOpenChat = true, visibility }) => {+ ({+ groupId,+ initialDevice,+ onTitleChange,+ showOpenChat = true,+ visibility: initialVisibility,+ }) => {const { t } = useTranslation('chat');+ // Same "Private / Workspace" field as the create-agent form; the caller's+ // value is only where it starts.+ const visibilityState = useCreateVisibility({ groupId, visibility: initialVisibility });+ const visibility = visibilityState.value;const { close, setCanDismissByClickOutside } = useModalContext();const navigate = useWorkspaceAwareNavigate();const storeCreateAgent = useAgentStore((s) => s.createAgent);@@ -513,17 +527,47 @@ const ConnectAgentContent = memo<ConnectAgentContentProps>([currentDeviceId, profiles, target],);+ const defaultSingleName = useCallback(+ (nextVisibility?: CreateVisibility) => {+ if (!single) return '';+ const profile = isRemoteHeterogeneousType(single.type) ? profiles[single.type] : undefined;+ const productTitle = profile?.title ?? single.title;+ return (+ heteroAgentDefaultName({+ productTitle,+ visibility: nextVisibility,+ workspaceId: activeWorkspaceId,+ }) ?? productTitle+ );+ },+ [activeWorkspaceId, profiles, single],+ );+const goConfirm = useCallback(() => {if (!single) return;const profile = isRemoteHeterogeneousType(single.type) ? profiles[single.type] : undefined;- const productTitle = profile?.title ?? single.title;- setName(- heteroAgentDefaultName({ productTitle, visibility, workspaceId: activeWorkspaceId }) ??- productTitle,- );+ setName(defaultSingleName(visibility));setDescription(profile?.description ?? '');setStep(2);- }, [activeWorkspaceId, profiles, single, visibility]);+ }, [defaultSingleName, profiles, single, visibility]);++ // The default name says whose agent a workspace agent is ("Ann's Codex"),+ // so switching visibility on the confirm step re-derives a name the user+ // has not edited.+ const confirmVisibilityState = useMemo(+ () => ({+ ...visibilityState,+ setValue: (next: CreateVisibility) => {+ setName((current) =>+ current === defaultSingleName(visibilityState.value)+ ? defaultSingleName(next)+ : current,+ );+ visibilityState.setValue(next);+ },+ }),+ [defaultSingleName, visibilityState],+ );const buildCreateParams = useCallback((provider: ConnectableProvider, overrides?: { description?: string; name?: string }) => {@@ -888,6 +932,10 @@ const ConnectAgentContent = memo<ConnectAgentContentProps>(</Flexbox>)}+ {scanState.status === 'success' && detectedCount > 0 && (+ <CreateVisibilityField state={visibilityState} />+ )}+{createError && (<AlertshowIcon@@ -978,6 +1026,7 @@ const ConnectAgentContent = memo<ConnectAgentContentProps>(<Icon color={cssVar.colorSuccess} icon={CheckCircle2} size={16} /></div></div>+ <CreateVisibilityField state={confirmVisibilityState} />{createError && (<AlertshowIcondiff --git a/src/features/CreateVisibilityField/index.tsx b/src/features/CreateVisibilityField/index.tsxnew file mode 100644index 00000000000..81ba7239b4c--- /dev/null+++ b/src/features/CreateVisibilityField/index.tsx@@ -0,0 +1,72 @@+'use client';++import { Flexbox, Icon, Segmented, Text } from '@lobehub/ui';+import { LockIcon, UsersIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import type { CreateVisibility, CreateVisibilityState } from './useCreateVisibility';++export type { CreateVisibility, CreateVisibilityOptions } from './useCreateVisibility';+export { resolveCreateVisibility, useCreateVisibility } from './useCreateVisibility';++interface CreateVisibilityFieldProps {+ state: CreateVisibilityState;+}++/**+ * "Private / Workspace" choice shared by the create-agent form, the connect+ * external agent wizard and the create-group dialog, so all three say the same+ * thing about who can open the result. Renders nothing outside a workspace.+ */+const CreateVisibilityField = memo<CreateVisibilityFieldProps>(({ state }) => {+ const { t } = useTranslation('chat');+ const { canPublish, locked, publishBlockedReason, setValue, show, value } = state;++ if (!show || !value) return null;++ const hint = locked+ ? t(+ value === 'private'+ ? 'createVisibility.inheritedPrivate'+ : 'createVisibility.inheritedPublic',+ )+ : value === 'private'+ ? !canPublish && publishBlockedReason+ ? publishBlockedReason+ : t('createVisibility.privateHint')+ : t('createVisibility.publicHint');++ return (+ <Flexbox gap={6}>+ <Text type={'secondary'}>{t('createVisibility.label')}</Text>+ <Segmented<CreateVisibility>+ block+ disabled={locked}+ value={value}+ options={[+ {+ icon: <Icon icon={LockIcon} />,+ label: t('createVisibility.private'),+ value: 'private',+ },+ {+ disabled: !canPublish,+ icon: <Icon icon={UsersIcon} />,+ label: t('createVisibility.public'),+ title: canPublish ? undefined : publishBlockedReason,+ value: 'public',+ },+ ]}+ onChange={setValue}+ />+ <Text style={{ fontSize: 12 }} type={'secondary'}>+ {hint}+ </Text>+ </Flexbox>+ );+});++CreateVisibilityField.displayName = 'CreateVisibilityField';++export default CreateVisibilityField;diff --git a/src/features/CreateVisibilityField/useCreateVisibility.test.ts b/src/features/CreateVisibilityField/useCreateVisibility.test.tsnew file mode 100644index 00000000000..6ba36b3661a--- /dev/null+++ b/src/features/CreateVisibilityField/useCreateVisibility.test.ts@@ -0,0 +1,93 @@+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { resolveCreateVisibility, useCreateVisibility } from './useCreateVisibility';++const mocks = vi.hoisted(() => ({+ permission: { allowed: true, reason: undefined as string | undefined },+ workspaceId: 'ws-1' as string | undefined,+}));++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ useActiveWorkspaceId: () => mocks.workspaceId,+}));++vi.mock('@/hooks/usePermission', () => ({+ usePermission: () => mocks.permission,+}));++describe('resolveCreateVisibility', () => {+ it('starts private in a workspace when the caller gives no context', () => {+ expect(resolveCreateVisibility({ inWorkspace: true })).toEqual({+ initial: 'private',+ locked: false,+ show: true,+ });+ });++ it('keeps the list context as an editable starting value', () => {+ expect(resolveCreateVisibility({ inWorkspace: true, visibility: 'public' })).toEqual({+ initial: 'public',+ locked: false,+ show: true,+ });+ });++ it('locks to the folder visibility when creating inside a folder', () => {+ expect(+ resolveCreateVisibility({ groupId: 'sg-1', inWorkspace: true, visibility: 'public' }),+ ).toEqual({ initial: 'public', locked: true, show: true });+ });++ it('hides the field for a folder of unknown visibility so the server inherits it', () => {+ expect(resolveCreateVisibility({ groupId: 'sg-1', inWorkspace: true })).toEqual({+ initial: undefined,+ locked: true,+ show: false,+ });+ });++ it('hides the field outside a workspace and passes the caller value through', () => {+ expect(resolveCreateVisibility({ inWorkspace: false })).toEqual({+ initial: undefined,+ locked: false,+ show: false,+ });+ });+});++describe('useCreateVisibility', () => {+ beforeEach(() => {+ mocks.permission = { allowed: true, reason: undefined };+ mocks.workspaceId = 'ws-1';+ });++ it('lets the user switch the default to workspace', () => {+ const { result } = renderHook(() => useCreateVisibility());+ expect(result.current.value).toBe('private');++ act(() => result.current.setValue('public'));++ expect(result.current.value).toBe('public');+ });++ it('falls back to private when the user cannot create workspace content', () => {+ mocks.permission = { allowed: false, reason: 'Members only' };++ const { result } = renderHook(() => useCreateVisibility({ visibility: 'public' }));++ expect(result.current.value).toBe('private');+ expect(result.current.canPublish).toBe(false);+ expect(result.current.publishBlockedReason).toBe('Members only');+ });++ it('does not remember the previous choice across dialogs', () => {+ const first = renderHook(() => useCreateVisibility());+ act(() => first.result.current.setValue('public'));+ first.unmount();++ const second = renderHook(() => useCreateVisibility());++ expect(second.result.current.value).toBe('private');+ });+});diff --git a/src/features/CreateVisibilityField/useCreateVisibility.ts b/src/features/CreateVisibilityField/useCreateVisibility.tsnew file mode 100644index 00000000000..aa179e6247b--- /dev/null+++ b/src/features/CreateVisibilityField/useCreateVisibility.ts@@ -0,0 +1,69 @@+import { useState } from 'react';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { usePermission } from '@/hooks/usePermission';++export type CreateVisibility = 'private' | 'public';++export interface CreateVisibilityOptions {+ /** Sidebar folder the new item is created in. */+ groupId?: string;+ /**+ * The caller's context: the folder's visibility when `groupId` is set,+ * otherwise the list the user is looking at (e.g. the Private tab).+ */+ visibility?: CreateVisibility;+}++export interface ResolvedCreateVisibility {+ /** Value the field starts on; `undefined` lets the server decide. */+ initial?: CreateVisibility;+ /** The folder decides, so the field shows its value but cannot change it. */+ locked: boolean;+ /** Visibility only exists inside a workspace. */+ show: boolean;+}++/**+ * Where a new agent / group starts. In a workspace the default is private:+ * a wrong private default is noticed at once and fixed by publishing, while a+ * wrong workspace default silently exposes prompts and knowledge to everyone.+ * Inside a folder the folder decides (the server rejects a mismatch). Nothing+ * is remembered between dialogs, so the default never drifts.+ */+export const resolveCreateVisibility = ({+ groupId,+ inWorkspace,+ visibility,+}: CreateVisibilityOptions & { inWorkspace: boolean }): ResolvedCreateVisibility => {+ if (!inWorkspace) return { initial: visibility, locked: false, show: false };+ // A folder of unknown visibility: leave it to the server's folder inheritance.+ if (groupId) return { initial: visibility, locked: true, show: !!visibility };+ return { initial: visibility ?? 'private', locked: false, show: true };+};++export interface CreateVisibilityState {+ /** Whether the user may create workspace-visible items at all. */+ canPublish: boolean;+ locked: boolean;+ publishBlockedReason?: string;+ setValue: (value: CreateVisibility) => void;+ show: boolean;+ /** What to send to the server; `undefined` lets the server decide. */+ value?: CreateVisibility;+}++/** Form state for the shared "Visibility" field of the create dialogs. */+export const useCreateVisibility = (+ options: CreateVisibilityOptions = {},+): CreateVisibilityState => {+ const inWorkspace = !!useActiveWorkspaceId();+ const { allowed: canPublish, reason: publishBlockedReason } = usePermission('create_content');+ const { initial, locked, show } = resolveCreateVisibility({ ...options, inWorkspace });++ const [value, setValue] = useState<CreateVisibility | undefined>(() =>+ !locked && initial === 'public' && !canPublish ? 'private' : initial,+ );++ return { canPublish, locked, publishBlockedReason, setValue, show, value };+};diff --git a/src/features/HomeSidebar/Body/Agent/ModalProvider.tsx b/src/features/HomeSidebar/Body/Agent/ModalProvider.tsxindex ad48679de04..145b2fab2e6 100644--- a/src/features/HomeSidebar/Body/Agent/ModalProvider.tsx+++ b/src/features/HomeSidebar/Body/Agent/ModalProvider.tsx@@ -17,7 +17,10 @@ import {import type { OpenCreateAgentIdentityModalOptions } from '@/features/AgentIdentityModal';import EditingPopover from '@/features/EditingPopover';-import type { OpenCreateAgentModalOptions } from '@/features/HomeSidebar/hooks/useCreateModal';+import type {+ CreateAgentModalSubmitOptions,+ OpenCreateAgentModalOptions,+} from '@/features/HomeSidebar/hooks/useCreateModal';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { openLabelFormModal } from '@/features/WorkspaceSetting/Labels/LabelFormModal';import { useAgentStore } from '@/store/agent';@@ -107,16 +110,25 @@ const CreateGroupModalRenderer = memo<CreateGroupModalRendererProps>(const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);const sendAsGroup = useHomeStore((s) => s.sendAsGroup);+ // The dialog's visibility field starts from the caller's context and hands+ // back what the user settled on.const handleSubmit = useCallback(- async (prompt: string) => {- await sendAsGroup({ groupId, message: prompt, visibility });+ async (prompt: string, options?: CreateAgentModalSubmitOptions) => {+ await sendAsGroup({+ groupId,+ message: prompt,+ visibility: options?.visibility ?? visibility,+ });},[sendAsGroup, groupId, visibility],);- const handleCreateBlank = useCallback(async () => {- await sendAsGroup({ groupId, message: '', visibility });- }, [sendAsGroup, groupId, visibility]);+ const handleCreateBlank = useCallback(+ async (options?: CreateAgentModalSubmitOptions) => {+ await sendAsGroup({ groupId, message: '', visibility: options?.visibility ?? visibility });+ },+ [sendAsGroup, groupId, visibility],+ );// Mounted only while the modal should be open, so the open/close bridge is// just this component's lifetime — the panel itself lives in the ModalHost.@@ -127,6 +139,7 @@ const CreateGroupModalRenderer = memo<CreateGroupModalRendererProps>(onClosed: onClose,onCreateBlank: handleCreateBlank,onSubmit: handleSubmit,+ visibility: { groupId, visibility },};useEffect(() => {diff --git a/src/features/HomeSidebar/Body/Agent/index.tsx b/src/features/HomeSidebar/Body/Agent/index.tsxindex 707b195f1b1..48b86aea044 100644--- a/src/features/HomeSidebar/Body/Agent/index.tsx+++ b/src/features/HomeSidebar/Body/Agent/index.tsx@@ -16,13 +16,11 @@ import { ArrowRight } from 'lucide-react';import React, { memo, type MouseEvent, Suspense, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';-import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import SectionTitle, { useSectionTriggerStyle } from '@/features/NavPanel/components/SectionTitle';import SkeletonList from '@/features/NavPanel/components/SkeletonList';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { useFetchAgentLabels } from '@/hooks/useFetchAgentLabels';import { useFetchAgentList } from '@/hooks/useFetchAgentList';-import { usePermission } from '@/hooks/usePermission';import { useCreateMenuItems } from '../../hooks';import Actions from './Actions';@@ -42,60 +40,13 @@ const Agent = memo<AgentProps>(({ itemKey }) => {useFetchAgentLabels();// One "Agents" section in both modes. In a workspace it lists shared and// private rows together (private ones carry a lock icon).- const activeWorkspaceId = useActiveWorkspaceId();-const { openConfigGroupModal } = useAgentModal();- // Create menu items- const {- createAgentListMenuItem,- createAgentMenuItem,- createConnectAgentMenuItem,- createGroupChatMenuItem,- createMarketAgentMenuItem,- createTopLevelMenuItems,- isLoading,- } = useCreateMenuItems();- const { allowed: canCreatePublic } = usePermission('create_content');-- const addMenuItems = useMemo(() => {- if (!activeWorkspaceId) return createTopLevelMenuItems();-- // Workspace: new agents start private (the safe default the former- // Private section used); a workspace agent is one explicit entry away.- const connectItem = createConnectAgentMenuItem({ visibility: 'private' });- const workspaceAgentItem = canCreatePublic- ? createAgentMenuItem({ visibility: 'public' })- : undefined;-- return [- createAgentMenuItem({ visibility: 'private' }),- ...(workspaceAgentItem- ? [- {- ...workspaceAgentItem,- key: 'newWorkspaceAgent',- label: t('navPanel.createWorkspaceAgent'),- },- ]- : []),- createGroupChatMenuItem({ visibility: 'private' }),- ...(connectItem ? [{ type: 'divider' as const }, connectItem] : []),- { type: 'divider' as const },- createAgentListMenuItem(),- createMarketAgentMenuItem(),- ];- }, [- activeWorkspaceId,- canCreatePublic,- createAgentListMenuItem,- createAgentMenuItem,- createConnectAgentMenuItem,- createGroupChatMenuItem,- createMarketAgentMenuItem,- createTopLevelMenuItems,- t,- ]);+ // One create menu in both modes. In a workspace each dialog (agent, group,+ // external agent) carries its own "Private / Workspace" field, defaulting to+ // private, so the menu no longer splits entries by visibility.+ const { createTopLevelMenuItems, isLoading } = useCreateMenuItems();+ const addMenuItems = useMemo(() => createTopLevelMenuItems(), [createTopLevelMenuItems]);const handleOpenConfigGroupModal = useCallback((scope?: 'private' | 'public') => {diff --git a/src/features/HomeSidebar/hooks/useCreateModal.tsx b/src/features/HomeSidebar/hooks/useCreateModal.tsxindex b06120ca958..300248ca273 100644--- a/src/features/HomeSidebar/hooks/useCreateModal.tsx+++ b/src/features/HomeSidebar/hooks/useCreateModal.tsx@@ -18,6 +18,11 @@ import {ChatInputProvider,DesktopChatInput,} from '@/features/ChatInput';+import CreateVisibilityField, {+ type CreateVisibility,+ type CreateVisibilityOptions,+ useCreateVisibility,+} from '@/features/CreateVisibilityField';import { useRandomQuestions } from '@/features/Home/SuggestQuestions/useRandomQuestions';import { agentSkillService } from '@/services/skill';import { useToolStore } from '@/store/tool';@@ -312,6 +317,11 @@ const Examples = memo<ExamplesProps>(({ suggestMode, onExampleClick }) => {);});+export interface CreateAgentModalSubmitOptions {+ /** The visibility the user settled on; only set when the field was shown. */+ visibility?: CreateVisibility;+}+export interface CreateAgentModalProps {agentId?: string;/**@@ -321,16 +331,37 @@ export interface CreateAgentModalProps {*/modalRef?: { current?: ModalInstance };onClose: () => void;- onCreateBlank: () => Promise<void> | void;+ onCreateBlank: (options?: CreateAgentModalSubmitOptions) => Promise<void> | void;onOpenSkills?: (identifier: string) => void;- onSubmit: (prompt: string) => Promise<void> | void;+ onSubmit: (prompt: string, options?: CreateAgentModalSubmitOptions) => Promise<void> | void;onTryInLobeAI?: () => Promise<void> | void;type: 'agent' | 'group';+ /**+ * Shows the "Private / Workspace" field, starting from this context (the+ * group dialog passes it; workspace only). Omitted, no field is shown.+ */+ visibility?: CreateVisibilityOptions;}export const CreateAgentModal = memo<CreateAgentModalProps>(- ({ type, agentId, modalRef, onClose, onOpenSkills, onSubmit, onCreateBlank, onTryInLobeAI }) => {+ ({+ type,+ agentId,+ modalRef,+ onClose,+ onOpenSkills,+ onSubmit,+ onCreateBlank,+ onTryInLobeAI,+ visibility,+ }) => {const { t } = useTranslation('chat');+ const visibilityState = useCreateVisibility(visibility);+ const showVisibility = !!visibility && visibilityState.show;+ const submitOptions = useMemo<CreateAgentModalSubmitOptions | undefined>(+ () => (visibility ? { visibility: visibilityState.value } : undefined),+ [visibility, visibilityState.value],+ );const editorRef = useRef<ChatInputEditor | null>(null);const contentRef = useRef('');const examplePromptRef = useRef('');@@ -424,7 +455,7 @@ export const CreateAgentModal = memo<CreateAgentModalProps>(}}- await onSubmit(text);+ await (submitOptions ? onSubmit(text, submitOptions) : onSubmit(text));void trackCreateAgentModalCreationSucceeded({source: getSubmitSource(text),type,@@ -434,7 +465,7 @@ export const CreateAgentModal = memo<CreateAgentModalProps>(setLoading(false);}},- [getSubmitSource, handleClose, isAgent, loading, onSubmit, type],+ [getSubmitSource, handleClose, isAgent, loading, onSubmit, submitOptions, type],);const handleContinueCreate = useCallback(() => {@@ -498,7 +529,7 @@ export const CreateAgentModal = memo<CreateAgentModalProps>(if (loading) return;setLoading(true);try {- await onCreateBlank();+ await (submitOptions ? onCreateBlank(submitOptions) : onCreateBlank());void trackCreateAgentModalCreationSucceeded({source: 'blank',type,@@ -507,7 +538,7 @@ export const CreateAgentModal = memo<CreateAgentModalProps>(} finally {setLoading(false);}- }, [handleClose, loading, onCreateBlank, type]);+ }, [handleClose, loading, onCreateBlank, submitOptions, type]);const handleExampleClick = useCallback((prompt: string) => {examplePromptRef.current = prompt.trim();@@ -601,6 +632,8 @@ export const CreateAgentModal = memo<CreateAgentModalProps>(/></ChatInputProvider>+ {showVisibility && <CreateVisibilityField state={visibilityState} />}+{isAgent && skillSuggestion && (<SkillSuggestionPanelinstallError={skillInstallError}diff --git a/src/features/MobileShell/AgentPagesLayout.tsx b/src/features/MobileShell/AgentPagesLayout.tsxindex ca0b76dd600..3e4dcd189da 100644--- a/src/features/MobileShell/AgentPagesLayout.tsx+++ b/src/features/MobileShell/AgentPagesLayout.tsx@@ -10,7 +10,7 @@ import MobilePageLayout from './PageLayout';/** Full-screen agent sub-pages (profile, docs, …) with the agent 404 fallback. */const MobileAgentPagesLayout: FC = () => (<MobilePageLayout>- <AgentNotFoundGuard>+ <AgentNotFoundGuard showAgentList><Outlet /></AgentNotFoundGuard></MobilePageLayout>diff --git a/src/features/PageEditor/Copilot/TopicSelector/useDropdownMenu.tsx b/src/features/PageEditor/Copilot/TopicSelector/useDropdownMenu.tsxindex ecaa4aac8b1..38ef119e5b0 100644--- a/src/features/PageEditor/Copilot/TopicSelector/useDropdownMenu.tsx+++ b/src/features/PageEditor/Copilot/TopicSelector/useDropdownMenu.tsx@@ -24,6 +24,7 @@ import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaimport { openRenameModal } from '@/components/RenameModal';import { isDesktop } from '@/const/version';import { confirmRemoveTopic } from '@/features/DeleteTopicConfirm';+import { usePrivateAgentLinkNotice } from '@/features/PrivateAgentLinkNotice';import { openShareModal } from '@/features/ShareModal';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';@@ -53,6 +54,7 @@ export const useDropdownMenu = ({topicTitle,}: UseDropdownMenuProps): (() => DropdownItem[]) => {const { t } = useTranslation(['common', 'topic', 'chat']);+ const notifyPrivateAgentLink = usePrivateAgentLinkNotice();const appOrigin = useAppOrigin();const navigate = useWorkspaceAwareNavigate();@@ -199,14 +201,16 @@ export const useDropdownMenu = ({icon: <Icon icon={Link2} />,key: 'copyLink',label: t('actions.copyLink', { ns: 'topic' }),- onClick: () => {+ onClick: async () => {if (!agentId) return;const url = `${appOrigin}${buildWorkspaceAwarePath(AGENT_CHAT_TOPIC_URL(agentId, topicId),activeWorkspaceSlug,)}`;void navigator.clipboard.writeText(url);- toast.success(t('actions.copyLinkSuccess', { ns: 'topic' }));+ // A private agent's topic link opens for nobody else in the workspace.+ if (!(await notifyPrivateAgentLink(agentId)))+ toast.success(t('actions.copyLinkSuccess', { ns: 'topic' }));},},{@@ -266,6 +270,7 @@ export const useDropdownMenu = ({isCompleted,markTopicCompleted,navigate,+ notifyPrivateAgentLink,onClose,onDelete,openTopicInNewWindow,diff --git a/src/features/Portal/AgentDetail/useMoreMenu.ts b/src/features/Portal/AgentDetail/useMoreMenu.tsindex 604aad64a3b..70d7ec5b502 100644--- a/src/features/Portal/AgentDetail/useMoreMenu.ts+++ b/src/features/Portal/AgentDetail/useMoreMenu.ts@@ -3,6 +3,7 @@ import { agentDisplayName, agentRenameField } from '@lobechat/types';import { openRenameModal } from '@/components/RenameModal';import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';+import { usePrivateAgentLinkNotice } from '@/features/PrivateAgentLinkNotice';import { usePermission } from '@/hooks/usePermission';import { useAgentStore } from '@/store/agent';import { agentSelectors } from '@/store/agent/selectors';@@ -20,12 +21,15 @@ export const useAgentDetailMoreMenu = (): PortalMoreMenuConfig | undefined => {]);const { allowed: canEdit } = usePermission('edit_own_content');const shareUrl = usePortalShareUrl(agentId ? AGENT_CHAT_URL(agentId) : undefined);+ const notifyPrivateAgentLink = usePrivateAgentLinkNotice();if (!agentId) return;return {copyId: agentId,copyLink: shareUrl,+ // A private agent's link opens for nobody else in the workspace.+ onLinkCopied: () => notifyPrivateAgentLink(agentId),refresh: () => refreshAgentConfig(agentId),rename: canEdit? () =>diff --git a/src/features/Portal/components/PortalMoreMenu/buildItems.test.ts b/src/features/Portal/components/PortalMoreMenu/buildItems.test.tsindex d6450acb30c..ead8f6a13df 100644--- a/src/features/Portal/components/PortalMoreMenu/buildItems.test.ts+++ b/src/features/Portal/components/PortalMoreMenu/buildItems.test.ts@@ -57,6 +57,19 @@ describe('buildPortalMoreMenuItems', () => {expect(copy).toHaveBeenCalledWith('/repo/a.ts', 'moreMenu.copyPathSuccess');});+ it('hands the copy-link follow-up to the copier so it can replace the plain confirmation', () => {+ const copy = vi.fn();+ const onLinkCopied = vi.fn();+ const [item] = build({ copyLink: 'https://app.lobehub.com/x', onLinkCopied }, copy);++ (item as any).onClick();+ expect(copy).toHaveBeenCalledWith(+ 'https://app.lobehub.com/x',+ 'moreMenu.copyLinkSuccess',+ onLinkCopied,+ );+ });+it('ignores the declaration order of the config', () => {const items = build({delete: vi.fn(),@@ -103,6 +116,7 @@ describe('buildPortalMoreMenuItems', () => {1,'https://app.lobehub.com/x','moreMenu.copyLinkSuccess',+ undefined,);expect(copy).toHaveBeenNthCalledWith(2, 'id_1', 'moreMenu.copyIdSuccess');});diff --git a/src/features/Portal/components/PortalMoreMenu/buildItems.ts b/src/features/Portal/components/PortalMoreMenu/buildItems.tsindex 87f8ee2b559..ed989ffcda7 100644--- a/src/features/Portal/components/PortalMoreMenu/buildItems.ts+++ b/src/features/Portal/components/PortalMoreMenu/buildItems.ts@@ -18,7 +18,11 @@ export type PortalMoreMenuLabelKey =| 'moreMenu.rename';interface BuildOptions {- copy: (value: string, successKey: PortalMoreMenuLabelKey) => void;+ copy: (+ value: string,+ successKey: PortalMoreMenuLabelKey,+ onCopied?: () => boolean | Promise<boolean>,+ ) => void;t: (key: PortalMoreMenuLabelKey) => string;}@@ -52,7 +56,7 @@ export const buildPortalMoreMenuItems = (icon: createElement(Icon, { icon: Link }),key: 'copyLink',label: t('moreMenu.copyLink'),- onClick: () => copy(copyLink, 'moreMenu.copyLinkSuccess'),+ onClick: () => copy(copyLink, 'moreMenu.copyLinkSuccess', config.onLinkCopied),});if (copyId)share.push({diff --git a/src/features/Portal/components/PortalMoreMenu/index.tsx b/src/features/Portal/components/PortalMoreMenu/index.tsxindex b1a36009f2a..7e388861151 100644--- a/src/features/Portal/components/PortalMoreMenu/index.tsx+++ b/src/features/Portal/components/PortalMoreMenu/index.tsx@@ -30,8 +30,9 @@ const PortalMoreMenu = memo<PortalMoreMenuProps>(({ config, outdent }) => {const items = useMemo(() =>buildPortalMoreMenuItems(config, {- copy: async (value, successKey) => {+ copy: async (value, successKey, onCopied) => {await copyToClipboard(value);+ if (await onCopied?.()) return;toast.success(t(successKey));},t: (key) => t(key),diff --git a/src/features/Portal/components/PortalMoreMenu/types.ts b/src/features/Portal/components/PortalMoreMenu/types.tsindex c736cfe8113..2036a19a31a 100644--- a/src/features/Portal/components/PortalMoreMenu/types.ts+++ b/src/features/Portal/components/PortalMoreMenu/types.ts@@ -22,6 +22,11 @@ export interface PortalMoreMenuConfig {delete?: () => void;/** Portal-specific actions, rendered as their own group before delete. */extraItems?: DropdownItem[];+ /**+ * Runs after the link is copied. Returning `true` means it showed its own+ * confirmation (e.g. "only you can open this"), so the plain one is skipped.+ */+ onLinkCopied?: () => boolean | Promise<boolean>;/** Leave the panel for the entity's full page. */openInPage?: () => void;/** Refetch the entity from the server. */diff --git a/src/features/PrivateAgentLinkNotice/index.test.tsx b/src/features/PrivateAgentLinkNotice/index.test.tsxnew file mode 100644index 00000000000..6a3af638989--- /dev/null+++ b/src/features/PrivateAgentLinkNotice/index.test.tsx@@ -0,0 +1,77 @@+import { renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useAgentStore } from '@/store/agent';++import { usePrivateAgentLinkNotice } from './index';++const mocks = vi.hoisted(() => ({+ publish: vi.fn(),+ warning: vi.fn(),+ workspaceId: 'ws-1' as string | undefined,+}));++vi.mock('@lobehub/ui', () => ({ toast: { warning: mocks.warning } }));++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ useActiveWorkspaceId: () => mocks.workspaceId,+}));++vi.mock('./usePublishAgentToWorkspace', () => ({+ usePublishAgentToWorkspace: () => mocks.publish,+}));++const prefetch = vi.fn();++const setVisibility = (visibility: 'private' | 'public') =>+ useAgentStore.setState({+ agentMap: { agt_1: { id: 'agt_1', visibility } },+ prefetchAgentConfig: prefetch,+ });++describe('usePrivateAgentLinkNotice', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.workspaceId = 'ws-1';+ });++ it('warns that other members cannot open a private agent link and offers publishing', async () => {+ setVisibility('private');+ const { result } = renderHook(() => usePrivateAgentLinkNotice());++ await expect(result.current('agt_1')).resolves.toBe(true);++ const options = mocks.warning.mock.calls[0][0];+ expect(options.title).toBe('privateAgentLink.title');+ expect(options.description).toBe('privateAgentLink.desc');+ options.actions[0].onClick();+ expect(mocks.publish).toHaveBeenCalledWith('agt_1');+ });++ it('stays quiet for a workspace agent', async () => {+ setVisibility('public');+ const { result } = renderHook(() => usePrivateAgentLinkNotice());++ await expect(result.current('agt_1')).resolves.toBe(false);+ expect(mocks.warning).not.toHaveBeenCalled();+ });++ it('stays quiet outside a workspace', async () => {+ mocks.workspaceId = undefined;+ setVisibility('private');+ const { result } = renderHook(() => usePrivateAgentLinkNotice());++ await expect(result.current('agt_1')).resolves.toBe(false);+ expect(mocks.warning).not.toHaveBeenCalled();+ });++ it('loads an uncached agent before deciding, so a cold project row still warns', async () => {+ prefetch.mockImplementationOnce(async () => setVisibility('private'));+ useAgentStore.setState({ agentMap: {}, prefetchAgentConfig: prefetch });+ const { result } = renderHook(() => usePrivateAgentLinkNotice());++ await expect(result.current('agt_1')).resolves.toBe(true);+ expect(prefetch).toHaveBeenCalledWith('agt_1');+ expect(mocks.warning).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/features/PrivateAgentLinkNotice/index.tsx b/src/features/PrivateAgentLinkNotice/index.tsxnew file mode 100644index 00000000000..17b26c596b8--- /dev/null+++ b/src/features/PrivateAgentLinkNotice/index.tsx@@ -0,0 +1,53 @@+import { toast } from '@lobehub/ui';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { useAgentStore } from '@/store/agent';+import { agentSelectors } from '@/store/agent/selectors';++import { usePublishAgentToWorkspace } from './usePublishAgentToWorkspace';++export { usePublishAgentToWorkspace } from './usePublishAgentToWorkspace';++/**+ * Returns a callback for "a link into this agent was just copied". In a+ * workspace, a private agent's link opens for nobody but its creator, so the+ * confirmation warns about that and offers publishing right there. Returns+ * `true` when it showed the warning, so the caller can skip its plain success+ * toast.+ */+export const usePrivateAgentLinkNotice = () => {+ const { t } = useTranslation('chat');+ const activeWorkspaceId = useActiveWorkspaceId();+ const publishAgent = usePublishAgentToWorkspace();++ return useCallback(+ async (agentId: string | undefined) => {+ if (!activeWorkspaceId || !agentId) return false;++ const readVisibility = () =>+ agentSelectors.getAgentVisibilityById(agentId)(useAgentStore.getState());+ // A row of a cold project visit may point at an agent whose config was+ // never loaded; load it before deciding which confirmation to show.+ if (!readVisibility()) {+ try {+ await useAgentStore.getState().prefetchAgentConfig(agentId);+ } catch {+ return false;+ }+ }+ if (readVisibility() !== 'private') return false;++ toast.warning({+ actions: [{ label: t('agent.publishToWorkspace'), onClick: () => publishAgent(agentId) }],+ description: t('privateAgentLink.desc'),+ duration: 8000,+ id: `private-agent-link-${agentId}`,+ title: t('privateAgentLink.title'),+ });+ return true;+ },+ [activeWorkspaceId, publishAgent, t],+ );+};diff --git a/src/features/PrivateAgentLinkNotice/usePublishAgentToWorkspace.tsx b/src/features/PrivateAgentLinkNotice/usePublishAgentToWorkspace.tsxnew file mode 100644index 00000000000..8d521387c0d--- /dev/null+++ b/src/features/PrivateAgentLinkNotice/usePublishAgentToWorkspace.tsx@@ -0,0 +1,55 @@+import { confirmModal, toast } from '@lobehub/ui';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++import { getAgentPublishErrorKey } from '@/features/HomeSidebar/Body/Agent/List/AgentItem/agentMenuVisibility';+import { useRevealSidebarSection } from '@/features/HomeSidebar/hooks/useRevealSidebarSection';+import VisibilityConfirmContent from '@/features/VisibilityConfirmContent';+import { agentService } from '@/services/agent';+import { useAgentStore } from '@/store/agent';+import { useHomeStore } from '@/store/home';+import { useUserStore } from '@/store/user';++/**+ * Confirm, then publish a private agent to the workspace — the same flow as+ * the sidebar row's "Publish to Workspace", for surfaces outside the sidebar.+ */+export const usePublishAgentToWorkspace = () => {+ const { t } = useTranslation(['chat', 'common']);+ const refreshAgentList = useHomeStore((s) => s.refreshAgentList);+ const refreshAgentConfig = useAgentStore((s) => s.internal_refreshAgentConfig);+ const refreshWorkspaceUserPreference = useUserStore((s) => s.refreshWorkspaceUserPreference);+ const revealSidebarSection = useRevealSidebarSection();++ return useCallback(+ (agentId: string) =>+ confirmModal({+ cancelText: t('cancel', { ns: 'common' }),+ content: <VisibilityConfirmContent variant="publish" />,+ okText: t('agent.publishToWorkspace'),+ onOk: async () => {+ try {+ await agentService.publishAgentToWorkspace(agentId);+ // Publishing moves a private pin into this member's personal pin+ // list server-side; the config refresh clears the private state+ // the link notice reads.+ await Promise.all([+ refreshAgentList(),+ refreshWorkspaceUserPreference(),+ refreshAgentConfig(agentId),+ ]);+ revealSidebarSection('agent');+ toast.success(t('agent.publishToWorkspaceSuccess'));+ } catch (error) {+ console.error('Failed to publish agent:', error);+ const publishErrorKey = getAgentPublishErrorKey(error);+ toast.error(+ publishErrorKey ? t(publishErrorKey) : t('operationFailed', { ns: 'common' }),+ );+ }+ },+ title: t('agent.publishToWorkspace'),+ }),+ [refreshAgentConfig, refreshAgentList, refreshWorkspaceUserPreference, revealSidebarSection, t],+ );+};diff --git a/src/routes/(main)/agent/_layout/index.tsx b/src/routes/(main)/agent/_layout/index.tsxindex d1292a4099c..7611cfa509b 100644--- a/src/routes/(main)/agent/_layout/index.tsx+++ b/src/routes/(main)/agent/_layout/index.tsx@@ -19,7 +19,7 @@ const Layout: FC = () => {<Flexbox className={styles.mainContainer} flex={1} height={'100%'}>{/* Keep the sidebar interactive when the routed agent is gone (deletedor made private) — only the content area collapses to the 404 card. */}- <AgentNotFoundGuard>+ <AgentNotFoundGuard showAgentList><Outlet /></AgentNotFoundGuard></Flexbox>diff --git a/src/routes/(mobile)/chat/_layout/index.tsx b/src/routes/(mobile)/chat/_layout/index.tsxindex 4d47f1d8267..333bdfe30cd 100644--- a/src/routes/(mobile)/chat/_layout/index.tsx+++ b/src/routes/(mobile)/chat/_layout/index.tsx@@ -19,7 +19,7 @@ const Layout: FC = () => (>{/* Same 404 fallback as the desktop agent layout: only the content areacollapses when the routed agent is gone or turned private. */}- <AgentNotFoundGuard>+ <AgentNotFoundGuard showAgentList><Outlet /></AgentNotFoundGuard></MobileContentLayout>