🤯 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
♻️ refactor(agent): move permissions, visibility and transfer into Agent settings (#23753)
Rdmclin25991f8c7710e
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 12a9ec95a69..5a8eb6ac5b8 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -1608,6 +1608,7 @@"permission.noManagePermission": "Only the creator or a workspace owner can change permissions","permission.page.accessLevelLabel": "Access level","permission.page.accessLevelPrivateHint": "Members get this level once the agent is published to the workspace. It can be changed after publishing.",+ "permission.page.agentEntry": "Permissions","permission.page.configGroup": "Editable settings","permission.page.devicePolicyDesc": "Whether members can switch the execution environment for their own runs.","permission.page.devicePolicyFixedDesc": "Members can only use the environment you set",@@ -1634,6 +1635,7 @@"permission.page.groupTopicSharePolicyDesc": "Whether members can publish share links for this group's topics.","permission.page.groupTopicSharePolicyMemberDesc": "Members can publish share links for any of this group's topics","permission.page.groupTopicSharePolicyRestrictedDesc": "Only you and workspace owners can publish share links for this group",+ "permission.page.groupTransferDesc": "Hand this group to another workspace member. It moves to them once they accept.","permission.page.kbAccessibleWhenShared": "Can access when shared","permission.page.kbNoAccessWhenShared": "No access when shared","permission.page.libraryAccessLevelPrivateHint": "Members get this level once the knowledge base is published to the workspace. It can be changed after publishing.",@@ -1643,15 +1645,22 @@"permission.page.modelPolicyDesc": "Whether members can switch the model for their own conversations.","permission.page.modelPolicyFixedDesc": "Members can only use the model you set","permission.page.modelPolicyMemberDesc": "Members can use a model they set themselves",+ "permission.page.ownershipGroup": "Ownership","permission.page.personalDesc": "This agent only belongs to you, so there is nothing to share yet. Publish it to a workspace to set member permissions.","permission.page.personalTitle": "Permissions apply to workspace agents","permission.page.privateNotice": "This agent is still private. Everything here takes effect once you publish it to the workspace.",+ "permission.page.sharingGroup": "Visibility & ownership","permission.page.title": "Permissions","permission.page.topicSharePolicyDesc": "Whether members can publish share links for this agent's topics.","permission.page.topicSharePolicyMemberDesc": "Members can publish share links for any of this agent's topics","permission.page.topicSharePolicyRestrictedDesc": "Only you and workspace owners can publish share links",+ "permission.page.transferDesc": "Hand this agent to another workspace member. It moves to them once they accept.",+ "permission.page.transferLabel": "Transfer ownership","permission.page.usableWhenShared": "Can use when shared","permission.page.viewableWhenShared": "Can view when shared",+ "permission.page.visibilityBuiltinDesc": "Built-in agents are always visible to the whole workspace",+ "permission.page.visibilityCreatorOnlyDesc": "Only the creator can make a shared agent private again",+ "permission.page.visibilityDesc": "Who in the workspace can see and use this agent","permission.saveNoEditPermission": "You have view-only access to this page, so your changes were not saved","permission.updateError": "Failed to update permission","permission.viewOnlySendTip": "You have view-only access and cannot send messages",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex ee89b8b0eb5..59cd8933e44 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -1608,6 +1608,7 @@"permission.noManagePermission": "仅创建者或工作区所有者可以修改权限","permission.page.accessLevelLabel": "访问级别","permission.page.accessLevelPrivateHint": "发布到工作区后成员会拿到这个级别,发布后可以再调整。",+ "permission.page.agentEntry": "权限","permission.page.configGroup": "修改权限","permission.page.devicePolicyDesc": "成员在自己的运行中是否可以切换执行环境。","permission.page.devicePolicyFixedDesc": "成员只能使用你设定的执行环境",@@ -1634,6 +1635,7 @@"permission.page.groupTopicSharePolicyDesc": "成员是否可以把该群组中的话题发布为分享链接。","permission.page.groupTopicSharePolicyMemberDesc": "成员可以把该群组中的任意话题发布为分享链接","permission.page.groupTopicSharePolicyRestrictedDesc": "只有你和工作区所有者可以发布该群组的分享链接",+ "permission.page.groupTransferDesc": "把这个群组转交给工作区的其他成员,对方接受后生效。","permission.page.kbAccessibleWhenShared": "公开后可访问","permission.page.kbNoAccessWhenShared": "公开后不可访问","permission.page.libraryAccessLevelPrivateHint": "知识库发布到工作区后,成员将获得此访问级别,发布后仍可修改。",@@ -1643,15 +1645,22 @@"permission.page.modelPolicyDesc": "成员在自己的会话中是否可以切换模型。","permission.page.modelPolicyFixedDesc": "成员只能使用你设定的模型","permission.page.modelPolicyMemberDesc": "成员可以使用自己设定的模型",+ "permission.page.ownershipGroup": "所有权","permission.page.personalDesc": "这个助手只属于你,暂时没有需要分享的对象。发布到工作区后即可设置成员权限。","permission.page.personalTitle": "权限配置仅对工作区助手生效","permission.page.privateNotice": "这个助手当前是私人的,以下配置会在发布到工作区后生效。",+ "permission.page.sharingGroup": "可见性与所有权","permission.page.title": "成员权限","permission.page.topicSharePolicyDesc": "成员是否可以把该助手下的话题发布为分享链接。","permission.page.topicSharePolicyMemberDesc": "成员可以把该助手下的任意话题发布为分享链接","permission.page.topicSharePolicyRestrictedDesc": "只有你和工作区所有者可以发布分享链接",+ "permission.page.transferDesc": "把这个助手转交给工作区的其他成员,对方接受后生效。",+ "permission.page.transferLabel": "转让所有权","permission.page.usableWhenShared": "公开后可使用","permission.page.viewableWhenShared": "共享后可查看",+ "permission.page.visibilityBuiltinDesc": "内置助手始终对整个工作区可见",+ "permission.page.visibilityCreatorOnlyDesc": "只有创建者可以把已共享的助手改回私人",+ "permission.page.visibilityDesc": "工作区里谁能看到并使用这个助手","permission.saveNoEditPermission": "你仅有该页面的查看权限,修改未保存","permission.updateError": "权限更新失败","permission.viewOnlySendTip": "你仅有查看权限,无法发送消息",diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 95f28cd41ef..c6903a96ac8 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -528,6 +528,7 @@ export default {'permission.page.accessLevelLabel': 'Access level','permission.page.accessLevelPrivateHint':'Members get this level once the agent is published to the workspace. It can be changed after publishing.',+ 'permission.page.agentEntry': 'Permissions','permission.page.configGroup': 'Editable settings','permission.page.devicePolicyDesc':'Whether members can switch the execution environment for their own runs.',@@ -543,6 +544,8 @@ export default {'permission.page.documentPrivateNotice':'This page is still private. Everything here takes effect once you publish it to the workspace.','permission.page.entry': 'Permissions',+ 'permission.page.groupTransferDesc':+ 'Hand this group to another workspace member. It moves to them once they accept.','permission.page.kbAccessibleWhenShared': 'Can access when shared','permission.page.kbNoAccessWhenShared': 'No access when shared','permission.page.libraryAccessLevelPrivateHint':@@ -585,11 +588,13 @@ export default {'permission.page.modelPolicyMemberDesc': 'Members can use a model they set themselves','permission.page.modelPolicyDesc':'Whether members can switch the model for their own conversations.',+ 'permission.page.ownershipGroup': 'Ownership','permission.page.personalDesc':'This agent only belongs to you, so there is nothing to share yet. Publish it to a workspace to set member permissions.','permission.page.personalTitle': 'Permissions apply to workspace agents','permission.page.privateNotice':'This agent is still private. Everything here takes effect once you publish it to the workspace.',+ 'permission.page.sharingGroup': 'Visibility & ownership','permission.page.title': 'Permissions','permission.page.topicSharePolicyDesc':"Whether members can publish share links for this agent's topics.",@@ -597,8 +602,16 @@ export default {"Members can publish share links for any of this agent's topics",'permission.page.topicSharePolicyRestrictedDesc':'Only you and workspace owners can publish share links',+ 'permission.page.transferDesc':+ 'Hand this agent to another workspace member. It moves to them once they accept.',+ 'permission.page.transferLabel': 'Transfer ownership','permission.page.usableWhenShared': 'Can use when shared','permission.page.viewableWhenShared': 'Can view when shared',+ 'permission.page.visibilityBuiltinDesc':+ 'Built-in agents are always visible to the whole workspace',+ 'permission.page.visibilityCreatorOnlyDesc':+ 'Only the creator can make a shared agent private again',+ 'permission.page.visibilityDesc': 'Who in the workspace can see and use this agent','permission.saveNoEditPermission':'You have view-only access to this page, so your changes were not saved','permission.updateError': 'Failed to update permission',diff --git a/src/business/client/hooks/useAgentGroupTransferToMemberAction.ts b/src/business/client/hooks/useAgentGroupTransferToMemberAction.tsnew file mode 100644index 00000000000..8f5c7739efd--- /dev/null+++ b/src/business/client/hooks/useAgentGroupTransferToMemberAction.ts@@ -0,0 +1,11 @@+import type { AgentGroupTransferToMemberMeta } from './useAgentGroupTransferToMemberMenuItem';++/**+ * Opens the "transfer to member" flow for an agent group — hand its ownership+ * to another workspace member (recipient must accept). Returns null when the+ * viewer cannot start it. Open-source default: unavailable.+ */+export const useAgentGroupTransferToMemberAction = (+ _groupId?: string,+ _groupMeta?: AgentGroupTransferToMemberMeta,+): (() => void) | null => null;diff --git a/src/business/client/hooks/useAgentTransferToMemberAction.ts b/src/business/client/hooks/useAgentTransferToMemberAction.tsnew file mode 100644index 00000000000..9f524756231--- /dev/null+++ b/src/business/client/hooks/useAgentTransferToMemberAction.ts@@ -0,0 +1,14 @@+import type { MetaData } from '@lobechat/types';++import type { AgentTransferScope } from './useAgentTransferMenuItem';++/**+ * Opens the "transfer to member" flow for an agent — hand its ownership to+ * another workspace member (recipient must accept). Returns null when the+ * viewer cannot start it. Open-source default: unavailable.+ */+export const useAgentTransferToMemberAction = (+ _agentId?: string,+ _agentMeta?: MetaData,+ _scope?: AgentTransferScope,+): (() => void) | null => null;diff --git a/src/features/AgentPermission/PermissionForm.tsx b/src/features/AgentPermission/PermissionForm.tsxindex 8a0e0e0415c..d34e8d206f2 100644--- a/src/features/AgentPermission/PermissionForm.tsx+++ b/src/features/AgentPermission/PermissionForm.tsx@@ -14,6 +14,7 @@ import { getSelectionPolicyLabelKeys } from '@/features/ResourcePermission/selecimport { useAccessLevelOptions } from '@/features/ResourcePermission/useAccessLevelOptions';import { useAgentPermission } from './useAgentPermission';+import { useSharingGroup } from './useSharingGroup';const styles = createStaticStyles(({ css }) => ({// FormTitle centres the avatar against title+description; a one-line icon@@ -53,6 +54,7 @@ const PermissionForm = memo<PermissionFormProps>(({ agentId }) => {topicSharePolicy,} = useAgentPermission(agentId);const form = useForm();+ const sharingGroup = useSharingGroup(agentId);const labelKeys = getSelectionPolicyLabelKeys(isPrivate);@@ -265,9 +267,13 @@ const PermissionForm = memo<PermissionFormProps>(({ agentId }) => {<Formcollapsible={false}form={form}- items={[...(memberGroup ? [memberGroup] : []), configGroup]}itemsType={'group'}variant={'filled'}+ items={[+ ...(sharingGroup ? [sharingGroup] : []),+ ...(memberGroup ? [memberGroup] : []),+ configGroup,+ ]}{...FORM_STYLE}/></>diff --git a/src/features/AgentPermission/index.tsx b/src/features/AgentPermission/index.tsxindex 83eac87c14b..95c1d6e2954 100644--- a/src/features/AgentPermission/index.tsx+++ b/src/features/AgentPermission/index.tsx@@ -39,7 +39,7 @@ const AgentPermission = memo(() => {styles={{ left: { paddingInlineStart: 24 } }}left={activeAgentId ? (- <AgentBreadcrumb agentId={activeAgentId} title={t('permission.page.title')} />+ <AgentBreadcrumb agentId={activeAgentId} title={t('permission.page.agentEntry')} />) : null}/>diff --git a/src/features/AgentPermission/useSharingGroup.tsx b/src/features/AgentPermission/useSharingGroup.tsxnew file mode 100644index 00000000000..d59005d1f5e--- /dev/null+++ b/src/features/AgentPermission/useSharingGroup.tsx@@ -0,0 +1,120 @@+'use client';++import { Button, Icon } from '@lobehub/ui';+import { type FormGroupItem } from '@lobehub/ui/form';+import * as stylex from '@stylexjs/stylex';+import { GlobeIcon, LockIcon, UserRoundPlus } from 'lucide-react';+import { useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { useAgentTransferToMemberAction } from '@/business/client/hooks/useAgentTransferToMemberAction';+import {+ type AgentVisibilityOption,+ useAgentVisibilityControl,+} from '@/features/AgentVisibility/useAgentVisibilityControl';+import PolicySelect, { type PolicyOption } from '@/features/ResourcePermission/PolicySelect';+import { useAgentStore } from '@/store/agent';+import { agentByIdSelectors } from '@/store/agent/selectors';++const styles = stylex.create({+ // Same one-line-icon alignment as the other rows of the Permission form.+ rowIcon: {+ alignItems: 'center',+ alignSelf: 'flex-start',+ display: 'flex',+ height: '1em',+ },+});++/**+ * The "Visibility & ownership" card of the Agent Permission page: the+ * Private / Workspace scope and the handover to another member. Both used to+ * sit in the sidebar row menu; the gates are the same as there, and a viewer+ * who may not act sees the scope read-only and no transfer row at all.+ */+export const useSharingGroup = (agentId: string): FormGroupItem | undefined => {+ const { t } = useTranslation(['setting', 'chat', 'agent']);+ const agent = useAgentStore(agentByIdSelectors.getAgentById(agentId));++ const visibility = useAgentVisibilityControl({+ id: agentId,+ slug: agent?.slug,+ userId: agent?.userId,+ visibility: agent?.visibility,+ });++ const openTransfer = useAgentTransferToMemberAction(+ agentId,+ {+ avatar: agent?.avatar ?? undefined,+ backgroundColor: agent?.backgroundColor ?? undefined,+ title: agent?.title ?? undefined,+ },+ { userId: agent?.userId, visibility: agent?.visibility },+ );++ const visibilityOptions = useMemo(+ (): PolicyOption<AgentVisibilityOption>[] => [+ {+ desc: t('agent.visibility.privateDesc', { ns: 'chat' }),+ icon: LockIcon,+ label: t('agent.visibility.private', { ns: 'chat' }),+ value: 'private',+ },+ {+ desc: t('agent.visibility.workspaceDesc', { ns: 'chat' }),+ icon: GlobeIcon,+ label: t('agent.visibility.workspace', { ns: 'chat' }),+ value: 'public',+ },+ ],+ [t],+ );++ const { canChange, current, lockReason, select } = visibility;++ const visibilityRow = current+ ? {+ avatar: (+ <span {...stylex.props(styles.rowIcon)}>+ <Icon icon={current === 'private' ? LockIcon : GlobeIcon} size={16} />+ </span>+ ),+ children: (+ <PolicySelect+ disabled={!canChange}+ options={visibilityOptions}+ value={current}+ onChange={select}+ />+ ),+ desc:+ lockReason === 'builtin'+ ? t('permission.page.visibilityBuiltinDesc')+ : lockReason === 'notCreator'+ ? t('permission.page.visibilityCreatorOnlyDesc')+ : t('permission.page.visibilityDesc'),+ label: t('agent.visibility', { ns: 'chat' }),+ }+ : undefined;++ const transferRow = openTransfer+ ? {+ avatar: (+ <span {...stylex.props(styles.rowIcon)}>+ <Icon icon={UserRoundPlus} size={16} />+ </span>+ ),+ children: (+ <Button onClick={openTransfer}>{t('transfer.transferToMember', { ns: 'agent' })}</Button>+ ),+ desc: t('permission.page.transferDesc'),+ label: t('permission.page.transferLabel'),+ }+ : undefined;++ const children = [visibilityRow, transferRow].filter((row) => !!row);+ if (children.length === 0) return;++ return { children, title: t('permission.page.sharingGroup') };+};diff --git a/src/features/AgentProfileTabs/useAgentProfileTabOptions.ts b/src/features/AgentProfileTabs/useAgentProfileTabOptions.tsindex 6b1b4ec73ce..4be0269bbcd 100644--- a/src/features/AgentProfileTabs/useAgentProfileTabOptions.ts+++ b/src/features/AgentProfileTabs/useAgentProfileTabOptions.ts@@ -66,7 +66,7 @@ export const useAgentProfileTabOptions = (active: AgentProfileTab, agentId: stri'knowledge': t('tab.knowledge'),'mail': t('tab.mail'),'opening': t('agentTab.opening', { ns: 'setting' }),- 'permission': t('permission.page.entry', { ns: 'setting' }),+ 'permission': t('permission.page.agentEntry', { ns: 'setting' }),// Inside the profile group the whole surface *is* the agent profile,// so the first entry is the "basic" tab, not "Agent Profile" again —// that broader name stays on the sidebar entry that opens the group.diff --git a/src/features/AgentVisibility/publishError.test.ts b/src/features/AgentVisibility/publishError.test.tsnew file mode 100644index 00000000000..48e3e9b9ce4--- /dev/null+++ b/src/features/AgentVisibility/publishError.test.ts@@ -0,0 +1,18 @@+import { describe, expect, it } from 'vitest';++import { getAgentPublishErrorKey } from './publishError';++describe('getAgentPublishErrorKey', () => {+ it('maps the fixed private-device precondition to actionable publish copy', () => {+ expect(+ getAgentPublishErrorKey({+ data: { errorData: { code: 'FixedAgentRequiresPublicWorkspaceDevice' } },+ }),+ ).toBe('agent.publishToWorkspaceErrorFixedPrivateDevice');+ });++ it('keeps unrelated publish failures on the generic fallback', () => {+ expect(getAgentPublishErrorKey({ data: { code: 'FORBIDDEN' } })).toBeUndefined();+ expect(getAgentPublishErrorKey(new Error('network failure'))).toBeUndefined();+ });+});diff --git a/src/features/AgentVisibility/publishError.ts b/src/features/AgentVisibility/publishError.tsnew file mode 100644index 00000000000..222ec40c9b3--- /dev/null+++ b/src/features/AgentVisibility/publishError.ts@@ -0,0 +1,11 @@+export type AgentPublishErrorKey = 'agent.publishToWorkspaceErrorFixedPrivateDevice';++/** The specific copy for a refused publish, when the server named a known reason. */+export const getAgentPublishErrorKey = (error: unknown): AgentPublishErrorKey | undefined => {+ if (typeof error !== 'object' || error === null) return;++ const data = (error as { data?: { errorData?: { code?: unknown } } }).data;+ if (data?.errorData?.code === 'FixedAgentRequiresPublicWorkspaceDevice') {+ return 'agent.publishToWorkspaceErrorFixedPrivateDevice';+ }+};diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentItem/useAgentVisibilityMenu.test.tsx b/src/features/AgentVisibility/useAgentVisibilityControl.test.tsxsimilarity index 55%rename from src/features/HomeSidebar/Body/Agent/List/AgentItem/useAgentVisibilityMenu.test.tsxrename to src/features/AgentVisibility/useAgentVisibilityControl.test.tsxindex 25b91d34838..7a952e13f4e 100644--- a/src/features/HomeSidebar/Body/Agent/List/AgentItem/useAgentVisibilityMenu.test.tsx+++ b/src/features/AgentVisibility/useAgentVisibilityControl.test.tsx@@ -1,9 +1,7 @@import { act, renderHook } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';-import { canGoNative } from '@/libs/contextMenu/canGoNative';--import { useAgentVisibilityMenu } from './useAgentVisibilityMenu';+import { useAgentVisibilityControl } from './useAgentVisibilityControl';const mocks = vi.hoisted(() => ({activeWorkspaceId: 'workspace-1' as string | null,@@ -11,6 +9,7 @@ const mocks = vi.hoisted(() => ({canEditResource: true,confirmModal: vi.fn(),publishAgentToWorkspace: vi.fn(),+ refreshAgentConfig: vi.fn(),refreshAgentList: vi.fn(),refreshWorkspaceUserPreference: vi.fn(),setAgentVisibility: vi.fn(),@@ -67,27 +66,23 @@ vi.mock('@/store/user/selectors', () => ({userProfileSelectors: { userId: (s: UserStateMock) => s.userId },}));-vi.mock('../../../../hooks', () => ({ useRevealSidebarSection: () => vi.fn() }));+vi.mock('@/features/HomeSidebar/hooks/useRevealSidebarSection', () => ({+ useRevealSidebarSection: () => vi.fn(),+}));-type Params = Parameters<typeof useAgentVisibilityMenu>[0];+vi.mock('@/store/agent', () => ({+ useAgentStore: (selector: (s: { internal_refreshAgentConfig: unknown }) => unknown) =>+ selector({ internal_refreshAgentConfig: mocks.refreshAgentConfig }),+}));++type Params = Parameters<typeof useAgentVisibilityControl>[0];const render = (params: Partial<Params> = {}) =>renderHook(() =>- useAgentVisibilityMenu({ id: 'agent-1', userId: 'me', visibility: 'private', ...params }),+ useAgentVisibilityControl({ id: 'agent-1', userId: 'me', visibility: 'private', ...params }),).result.current;-type CheckboxOption = {- checked: boolean;- desc: string;- key: string;- label: string;- onCheckedChange: (checked: boolean) => void;-};--const options = (menu: ReturnType<typeof useAgentVisibilityMenu>) =>- menu.options as unknown as CheckboxOption[];--describe('useAgentVisibilityMenu', () => {+describe('useAgentVisibilityControl', () => {beforeEach(() => {vi.clearAllMocks();mocks.activeWorkspaceId = 'workspace-1';@@ -95,50 +90,17 @@ describe('useAgentVisibilityMenu', () => {mocks.canEditResource = true;});- it('shows the current scope on the Visibility row and checks it in the options', () => {- const menu = render({ visibility: 'private' });-- expect(menu.canChange).toBe(true);- expect(menu.submenu).toMatchObject({- extra: 'agent.visibility.private',- key: 'visibility',- label: 'agent.visibility',+ it('reports the current scope and lets the creator change it', () => {+ expect(render({ visibility: 'private' })).toMatchObject({+ canChange: true,+ current: 'private',+ lockReason: undefined,});- expect(- options(menu).map(({ checked, desc, key, label }) => ({ checked, desc, key, label })),- ).toEqual([- {- checked: true,- desc: 'agent.visibility.privateDesc',- key: 'visibility-private',- label: 'agent.visibility.private',- },- {- checked: false,- desc: 'agent.visibility.workspaceDesc',- key: 'visibility-public',- label: 'agent.visibility.workspace',- },- ]);- });-- it('labels a published Agent as Workspace', () => {- const menu = render({ visibility: 'public' });-- expect(menu.submenu).toMatchObject({ extra: 'agent.visibility.workspace' });- expect(options(menu).find((o) => o.checked)?.key).toBe('visibility-public');- });-- it('stays eligible for the native desktop context menu', () => {- const menu = render();-- expect(canGoNative([menu.submenu])).toBe(true);+ expect(render({ visibility: 'public' })).toMatchObject({ canChange: true, current: 'public' });});it('confirms and publishes when Workspace is picked on a private Agent', async () => {- const menu = render({ visibility: 'private' });-- options(menu)[1].onCheckedChange(true);+ render({ visibility: 'private' }).select('public');expect(mocks.confirmModal).toHaveBeenCalledTimes(1);await act(async () => {@@ -147,14 +109,14 @@ describe('useAgentVisibilityMenu', () => {expect(mocks.publishAgentToWorkspace).toHaveBeenCalledWith('agent-1');expect(mocks.refreshAgentList).toHaveBeenCalled();+ // The settings page reads the agent store, so its scope must refresh too.+ expect(mocks.refreshAgentConfig).toHaveBeenCalledWith('agent-1');expect(mocks.refreshWorkspaceUserPreference).toHaveBeenCalled();expect(mocks.toastSuccess).toHaveBeenCalledWith('agent.publishToWorkspaceSuccess');});it('confirms and makes private when Private is picked on a published Agent', async () => {- const menu = render({ visibility: 'public' });-- options(menu)[0].onCheckedChange(true);+ render({ visibility: 'public' }).select('private');expect(mocks.confirmModal).toHaveBeenCalledTimes(1);await act(async () => {@@ -162,34 +124,41 @@ describe('useAgentVisibilityMenu', () => {});expect(mocks.setAgentVisibility).toHaveBeenCalledWith('agent-1', 'private');+ expect(mocks.refreshAgentConfig).toHaveBeenCalledWith('agent-1');});it('does nothing when the current scope is picked again', () => {- const menu = render({ visibility: 'private' });-- options(menu)[0].onCheckedChange(false);- options(menu)[0].onCheckedChange(true);+ render({ visibility: 'private' }).select('private');expect(mocks.confirmModal).not.toHaveBeenCalled();});- it("does not let a member change another member's published Agent", () => {- const menu = render({ userId: 'someone-else', visibility: 'public' });+ it("locks another member's published Agent and says why", () => {+ const control = render({ userId: 'someone-else', visibility: 'public' });- expect(menu).toEqual({ canChange: false, options: [], submenu: null });+ expect(control).toMatchObject({+ canChange: false,+ current: 'public',+ lockReason: 'notCreator',+ });+ control.select('private');+ expect(mocks.confirmModal).not.toHaveBeenCalled();});- it('is absent outside a workspace', () => {+ it('has no scope outside a workspace', () => {mocks.activeWorkspaceId = null;- expect(render().canChange).toBe(false);+ expect(render()).toMatchObject({ canChange: false, current: undefined });});- it('is absent on builtin agents', () => {- expect(render({ slug: 'inbox', visibility: 'public' }).canChange).toBe(false);+ it('locks builtin agents', () => {+ expect(render({ slug: 'inbox', visibility: 'public' })).toMatchObject({+ canChange: false,+ lockReason: 'builtin',+ });});- it('is absent when the viewer cannot configure the Agent', () => {+ it('is read-only when the viewer cannot configure the Agent', () => {mocks.canEditResource = false;expect(render().canChange).toBe(false);diff --git a/src/features/AgentVisibility/useAgentVisibilityControl.tsx b/src/features/AgentVisibility/useAgentVisibilityControl.tsxnew file mode 100644index 00000000000..6ea378a15ae--- /dev/null+++ b/src/features/AgentVisibility/useAgentVisibilityControl.tsx@@ -0,0 +1,155 @@+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';+import { type SidebarVisibility } from '@lobechat/types';+import { confirmModal, toast } from '@lobehub/ui';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { getAgentPublishErrorKey } from '@/features/AgentVisibility/publishError';+import { useRevealSidebarSection } from '@/features/HomeSidebar/hooks/useRevealSidebarSection';+import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';+import VisibilityConfirmContent from '@/features/VisibilityConfirmContent';+import { usePermission } from '@/hooks/usePermission';+import { agentService } from '@/services/agent';+import { useAgentStore } from '@/store/agent';+import { useHomeStore } from '@/store/home';+import { useUserStore } from '@/store/user';+import { userProfileSelectors } from '@/store/user/selectors';++const BUILTIN_SLUGS = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));++export type AgentVisibilityOption = 'private' | 'public';++/** Why the scope is shown but cannot be switched. */+export type AgentVisibilityLockReason = 'builtin' | 'notCreator';++interface UseAgentVisibilityControlParams {+ id: string;+ slug?: string | null;+ userId?: string | null;+ visibility?: SidebarVisibility;+}++export interface AgentVisibilityControl {+ /** Whether the viewer may switch this Agent between Private and Workspace. */+ canChange: boolean;+ /** The current scope; undefined outside a workspace or before the row loads. */+ current?: AgentVisibilityOption;+ /** Set when a workspace Agent's scope is visible but locked for this viewer. */+ lockReason?: AgentVisibilityLockReason;+ /** Confirm, then switch to `next`. Picking the current scope is a no-op. */+ select: (next: AgentVisibilityOption) => void;+}++/**+ * Agent visibility as a property: Private (only the creator) or Workspace.+ *+ * Who may switch is enforced by the server with the same rules: only inside a+ * workspace, never on builtin agents, a private Agent can be published by+ * whoever sees it (its creator), and a published Agent only goes back to+ * private by its creator — a workspace owner demoting someone else's Agent+ * would appropriate it.+ */+export const useAgentVisibilityControl = ({+ id,+ slug,+ userId,+ visibility,+}: UseAgentVisibilityControlParams): AgentVisibilityControl => {+ const { t } = useTranslation(['chat', 'common']);++ const activeWorkspaceId = useActiveWorkspaceId();+ const currentUserId = useUserStore(userProfileSelectors.userId);+ const refreshWorkspaceUserPreference = useUserStore((s) => s.refreshWorkspaceUserPreference);+ const refreshAgentList = useHomeStore((s) => s.refreshAgentList);+ const refreshAgentConfig = useAgentStore((s) => s.internal_refreshAgentConfig);+ const revealSidebarSection = useRevealSidebarSection();++ const { allowed: canEdit } = usePermission('edit_own_content');+ const { canEditResource, isAccessResolved } = useResourceAccess('agent', id);+ const canConfigure = canEdit && isAccessResolved && canEditResource;++ const isBuiltin = !!slug && BUILTIN_SLUGS.has(slug);+ const isCreator = !!currentUserId && userId === currentUserId;+ const current: AgentVisibilityOption | undefined = !activeWorkspaceId+ ? undefined+ : visibility === 'private'+ ? 'private'+ : visibility === 'public'+ ? 'public'+ : undefined;++ const lockReason: AgentVisibilityLockReason | undefined = !current+ ? undefined+ : isBuiltin+ ? 'builtin'+ : current === 'public' && !isCreator+ ? 'notCreator'+ : undefined;++ const canChange = !!current && canConfigure && !lockReason;++ // The settings page reads the Agent from the agent store, the sidebar from+ // the home list — refresh both so neither keeps the old scope.+ const refresh = useCallback(+ () => Promise.all([refreshAgentList(), refreshAgentConfig(id)]),+ [id, refreshAgentConfig, refreshAgentList],+ );++ const publish = useCallback(() => {+ confirmModal({+ cancelText: t('cancel', { ns: 'common' }),+ content: <VisibilityConfirmContent variant="publish" />,+ okText: t('agent.publishToWorkspace'),+ onOk: async () => {+ try {+ await agentService.publishAgentToWorkspace(id);+ // Publishing moves a private pin into this member's personal pin+ // list server-side.+ await Promise.all([refresh(), refreshWorkspaceUserPreference()]);+ 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'),+ });+ }, [id, refresh, refreshWorkspaceUserPreference, revealSidebarSection, t]);++ const makePrivate = useCallback(() => {+ confirmModal({+ cancelText: t('cancel', { ns: 'common' }),+ content: <VisibilityConfirmContent variant="makePrivate" />,+ okButtonProps: { danger: true },+ okText: t('makePrivate.confirm.ok', { ns: 'common' }),+ onOk: async () => {+ try {+ await agentService.setAgentVisibility(id, 'private');+ await refresh();+ revealSidebarSection('agent');+ toast.success(t('makePrivate.success', { ns: 'common' }));+ } catch (error) {+ console.error('Failed to make agent private:', error);+ toast.error(t('makePrivate.error', { ns: 'common' }));+ }+ },+ title: t('makePrivate.confirm.title', { ns: 'common' }),+ });+ }, [id, refresh, revealSidebarSection, t]);++ const select = useCallback(+ (next: AgentVisibilityOption) => {+ if (!canChange || next === current) return;+ if (next === 'public') publish();+ else makePrivate();+ },+ [canChange, current, makePrivate, publish],+ );++ return { canChange, current, lockReason, select };+};diff --git a/src/features/GroupPermission/PermissionForm.tsx b/src/features/GroupPermission/PermissionForm.tsxindex 7afd8dda231..69de620a912 100644--- a/src/features/GroupPermission/PermissionForm.tsx+++ b/src/features/GroupPermission/PermissionForm.tsx@@ -1,12 +1,21 @@'use client';import type { AgentModelSelectionPolicy, AgentTopicSharePolicy } from '@lobechat/types';-import { Alert, createStaticStyles, Empty, Icon } from '@lobehub/ui';+import { Alert, Button, createStaticStyles, Empty, Icon } from '@lobehub/ui';import { Form, type FormGroupItem, useForm } from '@lobehub/ui/form';-import { Bot, InfoIcon, LockIcon, MonitorSmartphone, Share2, UsersIcon } from 'lucide-react';+import {+ Bot,+ InfoIcon,+ LockIcon,+ MonitorSmartphone,+ Share2,+ UserRoundPlus,+ UsersIcon,+} from 'lucide-react';import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';+import { useAgentGroupTransferToMemberAction } from '@/business/client/hooks/useAgentGroupTransferToMemberAction';import AsyncError from '@/components/AsyncError';import { FORM_STYLE } from '@/const/layoutTokens';import PolicySelect, { type PolicyOption } from '@/features/ResourcePermission/PolicySelect';@@ -33,7 +42,7 @@ interface PermissionFormProps {}const PermissionForm = memo<PermissionFormProps>(({ groupId }) => {- const { t } = useTranslation('setting');+ const { t } = useTranslation(['setting', 'agent']);const {accessError,accessLevel,@@ -55,6 +64,9 @@ const PermissionForm = memo<PermissionFormProps>(({ groupId }) => {topicSharePolicy,} = useGroupPermission(groupId);const form = useForm();+ // Handing the group to another member used to sit in the sidebar row menu;+ // null when the viewer may not start it (or the deployment has no such flow).+ const openTransfer = useAgentGroupTransferToMemberAction(groupId);const accessOptions = useAccessLevelOptions({ accessLevel, isPrivate });@@ -254,6 +266,28 @@ const PermissionForm = memo<PermissionFormProps>(({ groupId }) => {}: undefined;+ const ownershipGroup: FormGroupItem | undefined = openTransfer+ ? {+ children: [+ {+ avatar: (+ <span className={styles.rowIcon}>+ <Icon icon={UserRoundPlus} size={16} />+ </span>+ ),+ children: (+ <Button onClick={openTransfer}>+ {t('transfer.transferToMember', { ns: 'agent' })}+ </Button>+ ),+ desc: t('permission.page.groupTransferDesc'),+ label: t('permission.page.transferLabel'),+ },+ ],+ title: t('permission.page.ownershipGroup'),+ }+ : undefined;+return (<>{/* A failed permission fetch must not read as "this group has no member@@ -275,9 +309,13 @@ const PermissionForm = memo<PermissionFormProps>(({ groupId }) => {<Formcollapsible={false}form={form}- items={[...(memberGroup ? [memberGroup] : []), ...(configGroup ? [configGroup] : [])]}itemsType={'group'}variant={'filled'}+ items={[+ ...(memberGroup ? [memberGroup] : []),+ ...(configGroup ? [configGroup] : []),+ ...(ownershipGroup ? [ownershipGroup] : []),+ ]}{...FORM_STYLE}/></>diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentGroupItem/useDropdownMenu.test.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentGroupItem/useDropdownMenu.test.tsxindex 14d74c97ed7..dfae94fdbc8 100644--- a/src/features/HomeSidebar/Body/Agent/List/AgentGroupItem/useDropdownMenu.test.tsx+++ b/src/features/HomeSidebar/Body/Agent/List/AgentGroupItem/useDropdownMenu.test.tsx@@ -8,12 +8,14 @@ const mocks = vi.hoisted(() => ({canEdit: true,canEditResource: true,canManage: true,+ canManageResource: false,home: {duplicateAgentGroup: vi.fn(),pinAgentGroup: vi.fn(),removeAgentGroup: vi.fn(),},isSidebarItemVisible: vi.fn(() => true),+ navigate: vi.fn(),openAgentInNewWindow: vi.fn(),setSidebarItemVisible: vi.fn(),toastError: vi.fn(),@@ -33,14 +35,18 @@ vi.mock('@/business/client/hooks/useAgentGroupTransferMenuItem', () => ({useAgentGroupTransferMenuItem: () => null,}));-vi.mock('@/business/client/hooks/useAgentGroupTransferToMemberMenuItem', () => ({- useAgentGroupTransferToMemberMenuItem: () => null,-}));-vi.mock('@/features/EditingPopover/store', () => ({ openEditingPopover: vi.fn() }));vi.mock('@/features/ResourcePermission/useResourceAccess', () => ({- useResourceAccess: () => ({ canEditResource: mocks.canEditResource, isAccessResolved: true }),+ useResourceAccess: () => ({+ canEditResource: mocks.canEditResource,+ canManageResource: mocks.canManageResource,+ isAccessResolved: true,+ }),+}));++vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({+ useWorkspaceAwareNavigate: () => mocks.navigate,}));vi.mock('@/hooks/usePermission', () => ({@@ -99,6 +105,7 @@ describe('useGroupDropdownMenu', () => {mocks.canEdit = true;mocks.canEditResource = true;mocks.canManage = true;+ mocks.canManageResource = false;mocks.isSidebarItemVisible.mockReturnValue(true);});@@ -126,6 +133,27 @@ describe('useGroupDropdownMenu', () => {expect(getMenuKeys(result.current()).slice(0, 3)).toEqual(['pin', 'hideFromSidebar', 'rename']);});+ it('offers the creator or an owner a shortcut to the group Permissions settings', () => {+ mocks.activeWorkspaceId = 'ws_1';+ mocks.canManageResource = true;+ const { result } = renderGroupMenu();++ expect(getMenuKeys(result.current())).toContain('permission');++ const entry = (result.current() ?? []).find(+ (item) => item && typeof item === 'object' && 'key' in item && item.key === 'permission',+ ) as { onClick: (info: unknown) => void };+ entry.onClick({ domEvent: { stopPropagation: vi.fn() } });+ expect(mocks.navigate).toHaveBeenCalledWith('/group/cg_1/permission');+ });++ it('keeps the Permissions shortcut from members who do not manage the group', () => {+ mocks.activeWorkspaceId = 'ws_1';+ const { result } = renderGroupMenu();++ expect(getMenuKeys(result.current())).not.toContain('permission');+ });+it('offers hide to a member who cannot configure the group', () => {mocks.canEditResource = false;const { result } = renderGroupMenu();diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentGroupItem/useDropdownMenu.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentGroupItem/useDropdownMenu.tsxindex 1ec10b24aaa..9dde5e598ed 100644--- a/src/features/HomeSidebar/Body/Agent/List/AgentGroupItem/useDropdownMenu.tsx+++ b/src/features/HomeSidebar/Body/Agent/List/AgentGroupItem/useDropdownMenu.tsx@@ -8,6 +8,7 @@ import {PictureInPicture2Icon,Pin,PinOff,+ ShieldIcon,Trash,} from 'lucide-react';import { useMemo } from 'react';@@ -15,9 +16,9 @@ import { useTranslation } from 'react-i18next';import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { useAgentGroupTransferMenuItem } from '@/business/client/hooks/useAgentGroupTransferMenuItem';-import { useAgentGroupTransferToMemberMenuItem } from '@/business/client/hooks/useAgentGroupTransferToMemberMenuItem';import { openEditingPopover } from '@/features/EditingPopover/store';import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { usePermission } from '@/hooks/usePermission';import { useResourceManageable } from '@/hooks/useResourceManageable';import { useGlobalStore } from '@/store/global';@@ -52,10 +53,13 @@ export const useGroupDropdownMenu = ({userId,visibility,}: UseGroupDropdownMenuParams): (() => DropdownItem[]) => {- const { t } = useTranslation(['chat', 'common']);+ const { t } = useTranslation(['chat', 'common', 'setting']);const { allowed: canEdit } = usePermission('edit_own_content');- const { canEditResource, isAccessResolved } = useResourceAccess('agentGroup', id);+ const { canEditResource, canManageResource, isAccessResolved } = useResourceAccess(+ 'agentGroup',+ id,+ );const canConfigure = canEdit && isAccessResolved && canEditResource;const canManage = useResourceManageable(userId);@@ -72,11 +76,7 @@ export const useGroupDropdownMenu = ({memberAvatars,title,});- const transferToMemberItem = useAgentGroupTransferToMemberMenuItem(id, {- avatar,- backgroundColor,- title,- });+ const navigate = useWorkspaceAwareNavigate();const activeWorkspaceId = useActiveWorkspaceId();// Workspace: personal pin for every member + owner/admin team pin on public@@ -173,11 +173,25 @@ export const useGroupDropdownMenu = ({},sfSymbol: 'macwindow.badge.plus',},- ...(canConfigure && (transferMenuItems?.length || transferToMemberItem)+ ...(canConfigure && transferMenuItems?.length+ ? [{ type: 'divider' as const }, ...transferMenuItems]+ : []),+ // Member permissions and the handover to a member live in the group's+ // Permissions settings; the row keeps one shortcut there for the+ // creator and workspace owners, like Agent rows.+ ...(activeWorkspaceId && canConfigure && canManageResource? [{ type: 'divider' as const },- ...(transferMenuItems ?? []),- ...(transferToMemberItem ? [transferToMemberItem] : []),+ {+ icon: <Icon icon={ShieldIcon} />,+ key: 'permission',+ label: t('permission.page.entry', { ns: 'setting' }),+ onClick: ({ domEvent }: any) => {+ domEvent?.stopPropagation();+ navigate(`/group/${id}/permission`);+ },+ sfSymbol: 'lock.shield',+ },]: []),...(canConfigure && canManage@@ -231,7 +245,8 @@ export const useGroupDropdownMenu = ({openAgentInNewWindow,removeAgentGroup,transferMenuItems,- transferToMemberItem,+ canManageResource,+ navigate,],);};diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentItem/VisibilityLockAction.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentItem/VisibilityLockAction.tsxindex 04df1c1b64c..2c771180ab0 100644--- a/src/features/HomeSidebar/Body/Agent/List/AgentItem/VisibilityLockAction.tsx+++ b/src/features/HomeSidebar/Body/Agent/List/AgentItem/VisibilityLockAction.tsx@@ -1,30 +1,42 @@-import { ActionIcon, type DropdownItem, DropdownMenu } from '@lobehub/ui';+import { ActionIcon } from '@lobehub/ui';import { LockIcon } from 'lucide-react';-import { memo } from 'react';+import { memo, type MouseEvent, useCallback } from 'react';import { useTranslation } from 'react-i18next';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+interface VisibilityLockActionProps {- options: DropdownItem[];+ agentId: string;}/*** The row's lock, as a door rather than a badge: on hover it sits beside the- * "…" trigger and opens the same Private / Workspace choice as the menu's- * Visibility row, so the scope can be changed without scrolling the menu.+ * "…" trigger and opens the Agent's Permissions settings, where the scope is+ * changed — the same place the row menu's settings shortcut leads.*/-const VisibilityLockAction = memo<VisibilityLockActionProps>(({ options }) => {+const VisibilityLockAction = memo<VisibilityLockActionProps>(({ agentId }) => {const { t } = useTranslation('chat');+ const navigate = useWorkspaceAwareNavigate();++ const handleClick = useCallback(+ (event: MouseEvent) => {+ // The row is a link to the chat; the lock goes to settings instead.+ event.preventDefault();+ event.stopPropagation();+ navigate(`/agent/${agentId}/permission`);+ },+ [agentId, navigate],+ );return (- <DropdownMenu items={options}>- <ActionIcon- aria-label={t('agent.visibility.change')}- data-testid="sidebar-visibility-lock"- icon={LockIcon}- size={'small'}- title={t('agent.visibility.change')}- />- </DropdownMenu>+ <ActionIcon+ aria-label={t('agent.visibility.change')}+ data-testid="sidebar-visibility-lock"+ icon={LockIcon}+ size={'small'}+ title={t('agent.visibility.change')}+ onClick={handleClick}+ />);});diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentItem/agentMenuVisibility.test.ts b/src/features/HomeSidebar/Body/Agent/List/AgentItem/agentMenuVisibility.test.tsindex 3d1be6383ac..667e31e481f 100644--- a/src/features/HomeSidebar/Body/Agent/List/AgentItem/agentMenuVisibility.test.ts+++ b/src/features/HomeSidebar/Body/Agent/List/AgentItem/agentMenuVisibility.test.ts@@ -2,22 +2,7 @@import { describe, expect, it } from 'vitest';-import { getAgentPublishErrorKey, shouldShowAgentDeleteMenuItem } from './agentMenuVisibility';--describe('getAgentPublishErrorKey', () => {- it('maps the fixed private-device precondition to actionable publish copy', () => {- expect(- getAgentPublishErrorKey({- data: { errorData: { code: 'FixedAgentRequiresPublicWorkspaceDevice' } },- }),- ).toBe('agent.publishToWorkspaceErrorFixedPrivateDevice');- });-- it('keeps unrelated publish failures on the generic fallback', () => {- expect(getAgentPublishErrorKey({ data: { code: 'FORBIDDEN' } })).toBeUndefined();- expect(getAgentPublishErrorKey(new Error('network failure'))).toBeUndefined();- });-});+import { shouldShowAgentDeleteMenuItem } from './agentMenuVisibility';describe('shouldShowAgentDeleteMenuItem', () => {it('shows Delete only when the agent can be edited and managed', () => {diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentItem/agentMenuVisibility.ts b/src/features/HomeSidebar/Body/Agent/List/AgentItem/agentMenuVisibility.tsindex 14ad2a52f18..ad52f9c4ddf 100644--- a/src/features/HomeSidebar/Body/Agent/List/AgentItem/agentMenuVisibility.ts+++ b/src/features/HomeSidebar/Body/Agent/List/AgentItem/agentMenuVisibility.ts@@ -3,16 +3,5 @@ interface AgentDeleteMenuVisibility {canManage: boolean;}-export type AgentPublishErrorKey = 'agent.publishToWorkspaceErrorFixedPrivateDevice';--export const getAgentPublishErrorKey = (error: unknown): AgentPublishErrorKey | undefined => {- if (typeof error !== 'object' || error === null) return;-- const data = (error as { data?: { errorData?: { code?: unknown } } }).data;- if (data?.errorData?.code === 'FixedAgentRequiresPublicWorkspaceDevice') {- return 'agent.publishToWorkspaceErrorFixedPrivateDevice';- }-};-export const shouldShowAgentDeleteMenuItem = ({ canEdit, canManage }: AgentDeleteMenuVisibility) =>canEdit && canManage;diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsxindex b9e6486574b..13e358197b3 100644--- a/src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsx+++ b/src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsx@@ -12,6 +12,7 @@ import AgentAvatar, { isGeneratedAgentAvatar } from '@/components/AgentAvatar';import PrivateLockIcon from '@/components/PrivateLockIcon';import { useAgentAvatarActivity } from '@/features/AgentAvatarActivity/useAgentAvatarActivity';import AgentProfilePopup from '@/features/AgentProfileCard/AgentProfilePopup';+import { useAgentVisibilityControl } from '@/features/AgentVisibility/useAgentVisibilityControl';import NavItem from '@/features/NavPanel/components/NavItem';import WorkspaceLink from '@/features/Workspace/WorkspaceLink';import { usePrefetchAgent } from '@/hooks/usePrefetchAgent';@@ -24,7 +25,6 @@ import { useAgentModal } from '../../ModalProvider';import { useSidebarPinState } from '../../useSidebarPinState';import Actions from '../Item/Actions';import { usePreservedAgentUrl } from '../usePreservedAgentUrl';-import { useAgentVisibilityMenu } from './useAgentVisibilityMenu';import { useAgentDropdownMenu } from './useDropdownMenu';import VisibilityLockAction from './VisibilityLockAction';@@ -237,10 +237,15 @@ const AgentItem = memo<AgentItemProps>(({ item, style, className, onNavigate, sevisibility,});- // The lock is the same door as the menu's Visibility row: whoever may change- // the scope can open it from the lock on hover.- const visibilityMenu = useAgentVisibilityMenu({ id, slug, userId, visibility });- const showVisibilityLock = isPrivate && visibilityMenu.canChange;+ // Whoever may change the scope gets the lock on hover, a shortcut into the+ // Agent's Permissions settings where visibility now lives.+ const { canChange: canChangeVisibility } = useAgentVisibilityControl({+ id,+ slug,+ userId,+ visibility,+ });+ const showVisibilityLock = isPrivate && canChangeVisibility;return (<WorkspaceLink@@ -264,7 +269,7 @@ const AgentItem = memo<AgentItemProps>(({ item, style, className, onNavigate, se// so the resting lock fades under the clickable one.showVisibilityLock ? (<>- <VisibilityLockAction options={visibilityMenu.options} />+ <VisibilityLockAction agentId={id} /><Actions dropdownMenu={dropdownMenu} /></>) : (diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentItem/useAgentVisibilityMenu.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentItem/useAgentVisibilityMenu.tsxdeleted file mode 100644index ff25cf0a184..00000000000--- a/src/features/HomeSidebar/Body/Agent/List/AgentItem/useAgentVisibilityMenu.tsx+++ /dev/null@@ -1,173 +0,0 @@-import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';-import { type SidebarVisibility } from '@lobechat/types';-import { confirmModal, type DropdownItem, Icon, toast } from '@lobehub/ui';-import { GlobeIcon, LockIcon } from 'lucide-react';-import { useCallback, useMemo } from 'react';-import { useTranslation } from 'react-i18next';--import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';-import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';-import VisibilityConfirmContent from '@/features/VisibilityConfirmContent';-import { usePermission } from '@/hooks/usePermission';-import { agentService } from '@/services/agent';-import { useHomeStore } from '@/store/home';-import { useUserStore } from '@/store/user';-import { userProfileSelectors } from '@/store/user/selectors';--import { useRevealSidebarSection } from '../../../../hooks';-import { getAgentPublishErrorKey } from './agentMenuVisibility';--const BUILTIN_SLUGS = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));--type AgentVisibilityOption = 'private' | 'public';--interface UseAgentVisibilityMenuParams {- id: string;- slug?: string | null;- userId?: string | null;- visibility?: SidebarVisibility;-}--export interface AgentVisibilityMenu {- /** Whether the viewer may switch this Agent between Private and Workspace. */- canChange: boolean;- /** The two scope options, the current one checked. Empty when `canChange` is false. */- options: DropdownItem[];- /** The "Visibility" row for the Agent menu, carrying the current value. */- submenu: DropdownItem | null;-}--/**- * Agent visibility as a property rather than a one-way action: the menu row- * shows the current scope, and the same two options open from the row's lock.- *- * Who may switch is unchanged from the old Publish / Make private actions, and- * the server enforces the same rules: only inside a workspace, never on builtin- * agents, a private Agent can be published by whoever sees it (its creator),- * and a published Agent only goes back to private by its creator — a workspace- * owner demoting someone else's Agent would appropriate it.- */-export const useAgentVisibilityMenu = ({- id,- slug,- userId,- visibility,-}: UseAgentVisibilityMenuParams): AgentVisibilityMenu => {- const { t } = useTranslation(['chat', 'common']);-- const activeWorkspaceId = useActiveWorkspaceId();- const currentUserId = useUserStore(userProfileSelectors.userId);- const refreshWorkspaceUserPreference = useUserStore((s) => s.refreshWorkspaceUserPreference);- const refreshAgentList = useHomeStore((s) => s.refreshAgentList);- const revealSidebarSection = useRevealSidebarSection();-- const { allowed: canEdit } = usePermission('edit_own_content');- const { canEditResource, isAccessResolved } = useResourceAccess('agent', id);- const canConfigure = canEdit && isAccessResolved && canEditResource;-- const isBuiltin = !!slug && BUILTIN_SLUGS.has(slug);- const isCreator = !!currentUserId && userId === currentUserId;- const current: AgentVisibilityOption | undefined =- visibility === 'private' ? 'private' : visibility === 'public' ? 'public' : undefined;-- const canChange =- Boolean(activeWorkspaceId) &&- canConfigure &&- !isBuiltin &&- (current === 'private' || (current === 'public' && isCreator));-- const publish = useCallback(() => {- confirmModal({- cancelText: t('cancel', { ns: 'common' }),- content: <VisibilityConfirmContent variant="publish" />,- okText: t('agent.publishToWorkspace'),- onOk: async () => {- try {- await agentService.publishAgentToWorkspace(id);- // Publishing moves a private pin into this member's personal pin- // list server-side.- await Promise.all([refreshAgentList(), refreshWorkspaceUserPreference()]);- 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'),- });- }, [id, refreshAgentList, refreshWorkspaceUserPreference, revealSidebarSection, t]);-- const makePrivate = useCallback(() => {- confirmModal({- cancelText: t('cancel', { ns: 'common' }),- content: <VisibilityConfirmContent variant="makePrivate" />,- okButtonProps: { danger: true },- okText: t('makePrivate.confirm.ok', { ns: 'common' }),- onOk: async () => {- try {- await agentService.setAgentVisibility(id, 'private');- await refreshAgentList();- revealSidebarSection('agent');- toast.success(t('makePrivate.success', { ns: 'common' }));- } catch (error) {- console.error('Failed to make agent private:', error);- toast.error(t('makePrivate.error', { ns: 'common' }));- }- },- title: t('makePrivate.confirm.title', { ns: 'common' }),- });- }, [id, refreshAgentList, revealSidebarSection, t]);-- return useMemo(() => {- if (!canChange || !current) return { canChange: false, options: [], submenu: null };-- const option = (- value: AgentVisibilityOption,- icon: typeof LockIcon,- onSelect: () => void,- ): DropdownItem => {- const checked = current === value;-- // A checkbox item puts the check on the right of the scope icon and- // keeps the menu eligible for the native desktop context menu.- return {- checked,- // Base UI keeps checkbox menus open by default; a scope pick is final.- closeOnClick: true,- desc: t(- value === 'private' ? 'agent.visibility.privateDesc' : 'agent.visibility.workspaceDesc',- ),- icon,- key: `visibility-${value}`,- label: t(value === 'private' ? 'agent.visibility.private' : 'agent.visibility.workspace'),- // Picking the current scope is a no-op, not a second confirmation.- onCheckedChange: (next: boolean) => {- if (next && !checked) onSelect();- },- type: 'checkbox',- } as DropdownItem;- };-- const options = [- option('private', LockIcon, makePrivate),- option('public', GlobeIcon, publish),- ];-- const submenu = {- children: options,- // The current value sits in the row, so the reader does not need to- // open the submenu to learn which scope the Agent is in.- extra: t(current === 'private' ? 'agent.visibility.private' : 'agent.visibility.workspace'),- icon: <Icon icon={current === 'private' ? LockIcon : GlobeIcon} />,- key: 'visibility',- label: t('agent.visibility'),- sfSymbol: current === 'private' ? 'lock' : 'globe',- } as DropdownItem;-- return { canChange: true, options, submenu };- }, [canChange, current, makePrivate, publish, t]);-};diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.test.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.test.tsxindex 01e7700f19a..03381381f49 100644--- a/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.test.tsx+++ b/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.test.tsx@@ -489,7 +489,6 @@ describe('useAgentDropdownMenu', () => {'copy-agent','divider','permission',- 'visibility','divider','delete',]);@@ -542,6 +541,9 @@ describe('useAgentDropdownMenu', () => {) as { onClick: (info: { domEvent: { stopPropagation: () => void } }) => void } | undefined;expect(permissionItem).toBeTruthy();+ expect((permissionItem as unknown as { label: string }).label).toBe(+ 'permission.page.agentEntry',+ );permissionItem?.onClick({ domEvent: { stopPropagation: vi.fn() } });diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.tsxindex 666e996a41e..178786b07d2 100644--- a/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.tsx+++ b/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.tsx@@ -19,16 +19,15 @@ import {Pin,PinOff,Settings2Icon,+ ShieldIcon,TagIcon,Trash,- UsersIcon,} from 'lucide-react';import { useMemo } from 'react';import { useTranslation } from 'react-i18next';import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { useAgentTransferMenuItem } from '@/business/client/hooks/useAgentTransferMenuItem';-import { useAgentTransferToMemberMenuItem } from '@/business/client/hooks/useAgentTransferToMemberMenuItem';import { openRenameModal } from '@/components/RenameModal';import { confirmRemoveAgent } from '@/features/AgentDeleteConfirm';import { useOptionalAgentModal } from '@/features/HomeSidebar/Body/Agent/ModalProvider';@@ -44,7 +43,6 @@ import { getDeleteErrorMessageKey } from '@/utils/forbiddenError';import { useSidebarItemVisibility } from '../../useSidebarItemVisibility';import { useSidebarPinMenuItems } from '../../useSidebarPinMenuItems';-import { useAgentVisibilityMenu } from './useAgentVisibilityMenu';interface UseAgentDropdownMenuParams {avatar?: string;@@ -128,7 +126,6 @@ export const useAgentDropdownMenu = ({const activeWorkspaceId = useActiveWorkspaceId();const { isSidebarItemVisible, setSidebarItemVisible } = useSidebarItemVisibility();const isShownInSidebar = isSidebarItemVisible({ id, slug, type: 'agent', userId });- const visibilityMenu = useAgentVisibilityMenu({ id, slug, userId, visibility });// Member Permissions only gate Agent configuration. Workspace-level list// organization (pin/group) and duplication remain available to members.@@ -165,16 +162,7 @@ export const useAgentDropdownMenu = ({},{ userId, visibility },);- // Ownership handover to a workspace member (recipient must accept) — a- // separate entry from the cross-scope "Move to…" above.- const agentTransferToMemberItem = useAgentTransferToMemberMenuItem(- id,- { avatar, backgroundColor, title },- { userId, visibility },- );-const transferMenuItems = isInbox ? null : agentTransferMenuItems;- const transferToMemberItem = isInbox ? null : agentTransferToMemberItem;const canManagePermission = !isInbox && canManageResource;const copyAgentIdItem = useCopyAgentIdMenuItem(id);@@ -450,30 +438,25 @@ export const useAgentDropdownMenu = ({...(canConfigure && transferMenuItems?.length ? transferMenuItems : []),...(canConfigure? [- // Permissions live on their own page now — the sidebar keeps a- // shortcut so creators and workspace owners don't have to open- // the Agent first.+ // Member permissions, visibility and the handover to a member+ // are low-frequency management: they live in the Agent's+ // settings, and the row keeps one shortcut into that section+ // for creators and workspace owners....(activeWorkspaceId && canManagePermission? [{ type: 'divider' as const },{- icon: <Icon icon={UsersIcon} />,+ icon: <Icon icon={ShieldIcon} />,key: 'permission',- label: t('permission.page.entry', { ns: 'setting' }),+ label: t('permission.page.agentEntry', { ns: 'setting' }),onClick: ({ domEvent }: any) => {domEvent?.stopPropagation();navigate(`/agent/${id}/permission`);},- sfSymbol: 'person.2',+ sfSymbol: 'lock.shield',},]: []),- // Visibility is a property: the row carries the current scope- // and opens Private / Workspace, replacing the one-way- // "Publish to Workspace" and "Make private" actions.- ...(visibilityMenu.submenu ? [visibilityMenu.submenu] : []),- // Under Visibility: hand ownership to a member.- ...(transferToMemberItem ? [transferToMemberItem] : []),...(canDelete? [{ type: 'divider' as const },@@ -515,7 +498,6 @@ export const useAgentDropdownMenu = ({navigate,pinned,id,- avatar,title,name,pinAgent,@@ -536,8 +518,6 @@ export const useAgentDropdownMenu = ({isDefault,openCreateGroupModal,transferMenuItems,- transferToMemberItem,- visibilityMenu,isShownInSidebar,setSidebarItemVisible,t,diff --git a/src/features/PrivateAgentLinkNotice/usePublishAgentToWorkspace.tsx b/src/features/PrivateAgentLinkNotice/usePublishAgentToWorkspace.tsxindex 8d521387c0d..67b362877b3 100644--- a/src/features/PrivateAgentLinkNotice/usePublishAgentToWorkspace.tsx+++ b/src/features/PrivateAgentLinkNotice/usePublishAgentToWorkspace.tsx@@ -2,7 +2,7 @@ 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 { getAgentPublishErrorKey } from '@/features/AgentVisibility/publishError';import { useRevealSidebarSection } from '@/features/HomeSidebar/hooks/useRevealSidebarSection';import VisibilityConfirmContent from '@/features/VisibilityConfirmContent';import { agentService } from '@/services/agent';diff --git a/src/routes/(main)/agent/profile/features/Header/index.test.tsx b/src/routes/(main)/agent/profile/features/Header/index.test.tsxindex d719402e7d4..7c6c32dd3df 100644--- a/src/routes/(main)/agent/profile/features/Header/index.test.tsx+++ b/src/routes/(main)/agent/profile/features/Header/index.test.tsx@@ -407,7 +407,7 @@ describe('Agent profile Header', () => {render(<Header />);const settings = screen.getByRole('button', { name: 'advancedSettings' });- const permissionEntry = screen.getByRole('button', { name: 'permission.page.entry' });+ const permissionEntry = screen.getByRole('button', { name: 'permission.page.agentEntry' });expect(settings).toBeDisabled();expect(permissionEntry).toBeDisabled();@@ -450,7 +450,7 @@ describe('Agent profile Header', () => {render(<Header />);expect(screen.queryByRole('button', { name: 'advancedSettings' })).toBeNull();- expect(screen.queryByRole('button', { name: 'permission.page.entry' })).toBeNull();+ expect(screen.queryByRole('button', { name: 'permission.page.agentEntry' })).toBeNull();});it('shows workspace resource permission controls for the LobeAI inbox agent', () => {@@ -459,7 +459,7 @@ describe('Agent profile Header', () => {render(<Header />);- expect(screen.getByRole('button', { name: 'permission.page.entry' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'permission.page.agentEntry' })).toBeInTheDocument();expect(screen.getByTestId('access-level-resource-id')).toHaveTextContent('agent-1');});@@ -467,7 +467,7 @@ describe('Agent profile Header', () => {vi.stubGlobal('__MOBILE__', true);render(<Header />);- fireEvent.click(screen.getByRole('button', { name: 'permission.page.entry' }));+ fireEvent.click(screen.getByRole('button', { name: 'permission.page.agentEntry' }));expect(mocks.navigate).toHaveBeenCalledWith('/agent/agent-1/permission');});@@ -478,7 +478,7 @@ describe('Agent profile Header', () => {render(<Header />);- expect(screen.getByRole('button', { name: 'permission.page.entry' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'permission.page.agentEntry' })).toBeInTheDocument();// Member access is meaningless while private, so the tag stays unbound.expect(screen.getByTestId('access-level-resource-id')).toHaveTextContent('');});diff --git a/src/routes/(main)/agent/profile/features/Header/index.tsx b/src/routes/(main)/agent/profile/features/Header/index.tsxindex 808f9f335a6..4111b220c22 100644--- a/src/routes/(main)/agent/profile/features/Header/index.tsx+++ b/src/routes/(main)/agent/profile/features/Header/index.tsx@@ -309,7 +309,7 @@ const Header = memo<HeaderProps>(({ active = 'profile' }) => {disabled: !canConfigure,icon: <Icon icon={UsersIcon} />,key: 'permission',- label: t('permission.page.entry', { ns: 'setting' }),+ label: t('permission.page.agentEntry', { ns: 'setting' }),onClick: () => {if (!canConfigure) return;if (activeAgentId) navigate(`/agent/${activeAgentId}/permission`);