Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(agent): show Agent visibility as a property in the sidebar menu (#23519)

Rdmclin2a4952a0429a0
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index bdbb663f7e6..76e3c4be043 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -9,6 +9,12 @@
"agent.publishToWorkspace": "Publish to Workspace",
"agent.publishToWorkspaceErrorFixedPrivateDevice": "Publish the fixed device to the workspace, or let members choose a device, before publishing this Agent.",
"agent.publishToWorkspaceSuccess": "Published to workspace",
+ "agent.visibility": "Visibility",
+ "agent.visibility.change": "Change visibility",
+ "agent.visibility.private": "Private",
+ "agent.visibility.privateDesc": "Only you can see it",
+ "agent.visibility.workspace": "Workspace",
+ "agent.visibility.workspaceDesc": "Workspace members can access it",
"agentBuilder.installPlugin.authRequired": "Cloud MCP requires sign-in to continue",
"agentBuilder.installPlugin.cancel": "Cancel",
"agentBuilder.installPlugin.clickApproveToConnect": "Click \"Approve\" to connect and authorize this Integration",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 846dd598b86..b2a30ee3292 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -9,6 +9,12 @@
"agent.publishToWorkspace": "发布到工作区",
"agent.publishToWorkspaceErrorFixedPrivateDevice": "发布此助理前,请先将绑定的设备发布到工作区,或改为由成员选择设备。",
"agent.publishToWorkspaceSuccess": "已发布到工作区",
+ "agent.visibility": "可见性",
+ "agent.visibility.change": "更改可见性",
+ "agent.visibility.private": "私密",
+ "agent.visibility.privateDesc": "仅自己可见",
+ "agent.visibility.workspace": "工作区",
+ "agent.visibility.workspaceDesc": "工作区成员可访问",
"agentBuilder.installPlugin.authRequired": "云端 MCP 需要登录后才能继续",
"agentBuilder.installPlugin.cancel": "取消",
"agentBuilder.installPlugin.clickApproveToConnect": "点击「批准」连接并授权此连接器",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 7ced8320f74..fa31fbf2f6b 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1623,6 +1623,12 @@ export default {
'agent.publishToWorkspaceErrorFixedPrivateDevice':
'Publish the fixed device to the workspace, or let members choose a device, before publishing this Agent.',
'agent.publishToWorkspaceSuccess': 'Published to workspace',
+ 'agent.visibility': 'Visibility',
+ 'agent.visibility.change': 'Change visibility',
+ 'agent.visibility.private': 'Private',
+ 'agent.visibility.privateDesc': 'Only you can see it',
+ 'agent.visibility.workspace': 'Workspace',
+ 'agent.visibility.workspaceDesc': 'Workspace members can access it',
'resources.publishToWorkspace.menu': 'Publish to Workspace',
'resources.publishToWorkspace.confirm':
'Other workspace members will be able to see this file. You will not be able to make it private again.',
diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentItem/VisibilityLockAction.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentItem/VisibilityLockAction.tsx
new file mode 100644
index 00000000000..04df1c1b64c
--- /dev/null
+++ b/src/features/HomeSidebar/Body/Agent/List/AgentItem/VisibilityLockAction.tsx
@@ -0,0 +1,33 @@
+import { ActionIcon, type DropdownItem, DropdownMenu } from '@lobehub/ui';
+import { LockIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+interface VisibilityLockActionProps {
+ options: DropdownItem[];
+}
+
+/**
+ * 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.
+ */
+const VisibilityLockAction = memo<VisibilityLockActionProps>(({ options }) => {
+ const { t } = useTranslation('chat');
+
+ 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>
+ );
+});
+
+VisibilityLockAction.displayName = 'VisibilityLockAction';
+
+export default VisibilityLockAction;
diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsx
index 9349a9c77e0..b0284d74974 100644
--- a/src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsx
@@ -23,7 +23,9 @@ 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';
const styles = stylex.create({
badge: {
@@ -227,6 +229,11 @@ const AgentItem = memo<AgentItemProps>(({ item, style, className, onNavigate, se
visibility,
});
+ // 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;
+
return (
<WorkspaceLink
aria-label={displayTitle}
@@ -235,7 +242,6 @@ const AgentItem = memo<AgentItemProps>(({ item, style, className, onNavigate, se
onMouseEnter={handleMouseEnter}
>
<NavItem
- actions={<Actions dropdownMenu={dropdownMenu} />}
className={className}
contextMenuItems={dropdownMenu}
disabled={isUpdating}
@@ -244,6 +250,18 @@ const AgentItem = memo<AgentItemProps>(({ item, style, className, onNavigate, se
icon={avatarIcon}
key={id}
style={style}
+ actions={
+ // Two direct children widen the hover overlay (NavItem counts them),
+ // so the resting lock fades under the clickable one.
+ showVisibilityLock ? (
+ <>
+ <VisibilityLockAction options={visibilityMenu.options} />
+ <Actions dropdownMenu={dropdownMenu} />
+ </>
+ ) : (
+ <Actions dropdownMenu={dropdownMenu} />
+ )
+ }
title={
roleTag ? (
<>
diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentItem/useAgentVisibilityMenu.test.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentItem/useAgentVisibilityMenu.test.tsx
new file mode 100644
index 00000000000..25b91d34838
--- /dev/null
+++ b/src/features/HomeSidebar/Body/Agent/List/AgentItem/useAgentVisibilityMenu.test.tsx
@@ -0,0 +1,197 @@
+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';
+
+const mocks = vi.hoisted(() => ({
+ activeWorkspaceId: 'workspace-1' as string | null,
+ canEdit: true,
+ canEditResource: true,
+ confirmModal: vi.fn(),
+ publishAgentToWorkspace: vi.fn(),
+ refreshAgentList: vi.fn(),
+ refreshWorkspaceUserPreference: vi.fn(),
+ setAgentVisibility: vi.fn(),
+ toastError: vi.fn(),
+ toastSuccess: vi.fn(),
+}));
+
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ confirmModal: mocks.confirmModal,
+ toast: { error: mocks.toastError, success: mocks.toastSuccess },
+}));
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ useActiveWorkspaceId: () => mocks.activeWorkspaceId,
+}));
+
+vi.mock('@/features/ResourcePermission/useResourceAccess', () => ({
+ useResourceAccess: () => ({ canEditResource: mocks.canEditResource, isAccessResolved: true }),
+}));
+
+vi.mock('@/features/VisibilityConfirmContent', () => ({ default: () => null }));
+
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: () => ({ allowed: mocks.canEdit, reason: '' }),
+}));
+
+vi.mock('@/services/agent', () => ({
+ agentService: {
+ publishAgentToWorkspace: mocks.publishAgentToWorkspace,
+ setAgentVisibility: mocks.setAgentVisibility,
+ },
+}));
+
+vi.mock('@/store/home', () => ({
+ useHomeStore: (selector: (s: { refreshAgentList: unknown }) => unknown) =>
+ selector({ refreshAgentList: mocks.refreshAgentList }),
+}));
+
+interface UserStateMock {
+ refreshWorkspaceUserPreference: unknown;
+ userId: string;
+}
+
+vi.mock('@/store/user', () => ({
+ useUserStore: (selector: (s: UserStateMock) => unknown) =>
+ selector({
+ refreshWorkspaceUserPreference: mocks.refreshWorkspaceUserPreference,
+ userId: 'me',
+ }),
+}));
+
+vi.mock('@/store/user/selectors', () => ({
+ userProfileSelectors: { userId: (s: UserStateMock) => s.userId },
+}));
+
+vi.mock('../../../../hooks', () => ({ useRevealSidebarSection: () => vi.fn() }));
+
+type Params = Parameters<typeof useAgentVisibilityMenu>[0];
+
+const render = (params: Partial<Params> = {}) =>
+ renderHook(() =>
+ useAgentVisibilityMenu({ 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', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.activeWorkspaceId = 'workspace-1';
+ mocks.canEdit = true;
+ 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',
+ });
+ 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);
+ });
+
+ it('confirms and publishes when Workspace is picked on a private Agent', async () => {
+ const menu = render({ visibility: 'private' });
+
+ options(menu)[1].onCheckedChange(true);
+ expect(mocks.confirmModal).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ await mocks.confirmModal.mock.calls[0][0].onOk();
+ });
+
+ expect(mocks.publishAgentToWorkspace).toHaveBeenCalledWith('agent-1');
+ expect(mocks.refreshAgentList).toHaveBeenCalled();
+ 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);
+ expect(mocks.confirmModal).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ await mocks.confirmModal.mock.calls[0][0].onOk();
+ });
+
+ expect(mocks.setAgentVisibility).toHaveBeenCalledWith('agent-1', 'private');
+ });
+
+ 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);
+
+ 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' });
+
+ expect(menu).toEqual({ canChange: false, options: [], submenu: null });
+ });
+
+ it('is absent outside a workspace', () => {
+ mocks.activeWorkspaceId = null;
+
+ expect(render().canChange).toBe(false);
+ });
+
+ it('is absent on builtin agents', () => {
+ expect(render({ slug: 'inbox', visibility: 'public' }).canChange).toBe(false);
+ });
+
+ it('is absent when the viewer cannot configure the Agent', () => {
+ mocks.canEditResource = false;
+
+ expect(render().canChange).toBe(false);
+ });
+});
diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentItem/useAgentVisibilityMenu.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentItem/useAgentVisibilityMenu.tsx
new file mode 100644
index 00000000000..ff25cf0a184
--- /dev/null
+++ b/src/features/HomeSidebar/Body/Agent/List/AgentItem/useAgentVisibilityMenu.tsx
@@ -0,0 +1,173 @@
+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.tsx
index dfb4bbd0560..e5531b9d880 100644
--- a/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.test.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.test.tsx
@@ -458,7 +458,7 @@ describe('useAgentDropdownMenu', () => {
'copy-agent',
'divider',
'permission',
- 'makePrivate',
+ 'visibility',
'divider',
'delete',
]);
diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.tsx
index 662494f50e7..5772d130adb 100644
--- a/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.tsx
@@ -1,4 +1,3 @@
-import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
import {
agentRenameField,
SessionDefaultGroup,
@@ -6,13 +5,12 @@ import {
type SidebarVisibility,
} from '@lobechat/types';
import { type DropdownItem } from '@lobehub/ui';
-import { confirmModal, Icon, toast } from '@lobehub/ui';
+import { Icon, toast } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
import {
Check,
EyeOffIcon,
FolderInputIcon,
- GlobeIcon,
LucideCopy,
LucidePlus,
Pen,
@@ -34,25 +32,18 @@ import { openRenameModal } from '@/components/RenameModal';
import { confirmRemoveAgent } from '@/features/AgentDeleteConfirm';
import { useOptionalAgentModal } from '@/features/HomeSidebar/Body/Agent/ModalProvider';
import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
-import VisibilityConfirmContent from '@/features/VisibilityConfirmContent';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useCopyAgentIdMenuItem } from '@/hooks/useCopyAgentIdMenuItem';
import { usePermission } from '@/hooks/usePermission';
import { useResourceManageable } from '@/hooks/useResourceManageable';
-import { agentService } from '@/services/agent';
import { useGlobalStore } from '@/store/global';
import { useHomeStore } from '@/store/home';
import { agentLabelSelectors, homeAgentListSelectors } from '@/store/home/selectors';
-import { useUserStore } from '@/store/user';
-import { userProfileSelectors } from '@/store/user/selectors';
import { getDeleteErrorMessageKey } from '@/utils/forbiddenError';
-import { useRevealSidebarSection } from '../../../../hooks';
import { useSidebarItemVisibility } from '../../useSidebarItemVisibility';
import { useSidebarPinMenuItems } from '../../useSidebarPinMenuItems';
-import { getAgentPublishErrorKey } from './agentMenuVisibility';
-
-const BUILTIN_SLUGS = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));
+import { useAgentVisibilityMenu } from './useAgentVisibilityMenu';
interface UseAgentDropdownMenuParams {
avatar?: string;
@@ -106,7 +97,6 @@ export const useAgentDropdownMenu = ({
: homeAgentListSelectors.agentGroups,
isEqual,
);
- const refreshAgentList = useHomeStore((s) => s.refreshAgentList);
const [
pinAgent,
duplicateAgent,
@@ -134,27 +124,10 @@ export const useAgentDropdownMenu = ({
[registryLabels, assignedLabelIds],
);
- // Visibility actions are only meaningful inside a workspace: in personal
- // mode every row is implicitly owner-private. "Publish to Workspace"
- // appears on private agents; the inverse "Make private"
- // appears on published agents, but only for the creator ( —
- // owners demoting another member's agent would appropriate it), and never
- // on builtin agents (LobeAI etc.). The server enforces the same rules as
- // a backstop.
const activeWorkspaceId = useActiveWorkspaceId();
- const currentUserId = useUserStore(userProfileSelectors.userId);
const { isSidebarItemVisible, setSidebarItemVisible } = useSidebarItemVisibility();
- const refreshWorkspaceUserPreference = useUserStore((s) => s.refreshWorkspaceUserPreference);
const isShownInSidebar = isSidebarItemVisible({ id, slug, type: 'agent', userId });
- const isPrivate = visibility === 'private';
- const isBuiltin = !!slug && BUILTIN_SLUGS.has(slug);
- const showPublishAction = Boolean(activeWorkspaceId) && isPrivate;
- const showMakePrivateAction =
- Boolean(activeWorkspaceId) &&
- visibility === 'public' &&
- !isBuiltin &&
- !!currentUserId &&
- userId === currentUserId;
+ 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.
@@ -200,12 +173,6 @@ export const useAgentDropdownMenu = ({
const isDefault = group === SessionDefaultGroup.Default;
- // Visibility flips move the item across accordions. Reveal the destination
- // section afterwards — with a collapsed/hidden target (stale persisted
- // `sidebarExpandedKeys` predate newer sections) the item would silently
- // vanish from the sidebar.
- const revealSidebarSection = useRevealSidebarSection();
-
// Workspace: a personal pin for every member plus an owner/admin-only team
// pin on public rows. Personal mode keeps the single column-backed pin.
const { isTeamPinned, menuItems: workspacePinItems } = useSidebarPinMenuItems({
@@ -494,92 +461,12 @@ export const useAgentDropdownMenu = ({
},
]
: []),
- ...(showPublishAction
- ? [
- {
- icon: <Icon icon={GlobeIcon} />,
- key: 'publishToWorkspace',
- label: t('agent.publishToWorkspace', {
- defaultValue: 'Publish to Workspace',
- }),
- onClick: async ({ domEvent }: any) => {
- domEvent?.stopPropagation();
- confirmModal({
- cancelText: t('cancel', { ns: 'common' }),
- content: <VisibilityConfirmContent variant="publish" />,
- okText: t('agent.publishToWorkspace', {
- defaultValue: 'Publish to Workspace',
- }),
- 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', {
- defaultValue: 'Published to workspace',
- }),
- );
- } catch (error) {
- console.error('Failed to publish agent:', error);
- const publishErrorKey = getAgentPublishErrorKey(error);
- toast.error(
- publishErrorKey
- ? t(publishErrorKey)
- : t('error', {
- ns: 'common',
- defaultValue: 'Operation failed',
- }),
- );
- }
- },
- title: t('agent.publishToWorkspace', {
- defaultValue: 'Publish to Workspace',
- }),
- });
- },
- sfSymbol: 'globe',
- },
- ]
- : []),
- // Under "Publish to Workspace": hand ownership to a member.
+ // 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] : []),
- ...(showMakePrivateAction
- ? [
- {
- icon: <Icon icon={EyeOffIcon} />,
- key: 'makePrivate',
- label: t('makePrivate', { ns: 'common' }),
- onClick: async ({ domEvent }: any) => {
- domEvent?.stopPropagation();
- 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' }),
- });
- },
- sfSymbol: 'eye.slash',
- },
- ]
- : []),
...(canDelete
? [
{ type: 'divider' as const },
@@ -643,13 +530,9 @@ export const useAgentDropdownMenu = ({
openCreateGroupModal,
transferMenuItems,
transferToMemberItem,
- showPublishAction,
- showMakePrivateAction,
+ visibilityMenu,
isShownInSidebar,
setSidebarItemVisible,
- refreshAgentList,
- refreshWorkspaceUserPreference,
- revealSidebarSection,
t,
],
);
diff --git a/src/libs/contextMenu/canGoNative.test.ts b/src/libs/contextMenu/canGoNative.test.ts
index 60f1bbda937..77213ff56d3 100644
--- a/src/libs/contextMenu/canGoNative.test.ts
+++ b/src/libs/contextMenu/canGoNative.test.ts
@@ -40,6 +40,18 @@ describe('canGoNative', () => {
});
});
+ it('accepts a plain-text extra without a desc (it becomes the sublabel)', () => {
+ const items = [
+ {
+ children: [{ key: 'a', label: 'Private' }],
+ extra: 'Private',
+ key: 'visibility',
+ label: 'Visibility',
+ },
+ ] as unknown as NativeContextMenuItem[];
+ expect(canGoNative(items)).toBe(true);
+ });
+
describe('rejects', () => {
it('a switch item', () => {
expect(canGoNative([{ checked: true, key: '1', label: 'Auto save', type: 'switch' }])).toBe(
@@ -47,9 +59,16 @@ describe('canGoNative', () => {
);
});
- it('an item with non-empty extra', () => {
+ it('an item with a non-text extra', () => {
+ const items = [
+ { extra: { type: 'span' }, key: '1', label: 'Delete' },
+ ] as unknown as NativeContextMenuItem[];
+ expect(canGoNative(items)).toBe(false);
+ });
+
+ it('an item with both a text extra and a desc (only one fits the sublabel)', () => {
const items = [
- { extra: '1', key: '1', label: 'Delete' },
+ { desc: 'Only you', extra: 'Private', key: '1', label: 'Visibility' },
] as unknown as NativeContextMenuItem[];
expect(canGoNative(items)).toBe(false);
});
diff --git a/src/libs/contextMenu/canGoNative.ts b/src/libs/contextMenu/canGoNative.ts
index c6814ffde2e..3d2ae27ce42 100644
--- a/src/libs/contextMenu/canGoNative.ts
+++ b/src/libs/contextMenu/canGoNative.ts
@@ -8,7 +8,13 @@ const isNativeSafe = (item: NativeContextMenuItem): boolean => {
if (item === null) return true;
if (item.type === 'switch') return false;
- if ('extra' in item && item.extra) return false;
+ // A plain-text `extra` (a row's current value, e.g. "Visibility · Private")
+ // maps to the native sublabel, which only has room for it when there is no
+ // `desc`. Rich extras (icons, hotkeys) have no native counterpart.
+ if ('extra' in item && item.extra) {
+ if (typeof item.extra !== 'string') return false;
+ if ('desc' in item && item.desc) return false;
+ }
if ('loading' in item && item.loading) return false;
if ('closeOnClick' in item && item.closeOnClick === false) return false;
diff --git a/src/libs/contextMenu/index.test.ts b/src/libs/contextMenu/index.test.ts
index 91c5b03742e..19aa37249e2 100644
--- a/src/libs/contextMenu/index.test.ts
+++ b/src/libs/contextMenu/index.test.ts
@@ -52,7 +52,9 @@ describe('showContextMenu routing', () => {
it('delegates to the web menu on darwin when the menu is not native-safe', () => {
stubDarwin();
- const items = [{ extra: 'x', key: '1', label: 'Copy' }] as unknown as NativeContextMenuItem[];
+ const items = [
+ { key: '1', label: 'Copy', loading: true },
+ ] as unknown as NativeContextMenuItem[];
showContextMenu(items);
@@ -243,7 +245,7 @@ describe('registerNativeContextMenuInterceptor', () => {
stubDarwin();
interceptor.show?.(
- [{ extra: 'x', key: '1', label: 'Copy' }] as unknown as NativeContextMenuItem[],
+ [{ key: '1', label: 'Copy', loading: true }] as unknown as NativeContextMenuItem[],
undefined,
fallback,
);
diff --git a/src/libs/contextMenu/toNativeTemplate.test.ts b/src/libs/contextMenu/toNativeTemplate.test.ts
index 23d03284785..06eefbec106 100644
--- a/src/libs/contextMenu/toNativeTemplate.test.ts
+++ b/src/libs/contextMenu/toNativeTemplate.test.ts
@@ -58,6 +58,25 @@ describe('toNativeTemplate', () => {
expect(template).toEqual([{ id: '0', label: 'Copy', sublabel: 'Ctrl+C', type: 'normal' }]);
});
+ it('maps a plain-text extra to sublabel when there is no desc', () => {
+ const { template } = toNativeTemplate([
+ {
+ children: [{ key: 'a', label: 'Private' }],
+ extra: 'Private',
+ key: 'v',
+ label: 'Visibility',
+ },
+ ] as unknown as NativeContextMenuItem[]);
+ expect(template).toEqual([
+ {
+ label: 'Visibility',
+ sublabel: 'Private',
+ submenu: [{ id: '0.0', label: 'Private', type: 'normal' }],
+ type: 'submenu',
+ },
+ ]);
+ });
+
it('maps disabled to enabled: false', () => {
const { template } = toNativeTemplate([{ disabled: true, key: '1', label: 'Copy' }]);
expect(template).toEqual([{ enabled: false, id: '0', label: 'Copy', type: 'normal' }]);
diff --git a/src/libs/contextMenu/toNativeTemplate.ts b/src/libs/contextMenu/toNativeTemplate.ts
index 7dfa2181ce6..a86a3bf8973 100644
--- a/src/libs/contextMenu/toNativeTemplate.ts
+++ b/src/libs/contextMenu/toNativeTemplate.ts
@@ -35,6 +35,7 @@ const buildMenuInfo = (key: string): MenuInfo =>
const baseFields = (item: {
desc?: unknown;
disabled?: boolean;
+ extra?: unknown;
label?: unknown;
sfSymbol?: SFSymbol;
}) =>
@@ -42,7 +43,8 @@ const baseFields = (item: {
enabled: item.disabled ? false : undefined,
label: toLabel(item.label),
sfSymbol: item.sfSymbol,
- sublabel: toSublabel(item.desc),
+ // canGoNative only lets a plain-text `extra` through when `desc` is absent.
+ sublabel: toSublabel(item.desc) ?? toSublabel(item.extra),
});
const convertChildren = (