🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(agent): list an agent's tools once and show its own connection per row (#23465)
AmAzing-13a650e190bf
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 0c2eb8711f9..48768f637f8 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -1629,31 +1629,8 @@"settingAbout.remoteDebugging.restartToApply": "Restart LobeHub to apply this change.","settingAbout.remoteDebugging.title": "Remote Debugging","settingAgent.agentTools.add": "Add Tool",- "settingAgent.agentTools.agentEmpty": "Nothing only for this agent yet","settingAgent.agentTools.authorizedBy": "Authorized by {{name}}",- "settingAgent.agentTools.badge.agentOnly": "Agent-only",- "settingAgent.agentTools.badge.copy": "Copy",- "settingAgent.agentTools.badge.linked": "Linked",- "settingAgent.agentTools.badge.overridden": "Overridden",- "settingAgent.agentTools.connectNew.desc": "Agent-exclusive connection",- "settingAgent.agentTools.connectNew.title": "Connect new tool",- "settingAgent.agentTools.connectNewPickerTitle": "Connect a new tool for this Agent",- "settingAgent.agentTools.copy.desc": "Independent copy, separately configurable",- "settingAgent.agentTools.copy.title": "Copy user tool",- "settingAgent.agentTools.copyConfirm": "Copy {{count}}",- "settingAgent.agentTools.copyPick": "Select user connectors to copy into this agent",- "settingAgent.agentTools.menuTitle": "Add a tool for this Agent",- "settingAgent.agentTools.mount.desc": "Reference, syncs with user config",- "settingAgent.agentTools.mount.title": "Mount user tool",- "settingAgent.agentTools.overriddenNote": "{{count}} user tool(s) overridden by same-named Agent Tools; they will not run.","settingAgent.agentTools.pickerEmpty": "No user connectors available to add",- "settingAgent.agentTools.priorityHint": "Run priority",- "settingAgent.agentTools.priorityTooltip": "When tools share a name, the agent-exclusive tool runs first at runtime; your user tools come next.",- "settingAgent.agentTools.priorityTooltipWorkspace": "When tools share a name, this agent-scoped tool runs first at runtime; the workspace user tools are the fallback.",- "settingAgent.agentTools.removeOwnedConfirm": "Delete this agent-exclusive connector? Its credentials will be removed.",- "settingAgent.agentTools.tabAgent": "Only for this agent",- "settingAgent.agentTools.tabUser": "From my library",- "settingAgent.agentTools.tabWorkspace": "From the workspace library","settingAgent.artwork.avatar.generating": "Creating an image that matches this Agent…","settingAgent.artwork.avatar.image": "AI avatar","settingAgent.artwork.background.empty": "Add a background to give this Agent a visual identity",@@ -1774,7 +1751,6 @@"settingAgent.skills.source.community": "Community","settingAgent.skills.source.custom": "Custom","settingAgent.skillsPage.desc": "A skill is a set of steps it picks up only when a task needs them.",- "settingAgent.skillsPage.group.desc": "Skills come from your library and are shared by all your agents.","settingAgent.skillsPage.group.title": "Turned on for this agent","settingAgent.skillsPage.title": "Skills","settingAgent.slug.autoPlaceholder": "Leave empty to generate one",@@ -1792,16 +1768,38 @@"settingAgent.tag.title": "Tag","settingAgent.title": "Agent info","settingAgent.tools.close": "Close",+ "settingAgent.tools.connection.connectForAgent": "Connect an app for this agent only",+ "settingAgent.tools.connection.create": "Use a separate connection",+ "settingAgent.tools.connection.createAccount": "Connect a separate account",+ "settingAgent.tools.connection.createDesc": "For this agent only",+ "settingAgent.tools.connection.createFailed": "Could not set up a separate connection for {{name}}",+ "settingAgent.tools.connection.created": "{{name}} now has its own connection for this agent",+ "settingAgent.tools.connection.createdDesc": "It starts as a copy of the library one. Change how it signs in under Manage connection.",+ "settingAgent.tools.connection.libraryDesc": "Shared by every agent of yours that turns this on.",+ "settingAgent.tools.connection.libraryTitle": "Uses your library connection",+ "settingAgent.tools.connection.manage": "Manage connection",+ "settingAgent.tools.connection.menu": "Connection options",+ "settingAgent.tools.connection.own": "Own connection",+ "settingAgent.tools.connection.ownDesc": "This agent signs in separately from your library. Changing or removing the library connection does not affect it.",+ "settingAgent.tools.connection.ownDescWorkspace": "This agent signs in separately from the workspace library. Changing or removing the library connection does not affect it.",+ "settingAgent.tools.connection.ownTitle": "Uses its own connection",+ "settingAgent.tools.connection.removeConfirm.desc": "Only this agent has this connection. It will be deleted together with its credentials.",+ "settingAgent.tools.connection.removeConfirm.title": "Remove {{name}} from this agent?",+ "settingAgent.tools.connection.switchFailed": "Could not switch connections for {{name}}. This agent still uses its own connection.",+ "settingAgent.tools.connection.useLibrary": "Use the library connection",+ "settingAgent.tools.connection.useLibraryConfirm.desc": "This agent's own connection and its credentials will be deleted. It will use the one in your library from now on.",+ "settingAgent.tools.connection.useLibraryConfirm.title": "Stop using a separate connection for {{name}}?",+ "settingAgent.tools.connection.useWorkspace": "Use the workspace connection",+ "settingAgent.tools.connection.useWorkspaceConfirm.desc": "This agent's own connection and its credentials will be deleted. It will use the one in the workspace library from now on.",+ "settingAgent.tools.connection.workspaceDesc": "Shared by every agent in the workspace that turns this on.",+ "settingAgent.tools.connection.workspaceTitle": "Uses the workspace connection","settingAgent.tools.countOfTotal": "{{count}} of {{total}} turned on","settingAgent.tools.detail.tools_one": "{{count}} tool it gives the agent","settingAgent.tools.detail.tools_other": "{{count}} tools it gives the agent","settingAgent.tools.disable": "Turn off","settingAgent.tools.enable": "Turn on",- "settingAgent.tools.level.agentDesc": "Belong to this agent alone. When a name clashes, these run first.",- "settingAgent.tools.level.libraryDesc": "Shared by all your agents. Connection and credentials are managed in your library.","settingAgent.tools.level.libraryEmpty": "Nothing from the library is turned on for this agent yet","settingAgent.tools.level.skillsEmpty": "No skills are turned on for this agent yet",- "settingAgent.tools.level.workspaceDesc": "Shared across the workspace. Connection and credentials are managed in the workspace library.","settingAgent.tools.manageLibrary": "Manage library","settingAgent.tools.remove": "Remove from this agent","settingAgent.tools.showAll": "Show all {{count}}",@@ -1816,6 +1814,8 @@"settingAgent.tools.type.skill": "Skill","settingAgent.toolsConfig.title": "Tools","settingAgent.toolsPage.desc": "Connect what it can act on: look things up, read files, call your services.",+ "settingAgent.toolsPage.group.empty": "No tools are turned on for this agent yet",+ "settingAgent.toolsPage.group.title": "This agent's tools","settingAgent.toolsPage.title": "Tools and connectors","settingAgent.topicSharePolicy.membersCanShare": "Members can share","settingAgent.topicSharePolicy.membersCannotShare": "Creator and owners only",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex 31c3e9cbd9f..5725f03345a 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -1629,31 +1629,8 @@"settingAbout.remoteDebugging.restartToApply": "重启 LobeHub 后生效。","settingAbout.remoteDebugging.title": "远程调试","settingAgent.agentTools.add": "添加工具",- "settingAgent.agentTools.agentEmpty": "还没有只给它用的工具","settingAgent.agentTools.authorizedBy": "由 {{name}} 授权",- "settingAgent.agentTools.badge.agentOnly": "Agent 专属",- "settingAgent.agentTools.badge.copy": "副本",- "settingAgent.agentTools.badge.linked": "引用",- "settingAgent.agentTools.badge.overridden": "已覆盖",- "settingAgent.agentTools.connectNew.desc": "Agent 专属连接",- "settingAgent.agentTools.connectNew.title": "连接新工具",- "settingAgent.agentTools.connectNewPickerTitle": "为此 Agent 连接一个新工具",- "settingAgent.agentTools.copy.desc": "独立副本,可单独改配置",- "settingAgent.agentTools.copy.title": "复制用户工具",- "settingAgent.agentTools.copyConfirm": "确认复制 {{count}}",- "settingAgent.agentTools.copyPick": "勾选要复制到该 Agent 的用户连接器",- "settingAgent.agentTools.menuTitle": "为此 Agent 添加工具",- "settingAgent.agentTools.mount.desc": "引用,随用户配置更新",- "settingAgent.agentTools.mount.title": "挂载用户工具",- "settingAgent.agentTools.overriddenNote": "{{count}} 个用户工具被同名 Agent 工具覆盖,运行时不会生效。","settingAgent.agentTools.pickerEmpty": "没有可添加的用户连接器",- "settingAgent.agentTools.priorityHint": "运行优先级",- "settingAgent.agentTools.priorityTooltip": "工具同名时,运行时优先使用 Agent 专属工具,其次才使用你的用户工具。",- "settingAgent.agentTools.priorityTooltipWorkspace": "工具同名时,运行时优先使用该 Agent 维度的工具,其次兜底到当前工作空间下 user 维度的用户工具。",- "settingAgent.agentTools.removeOwnedConfirm": "删除这个 Agent 专属连接器?其凭据将被移除。",- "settingAgent.agentTools.tabAgent": "只给它用",- "settingAgent.agentTools.tabUser": "来自我的库",- "settingAgent.agentTools.tabWorkspace": "来自工作区的库","settingAgent.artwork.avatar.generating": "正在生成符合 Agent 设定的形象…","settingAgent.artwork.avatar.image": "AI 形象","settingAgent.artwork.background.empty": "添加背景,让助理拥有更鲜明的视觉形象",@@ -1774,7 +1751,6 @@"settingAgent.skills.source.community": "社区","settingAgent.skills.source.custom": "自己写的","settingAgent.skillsPage.desc": "技能是一套做事的步骤,只有任务需要时它才会去读。",- "settingAgent.skillsPage.group.desc": "技能来自你的库,所有助理共用。","settingAgent.skillsPage.group.title": "给这个助理打开的","settingAgent.skillsPage.title": "技能","settingAgent.slug.autoPlaceholder": "留空则自动生成",@@ -1792,16 +1768,38 @@"settingAgent.tag.title": "标签","settingAgent.title": "助理信息","settingAgent.tools.close": "关闭详情",+ "settingAgent.tools.connection.connectForAgent": "只给这个助理连接一个应用",+ "settingAgent.tools.connection.create": "改用专属连接",+ "settingAgent.tools.connection.createAccount": "连接专属账号",+ "settingAgent.tools.connection.createDesc": "只给这个助理用",+ "settingAgent.tools.connection.createFailed": "没能为 {{name}} 建立专属连接",+ "settingAgent.tools.connection.created": "这个助理已改用专属的 {{name}} 连接",+ "settingAgent.tools.connection.createdDesc": "它先复制了库里的连接。要换登录方式,请到“管理连接”里修改。",+ "settingAgent.tools.connection.libraryDesc": "你所有打开了它的助理共用这一个连接。",+ "settingAgent.tools.connection.libraryTitle": "使用你库里的连接",+ "settingAgent.tools.connection.manage": "管理连接",+ "settingAgent.tools.connection.menu": "连接选项",+ "settingAgent.tools.connection.own": "专属连接",+ "settingAgent.tools.connection.ownDesc": "这个助理单独登录,不走你库里的连接。库里的连接改了或删了,都不影响它。",+ "settingAgent.tools.connection.ownDescWorkspace": "这个助理单独登录,不走工作区库里的连接。库里的连接改了或删了,都不影响它。",+ "settingAgent.tools.connection.ownTitle": "使用专属连接",+ "settingAgent.tools.connection.removeConfirm.desc": "这个连接只有这个助理在用,它会和凭证一起被删除。",+ "settingAgent.tools.connection.removeConfirm.title": "从这个助理移除 {{name}}?",+ "settingAgent.tools.connection.switchFailed": "未能切换 {{name}} 的连接。这个助理仍使用自己的专属连接。",+ "settingAgent.tools.connection.useLibrary": "改用库里的连接",+ "settingAgent.tools.connection.useLibraryConfirm.desc": "这个助理的专属连接和凭证会被删除,之后改用你库里的连接。",+ "settingAgent.tools.connection.useLibraryConfirm.title": "不再给 {{name}} 用专属连接?",+ "settingAgent.tools.connection.useWorkspace": "改用工作区的连接",+ "settingAgent.tools.connection.useWorkspaceConfirm.desc": "这个助理的专属连接和凭证会被删除,之后改用工作区库里的连接。",+ "settingAgent.tools.connection.workspaceDesc": "工作区里所有打开了它的助理共用这一个连接。",+ "settingAgent.tools.connection.workspaceTitle": "使用工作区的连接","settingAgent.tools.countOfTotal": "已打开 {{count}} / 共 {{total}} 个","settingAgent.tools.detail.tools_one": "给助理带来 {{count}} 个工具","settingAgent.tools.detail.tools_other": "给助理带来 {{count}} 个工具","settingAgent.tools.disable": "关闭","settingAgent.tools.enable": "打开",- "settingAgent.tools.level.agentDesc": "只属于这个助理。重名时,它们优先运行。",- "settingAgent.tools.level.libraryDesc": "你所有助理共用。连接和凭证在“我的库”里统一管理。","settingAgent.tools.level.libraryEmpty": "还没有从库里启用任何工具","settingAgent.tools.level.skillsEmpty": "还没有给这个助理打开任何技能",- "settingAgent.tools.level.workspaceDesc": "整个工作区共用。连接和凭证在工作区的库里统一管理。","settingAgent.tools.manageLibrary": "管理库","settingAgent.tools.remove": "从这个助理移除","settingAgent.tools.showAll": "展开全部 {{count}} 个",@@ -1816,6 +1814,8 @@"settingAgent.tools.type.skill": "技能","settingAgent.toolsConfig.title": "工具","settingAgent.toolsPage.desc": "连上它能动手的东西:查资料、读文件、调用你的服务。",+ "settingAgent.toolsPage.group.empty": "还没有给这个助理打开任何工具",+ "settingAgent.toolsPage.group.title": "这个助理的工具","settingAgent.toolsPage.title": "工具与连接","settingAgent.topicSharePolicy.membersCanShare": "成员可分享","settingAgent.topicSharePolicy.membersCannotShare": "仅创建者和所有者",diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex c2cf39a0138..305b4d4df35 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -1412,44 +1412,11 @@ export default {'settingAgent.prompt.placeholder': 'Enter agent instructions','settingAgent.prompt.title': 'Core Instructions','settingAgent.agentTools.add': 'Add Tool',- 'settingAgent.agentTools.agentEmpty': 'Nothing only for this agent yet','settingAgent.agentTools.authorizedBy': 'Authorized by {{name}}',- 'settingAgent.agentTools.badge.agentOnly': 'Agent-only',- 'settingAgent.agentTools.badge.copy': 'Copy',- 'settingAgent.agentTools.badge.linked': 'Linked',- 'settingAgent.agentTools.badge.overridden': 'Overridden',- 'settingAgent.agentTools.connectNew.desc': 'Agent-exclusive connection',- 'settingAgent.agentTools.connectNew.title': 'Connect new tool',- 'settingAgent.agentTools.connectNewPickerTitle': 'Connect a new tool for this Agent',- 'settingAgent.agentTools.copy.desc': 'Independent copy, separately configurable',- 'settingAgent.agentTools.copy.title': 'Copy user tool',- 'settingAgent.agentTools.copyConfirm': 'Copy {{count}}',- 'settingAgent.agentTools.copyPick': 'Select user connectors to copy into this agent',- 'settingAgent.agentTools.menuTitle': 'Add a tool for this Agent',- 'settingAgent.agentTools.mount.desc': 'Reference, syncs with user config',- 'settingAgent.agentTools.mount.title': 'Mount user tool',- 'settingAgent.agentTools.overriddenNote':- '{{count}} user tool(s) overridden by same-named Agent Tools; they will not run.','settingAgent.agentTools.pickerEmpty': 'No user connectors available to add',- 'settingAgent.agentTools.priorityHint': 'Run priority',- 'settingAgent.agentTools.priorityTooltip':- 'When tools share a name, the agent-exclusive tool runs first at runtime; your user tools come next.',- 'settingAgent.agentTools.priorityTooltipWorkspace':- 'When tools share a name, this agent-scoped tool runs first at runtime; the workspace user tools are the fallback.',- 'settingAgent.agentTools.removeOwnedConfirm':- 'Delete this agent-exclusive connector? Its credentials will be removed.',- 'settingAgent.agentTools.tabAgent': 'Only for this agent',- 'settingAgent.agentTools.tabUser': 'From my library',- 'settingAgent.agentTools.tabWorkspace': 'From the workspace library',- 'settingAgent.tools.level.agentDesc':- 'Belong to this agent alone. When a name clashes, these run first.',- 'settingAgent.tools.level.libraryDesc':- 'Shared by all your agents. Connection and credentials are managed in your library.','settingAgent.tools.level.libraryEmpty':'Nothing from the library is turned on for this agent yet','settingAgent.tools.level.skillsEmpty': 'No skills are turned on for this agent yet',- 'settingAgent.tools.level.workspaceDesc':- 'Shared across the workspace. Connection and credentials are managed in the workspace library.','settingAgent.tools.showAll': 'Show all {{count}}','settingAgent.tools.showLess': 'Show less','settingAgent.tools.toolCount_one': '{{count}} tool',@@ -1460,6 +1427,41 @@ export default {'settingAgent.tools.close': 'Close','settingAgent.tools.detail.tools_one': '{{count}} tool it gives the agent','settingAgent.tools.detail.tools_other': '{{count}} tools it gives the agent',+ 'settingAgent.tools.connection.own': 'Own connection',+ 'settingAgent.tools.connection.ownTitle': 'Uses its own connection',+ 'settingAgent.tools.connection.ownDesc':+ 'This agent signs in separately from your library. Changing or removing the library connection does not affect it.',+ 'settingAgent.tools.connection.ownDescWorkspace':+ 'This agent signs in separately from the workspace library. Changing or removing the library connection does not affect it.',+ 'settingAgent.tools.connection.libraryTitle': 'Uses your library connection',+ 'settingAgent.tools.connection.libraryDesc': 'Shared by every agent of yours that turns this on.',+ 'settingAgent.tools.connection.workspaceTitle': 'Uses the workspace connection',+ 'settingAgent.tools.connection.workspaceDesc':+ 'Shared by every agent in the workspace that turns this on.',+ 'settingAgent.tools.connection.menu': 'Connection options',+ 'settingAgent.tools.connection.create': 'Use a separate connection',+ 'settingAgent.tools.connection.createAccount': 'Connect a separate account',+ 'settingAgent.tools.connection.createDesc': 'For this agent only',+ 'settingAgent.tools.connection.created': '{{name}} now has its own connection for this agent',+ 'settingAgent.tools.connection.createdDesc':+ 'It starts as a copy of the library one. Change how it signs in under Manage connection.',+ 'settingAgent.tools.connection.createFailed':+ 'Could not set up a separate connection for {{name}}',+ 'settingAgent.tools.connection.manage': 'Manage connection',+ 'settingAgent.tools.connection.switchFailed':+ 'Could not switch connections for {{name}}. This agent still uses its own connection.',+ 'settingAgent.tools.connection.useLibrary': 'Use the library connection',+ 'settingAgent.tools.connection.useWorkspace': 'Use the workspace connection',+ 'settingAgent.tools.connection.useLibraryConfirm.title':+ 'Stop using a separate connection for {{name}}?',+ 'settingAgent.tools.connection.useLibraryConfirm.desc':+ "This agent's own connection and its credentials will be deleted. It will use the one in your library from now on.",+ 'settingAgent.tools.connection.useWorkspaceConfirm.desc':+ "This agent's own connection and its credentials will be deleted. It will use the one in the workspace library from now on.",+ 'settingAgent.tools.connection.removeConfirm.title': 'Remove {{name}} from this agent?',+ 'settingAgent.tools.connection.removeConfirm.desc':+ 'Only this agent has this connection. It will be deleted together with its credentials.',+ 'settingAgent.tools.connection.connectForAgent': 'Connect an app for this agent only','settingAgent.tools.manageLibrary': 'Manage library','settingAgent.tools.remove': 'Remove from this agent','settingAgent.tools.type.builtin': 'Built-in tool',@@ -1518,12 +1520,12 @@ export default {'settingAgent.toolsPage.desc':'Connect what it can act on: look things up, read files, call your services.','settingAgent.toolsPage.title': 'Tools and connectors',+ 'settingAgent.toolsPage.group.title': "This agent's tools",+ 'settingAgent.toolsPage.group.empty': 'No tools are turned on for this agent yet','settingAgent.skillsPage.title': 'Skills','settingAgent.skillsPage.desc':'A skill is a set of steps it picks up only when a task needs them.','settingAgent.skillsPage.group.title': 'Turned on for this agent',- 'settingAgent.skillsPage.group.desc':- 'Skills come from your library and are shared by all your agents.','settingAgent.skills.source.builtin': 'Built-in','settingAgent.skills.source.community': 'Community','settingAgent.skills.source.custom': 'Custom',diff --git a/src/features/AgentSkillStore/Item.tsx b/src/features/AgentSkillStore/Item.tsxindex af5d0e038a4..56dde634d82 100644--- a/src/features/AgentSkillStore/Item.tsx+++ b/src/features/AgentSkillStore/Item.tsx@@ -53,7 +53,7 @@ const Item = memo<ItemProps>(({ agentId, appSlug, description, icon, identifier,if (!canEdit) return;confirmModal({cancelText: t('cancel', { ns: 'common' }),- content: t('settingAgent.agentTools.removeOwnedConfirm'),+ content: t('settingAgent.tools.connection.removeConfirm.desc'),okButtonProps: { danger: true },okText: t('tools.lobehubSkill.disconnect'),onOk: handleDisconnect,diff --git a/src/features/AgentSkillStore/index.tsx b/src/features/AgentSkillStore/index.tsxindex 81df274382b..560e863ac26 100644--- a/src/features/AgentSkillStore/index.tsx+++ b/src/features/AgentSkillStore/index.tsx@@ -10,6 +10,6 @@ export const createAgentSkillStoreModal = (agentId: string) =>createModal({content: <AgentSkillStoreContent agentId={agentId} />,footer: null,- title: t('settingAgent.agentTools.connectNewPickerTitle', { ns: 'setting' }),+ title: t('settingAgent.tools.connection.connectForAgent', { ns: 'setting' }),width: 'min(80%, 800px)',});diff --git a/src/features/ChatInput/ActionBar/Tools/useControls.test.ts b/src/features/ChatInput/ActionBar/Tools/useControls.test.tsindex 23ea6132436..6d6fa1847df 100644--- a/src/features/ChatInput/ActionBar/Tools/useControls.test.ts+++ b/src/features/ChatInput/ActionBar/Tools/useControls.test.ts@@ -20,6 +20,13 @@ const mocks = vi.hoisted(() => ({{ identifier: 'lobehub', name: 'LobeHub' },],checked: [] as string[],+ connectors: [] as Array<{+ identifier: string;+ isEnabled?: boolean;+ metadata: { mountedByAgentId?: string };+ status?: string;+ sourceType: 'custom';+ }>,composioEnabled: false,composioServers: [] as Pick<ComposioServer, 'identifier' | 'status'>[],lobehubEnabled: false,@@ -82,6 +89,7 @@ vi.mock('@/store/tool', () => ({useToolStore: (selector: (state: unknown) => unknown) =>selector({composioServers: mocks.composioServers,+ connectors: mocks.connectors,isConnectorsInit: true,lobehubSkillServers: mocks.lobehubSkillServers,useFetchAgentSkills: vi.fn(),@@ -119,9 +127,10 @@ vi.mock('@/store/tool/selectors', () => ({],},}));-vi.mock('@/store/tool/slices/connector', () => ({- connectorSelectors: { userMcpConnectors: () => [] },-}));+vi.mock(+ '@/store/tool/slices/connector',+ async () => import('@/store/tool/slices/connector/selectors'),+);const leafKeys = (items: ItemType[]): string[] =>items.flatMap((item) => {@@ -144,6 +153,7 @@ describe('chat input tool picker', () => {vi.clearAllMocks();mocks.agentId = 'agent-1';mocks.checked = [];+ mocks.connectors = [];mocks.composioEnabled = false;mocks.composioServers = [];mocks.lobehubEnabled = false;@@ -264,6 +274,46 @@ describe('chat input tool picker', () => {});});+ it('offers only free library MCP connections and those mounted to this agent', () => {+ mocks.connectors = [+ { identifier: 'free', metadata: {}, sourceType: 'custom' },+ { identifier: 'lent-here', metadata: { mountedByAgentId: 'agent-1' }, sourceType: 'custom' },+ {+ identifier: 'lent-elsewhere',+ metadata: { mountedByAgentId: 'agent-2' },+ sourceType: 'custom',+ },+ ];+ const { result } = renderHook(() => useControls());+ const ids = result.current.toolOptions.map((option) => option.id);+ expect(ids).toEqual(expect.arrayContaining(['free', 'lent-here']));+ expect(ids).not.toContain('lent-elsewhere');+ });++ it('counts a newly connected library tool without a plugin entry and leaves the pending tool off', () => {+ mocks.connectors = [+ {+ identifier: 'ready',+ isEnabled: true,+ metadata: {},+ sourceType: 'custom',+ status: 'connected',+ },+ {+ identifier: 'pending',+ isEnabled: true,+ metadata: {},+ sourceType: 'custom',+ status: 'disconnected',+ },+ ];++ const { result } = renderHook(() => useControls());+ const activeIds = result.current.toolOptions.filter((row) => row.enabled).map((row) => row.id);+ expect(activeIds).toContain('ready');+ expect(activeIds).not.toContain('pending');+ });+it('derives the profile summary from the same unfiltered options as chat', () => {const { result } = renderHook(() => useControls());const active = leafKeys(result.current.marketItems);diff --git a/src/features/ChatInput/ActionBar/Tools/useControls.tsx b/src/features/ChatInput/ActionBar/Tools/useControls.tsxindex 00f4c34e23b..b42c7eed32c 100644--- a/src/features/ChatInput/ActionBar/Tools/useControls.tsx+++ b/src/features/ChatInput/ActionBar/Tools/useControls.tsx@@ -21,7 +21,7 @@ import {Zap,} from 'lucide-react';import type { ReactNode } from 'react';-import { useCallback, useEffect, useMemo, useState } from 'react';+import { useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import { buildAgentProfileTabPath } from '@/features/AgentProfileTabs/tabOptions';@@ -512,14 +512,11 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =const installedBuiltinSkills = useToolStore(builtinToolSelectors.installedBuiltinSkills, isEqual);// MCP connectors the user added: custom ones and marketplace installs- const customConnectors = useToolStore(connectorSelectors.userMcpConnectors, isEqual);+ const customConnectors = useToolStore(+ connectorSelectors.userMcpConnectorsForAgent(agentId),+ isEqual,+ );const getConfigure = useConnectorConfigure();- const isConnectorsInit = useToolStore((s) => s.isConnectorsInit);- const fetchConnectors = useToolStore((s) => s.fetchConnectors);- useEffect(() => {- if (!isConnectorsInit) fetchConnectors();- }, [isConnectorsInit, fetchConnectors]);-const [useFetchUserComposioConnections,useFetchLobehubSkillConnections,diff --git a/src/features/ProfileEditor/AgentTool.tsx b/src/features/ProfileEditor/AgentTool.tsxindex f1028c3ac08..6285486eb87 100644--- a/src/features/ProfileEditor/AgentTool.tsx+++ b/src/features/ProfileEditor/AgentTool.tsx@@ -66,9 +66,9 @@ export interface AgentToolProps {agentId?: string;/*** Hide identifiers that are agent-owned/linked connectors from the rendered- * chips. ONLY the two-section agent profile sets this (it renders those- * connectors in a separate "Agent Tools" section above, so showing them here- * too would duplicate them — as an "uninstalled" chip lacking a base manifest).+ * chips. ONLY the agent profile sets this (its Tools page lists those+ * connectors itself, so showing them here too would duplicate them — as an+ * "uninstalled" chip lacking a base manifest).* Consumers that render `AgentTool` as the SOLE tool list (e.g. the group* member profile) MUST leave this off, otherwise the enabled agent tool would* disappear entirely with no way to see or remove it.@@ -93,7 +93,7 @@ export interface AgentToolProps {onOpenDetail?: (detail: ItemDetail) => void;/*** Show an "authorized by X" avatar on each connector chip. Set by the- * two-section agent profile in a workspace so a teammate can see whose+ * agent profile in a workspace so a teammate can see whose* credentials each shared tool runs under. Off elsewhere (personal mode has a* single authorizer — always the caller — so the tag would be noise).* @default false@@ -236,8 +236,8 @@ const AgentTool = memo<AgentToolProps>(// MCP connectors the user added: custom ones and marketplace installsconst customConnectors = useToolStore(connectorSelectors.userMcpConnectors, isEqual);// Agent-owned / linked connectors: when `excludeAgentConnectors` is set (the- // two-section agent profile), these are rendered in the dedicated "Agent- // Tools" section above, so they must be dropped from THIS base/user list —+ // agent profile), these are listed by the profile's Tools page, so they must+ // be dropped from THIS base/user list —// otherwise the identifier, pinned into `config.plugins` for runtime gating,// would surface here too and, lacking a base-dimension manifest, render as an// "uninstalled" chip. When the prop is off (e.g. the group member profile,diff --git a/src/features/ProfileEditor/AgentUserTools/AgentToolList.tsx b/src/features/ProfileEditor/AgentUserTools/AgentToolList.tsxnew file mode 100644index 00000000000..a18d314841d--- /dev/null+++ b/src/features/ProfileEditor/AgentUserTools/AgentToolList.tsx@@ -0,0 +1,258 @@+'use client';++import { upsertConnectorEnabled } from '@lobechat/types';+import { Button, type ItemType } from '@lobehub/ui';+import isEqual from 'fast-deep-equal';+import { PlusIcon } from 'lucide-react';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { useIsWorkspaceOwner } from '@/business/client/hooks/useIsWorkspaceOwner';+import AsyncBoundary from '@/components/AsyncBoundary';+import { createAgentSkillStoreModal } from '@/features/AgentSkillStore';+import ActionDropdown from '@/features/ChatInput/ActionBar/components/ActionDropdown';+import ToolItem from '@/features/ChatInput/ActionBar/Tools/ToolItem';+import { useControls } from '@/features/ChatInput/ActionBar/Tools/useControls';+import { createStore, Provider } from '@/features/ChatInput/store';+import { createSkillStoreModal } from '@/features/SkillStore';+import { useAgentStore } from '@/store/agent';+import { agentSelectors } from '@/store/agent/selectors';+import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';+import { useToolStore } from '@/store/tool';+import { connectorSelectors } from '@/store/tool/slices/connector';+import type { ConnectorWithTools } from '@/store/tool/slices/connector/types';+import { useUserStore } from '@/store/user';++import type { AgentToolProps } from '../AgentTool';+import type { ItemConnection } from '../ItemDetailPanel';+import PluginTag from '../PluginTag';+import ProfilePopoverContent from '../PopoverContent';+import ToolListGroup, { type ToolGroupMeta } from '../ToolListGroup';+import { buildAgentToolRows, countAvailableTools } from './agentToolRows';+import ConnectionMenu from './ConnectionMenu';+import { isAvailableLibraryConnection, isComposioConnection } from './useOwnConnection';++interface Props extends Pick<AgentToolProps, 'onOpenDetail'> {+ agentId: string;+ group: ToolGroupMeta;+}++const Tools = ({ agentId, group, onOpenDetail }: Props) => {+ const { t } = useTranslation('setting');+ const tools = useControls();+ const [open, setOpen] = useState(false);++ const activeWorkspaceId = useActiveWorkspaceId();+ const inWorkspace = !!activeWorkspaceId;+ const isWorkspaceOwner = useIsWorkspaceOwner();+ const currentUserId = useUserStore((s) => s.user?.id);+ const isComposioEnabled = useServerConfigStore(serverConfigSelectors.enableComposio);++ const isInit = useToolStore(connectorSelectors.isAgentConnectorsInit(agentId));+ const useFetchAgentConnectors = useToolStore((s) => s.useFetchAgentConnectors);+ const { error, isValidating, revalidate } = useFetchAgentConnectors(agentId);++ const agentConnectors = useToolStore(connectorSelectors.agentConnectors(agentId), isEqual);+ const libraryLoaded = useToolStore((s) => s.isConnectorsInit);+ const libraryConnectors = useToolStore(connectorSelectors.connectorList, isEqual);+ const config = useAgentStore(agentSelectors.getAgentConfigById(agentId));+ const plugins = config?.plugins;+ const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);++ const rows = buildAgentToolRows({+ agentConnectors,+ agentId,+ chatConfig: config?.chatConfig,+ libraryOptions: tools.toolOptions,+ plugins,+ });++ // In a workspace a connection carries someone's credentials: only that member or an owner+ // may copy, replace or delete it. Everyone else sees the row without the choice.+ const canManage = (connector: ConnectorWithTools) =>+ tools.canEdit &&+ (!inWorkspace || !connector.userId || connector.userId === currentUserId || isWorkspaceOwner);++ /** The library's connection for a tool that signs in somewhere; nothing for other tools. */+ const libraryConnectionOf = (identifier: string) =>+ libraryConnectors.find(+ (c) =>+ c.identifier === identifier &&+ isAvailableLibraryConnection(c, agentId) &&+ (!isComposioConnection(c) || isComposioEnabled),+ );++ const ownConnectionNote: ItemConnection = {+ desc: t(+ inWorkspace+ ? 'settingAgent.tools.connection.ownDescWorkspace'+ : 'settingAgent.tools.connection.ownDesc',+ ),+ label: t('settingAgent.tools.connection.own'),+ title: t('settingAgent.tools.connection.ownTitle'),+ };+ const libraryConnectionNote: ItemConnection = {+ desc: t(+ inWorkspace+ ? 'settingAgent.tools.connection.workspaceDesc'+ : 'settingAgent.tools.connection.libraryDesc',+ ),+ title: t(+ inWorkspace+ ? 'settingAgent.tools.connection.workspaceTitle'+ : 'settingAgent.tools.connection.libraryTitle',+ ),+ };++ const setEnabled = (+ id: string,+ ownConnection: ConnectorWithTools | undefined,+ enabled: boolean,+ ) => {+ if (!ownConnection) return void tools.setPolicy(id, enabled ? 'auto' : 'disabled');+ // An agent's own connector stays independently switchable when the library needs authorization.+ void updateAgentConfigById(agentId, {+ plugins: upsertConnectorEnabled(plugins, id, enabled),+ });+ };++ const items: ItemType[] = (['lobehub', 'community', 'custom'] as const).flatMap((source) => {+ const children = tools.toolOptions+ .filter((tool) => tool.group === source)+ .map((tool) => ({+ key: tool.id,+ icon: tool.icon,+ searchText: tool.searchText,+ popoverContent: tool.detail,+ label: tool.connectionAction ?? (+ <ToolItem+ checked={tool.enabled}+ disabled={!tools.canEdit || !tool.canDisable}+ id={tool.id}+ label={tool.title}+ onUpdate={(id, enabled) => tools.setPolicy(id, enabled ? 'auto' : 'disabled')}+ />+ ),+ }));+ return children.length+ ? [{ children, key: source, label: t(`skillStore.tabs.${source}`), type: 'group' as const }]+ : [];+ });++ const list = (+ <ToolListGroup+ {...group}+ activeCount={rows.filter((row) => row.enabled).length}+ emptyText={t('settingAgent.toolsPage.group.empty')}+ fold={false}+ total={countAvailableTools(rows, tools.totalCount)}+ addControl={+ <ActionDropdown+ maxWidth={400}+ menu={{ items: [], style: { maxHeight: 'unset', overflowY: 'visible' } }}+ minWidth={400}+ open={open}+ placement="bottomLeft"+ popupProps={{ style: { padding: 0 } }}+ trigger="click"+ popupRender={() => (+ <ProfilePopoverContent+ toolsOnly+ items={items}+ onClose={() => setOpen(false)}+ onConnectForAgent={+ isComposioEnabled && tools.canEdit+ ? () => {+ setOpen(false);+ createAgentSkillStoreModal(agentId);+ }+ : undefined+ }+ onOpenStore={() => {+ setOpen(false);+ createSkillStoreModal();+ }}+ />+ )}+ positionerProps={{+ collisionAvoidance: { align: 'flip', fallbackAxisSide: 'end', side: 'flip' },+ collisionBoundary:+ typeof document === 'undefined' ? undefined : document.documentElement,+ positionMethod: 'fixed',+ }}+ onOpenChange={setOpen}+ >+ <Button disabled={!tools.canEdit} icon={PlusIcon} size="small" type="text">+ {t('settingAgent.agentTools.add')}+ </Button>+ </ActionDropdown>+ }+ rows={rows.map(({ canDisable, enabled, id, inLibrary, ownConnection }) => {+ const libraryConnection = libraryConnectionOf(id);+ return (+ <PluginTag+ useAllMetaList+ agentId={agentId}+ disabled={!tools.canEdit || !canDisable}+ enabled={enabled}+ key={id}+ pluginId={id}+ removable={false}+ showAuthor={inWorkspace}+ variant="row"+ connection={+ ownConnection ? ownConnectionNote : libraryConnection && libraryConnectionNote+ }+ extra={+ <ConnectionMenu+ agentId={agentId}+ fallbackConnectionId={inLibrary ? libraryConnection?.id : undefined}+ libraryConnection={+ !ownConnection &&+ libraryConnection &&+ !libraryConnection.metadata?.mountedByAgentId &&+ canManage(libraryConnection)+ ? libraryConnection+ : undefined+ }+ ownConnection={+ libraryLoaded && ownConnection && canManage(ownConnection)+ ? ownConnection+ : undefined+ }+ />+ }+ onOpen={onOpenDetail}+ onToggle={(on) => setEnabled(id, ownConnection, on)}+ />+ );+ })}+ />+ );+ return (+ <AsyncBoundary+ data={isInit || undefined}+ error={error}+ isLoading={isValidating}+ onRetry={revalidate}+ >+ {list}+ </AsyncBoundary>+ );+};++/**+ * Everything the agent can act with, as one list: a row per tool, its switch, and — for a+ * tool that signs in somewhere — whether the agent uses the library's connection or its own.+ *+ * The list and its nested search/memory settings must read and write the profile being+ * edited, even when another agent is open in the composer.+ */+const AgentToolList = ({ agentId, ...props }: Props) => (+ <Provider createStore={() => createStore({ agentId })} key={agentId}>+ <Tools agentId={agentId} {...props} />+ </Provider>+);++export default AgentToolList;diff --git a/src/features/ProfileEditor/AgentUserTools/AgentToolsSection.tsx b/src/features/ProfileEditor/AgentUserTools/AgentToolsSection.tsxdeleted file mode 100644index bd831af418c..00000000000--- a/src/features/ProfileEditor/AgentUserTools/AgentToolsSection.tsx+++ /dev/null@@ -1,167 +0,0 @@-'use client';--import { getConnectorMode, upsertConnectorEnabled, upsertPluginMode } from '@lobechat/types';-import { Button, confirmModal, DropdownMenu, Flexbox, Icon, Text } from '@lobehub/ui';-import isEqual from 'fast-deep-equal';-import { CopyIcon, PlugZapIcon, PlusIcon } from 'lucide-react';-import { memo } from 'react';-import { useTranslation } from 'react-i18next';--import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';-import { useIsWorkspaceOwner } from '@/business/client/hooks/useIsWorkspaceOwner';-import { createAgentSkillStoreModal } from '@/features/AgentSkillStore';-import { type ItemDetail } from '@/features/ProfileEditor/ItemDetailPanel';-import PluginTag from '@/features/ProfileEditor/PluginTag';-import ToolListGroup, { type ToolGroupMeta } from '@/features/ProfileEditor/ToolListGroup';-import { usePermission } from '@/hooks/usePermission';-import { useAgentStore } from '@/store/agent';-import { agentSelectors } from '@/store/agent/selectors';-import { useToolStore } from '@/store/tool';-import { connectorSelectors } from '@/store/tool/slices/connector';-import type { ConnectorWithTools } from '@/store/tool/slices/connector/types';-import { useUserStore } from '@/store/user';--/**- * The "Agent Tools" section (top of the tools area): the connectors owned by- * this agent, rendered with the same chips as User Tools (PluginTag). Removing- * an agent chip is a two-step op — unpin it from `agents.plugins` AND delete the- * agent-owned `user_connectors` row (one more step than the user side).- */-const AgentToolsSection = memo<{- agentId: string;- onStartCopy: () => void;- /** The heading, description and action of the list; only the `list` variant shows them. */- group?: ToolGroupMeta;- /** Called with a connector's details when its row is clicked. */- onOpenDetail?: (detail: ItemDetail) => void;- /** `list` shows one row per tool as a settings group. */- variant?: 'chip' | 'list';-}>(({ agentId, group, onOpenDetail, onStartCopy, variant = 'chip' }) => {- const { t } = useTranslation('setting');- const { allowed: canEdit } = usePermission('edit_own_content');-- // Deleting an agent connector row is creator-or-owner only in a workspace- // (mirrors the server `assertWorkspaceRowManageable` gate). Used to hide the- // remove (×) on shared connectors the current member can't delete, so B- // never clicks into a FORBIDDEN error on A's connector.- const activeWorkspaceId = useActiveWorkspaceId();- const isWorkspaceOwner = useIsWorkspaceOwner();- const currentUserId = useUserStore((s) => s.user?.id);-- const agentConnectors = useToolStore(connectorSelectors.agentConnectors(agentId), isEqual);- const detachConnectorFromAgent = useToolStore((s) => s.detachConnectorFromAgent);- const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);-- const handleRemove = async (connector: ConnectorWithTools) => {- const ok = await confirmModal({ content: t('settingAgent.agentTools.removeOwnedConfirm') });- if (!ok) return;- // 1) remove from agents.plugins, 2) delete the agent connector row.- const config = agentSelectors.getAgentConfigById(agentId)(useAgentStore.getState());- await updateAgentConfigById(agentId, {- plugins: upsertPluginMode(config?.plugins, connector.identifier, 'auto'),- });- await detachConnectorFromAgent(connector.id, agentId, 'delete');- };-- const addMenuItems = [- {- desc: t('settingAgent.agentTools.connectNew.desc'),- icon: PlugZapIcon,- key: 'connectNew',- label: t('settingAgent.agentTools.connectNew.title'),- onClick: () => createAgentSkillStoreModal(agentId),- },- {- desc: t('settingAgent.agentTools.copy.desc'),- icon: CopyIcon,- key: 'copy',- label: t('settingAgent.agentTools.copy.title'),- onClick: onStartCopy,- },- ];-- const isList = variant === 'list';-- const addButton = (- <DropdownMenu items={addMenuItems} placement={'bottomLeft'}>- <Button disabled={!canEdit} icon={<Icon icon={PlusIcon} />} size={'small'} type={'text'}>- {t('settingAgent.agentTools.add')}- </Button>- </DropdownMenu>- );-- const config = useAgentStore(agentSelectors.getAgentConfigById(agentId));- const agentPlugins = config?.plugins;- const setEnabled = (identifier: string, enabled: boolean) =>- updateAgentConfigById(agentId, {- plugins: upsertConnectorEnabled(agentPlugins, identifier, enabled),- });-- const tags = agentConnectors.map((connector) => {- // Outside a workspace (personal), or when the row has no known- // creator, fall back to the existing edit-permission gate. In a- // workspace, only the creator or a workspace owner may delete.- const canManageRow =- !activeWorkspaceId ||- !connector.userId ||- connector.userId === currentUserId ||- isWorkspaceOwner;- return (- <PluginTag- agentId={agentId}- disabled={!canEdit}- key={connector.id}- pluginId={connector.identifier}- removable={canManageRow}- showAuthor={!!activeWorkspaceId}- variant={isList ? 'row' : 'chip'}- enabled={- getConnectorMode(agentPlugins, connector.identifier, config?.chatConfig) === 'auto'- }- onOpen={isList ? onOpenDetail : undefined}- onToggle={isList ? (next) => void setEnabled(connector.identifier, next) : undefined}- onRemove={() => {- handleRemove(connector);- }}- />- );- });-- if (isList && group) {- return (- <ToolListGroup- {...group}- addControl={addButton}- emptyText={t('settingAgent.agentTools.agentEmpty')}- rows={tags}- activeCount={- agentConnectors.filter(- (connector) =>- getConnectorMode(agentPlugins, connector.identifier, config?.chatConfig) === 'auto',- ).length- }- />- );- }-- return (- <Flexbox gap={8}>- <Text style={{ fontSize: 12, fontWeight: 500 }} type={'secondary'}>- {t('settingAgent.agentTools.tabAgent')} · {agentConnectors.length}- </Text>- <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>- {addButton}- {agentConnectors.length === 0 && (- <Text style={{ fontSize: 12 }} type={'secondary'}>- {t('settingAgent.agentTools.agentEmpty')}- </Text>- )}- {tags}- </Flexbox>- </Flexbox>- );-});--AgentToolsSection.displayName = 'AgentToolsSection';--export default AgentToolsSection;diff --git a/src/features/ProfileEditor/AgentUserTools/ConnectionMenu.tsx b/src/features/ProfileEditor/AgentUserTools/ConnectionMenu.tsxnew file mode 100644index 00000000000..9b04b65e870--- /dev/null+++ b/src/features/ProfileEditor/AgentUserTools/ConnectionMenu.tsx@@ -0,0 +1,102 @@+'use client';++import { ActionIcon, Center, DropdownMenu, Icon } from '@lobehub/ui';+import {+ LibraryIcon,+ MoreHorizontalIcon,+ Settings2Icon,+ Trash2Icon,+ UserRoundPlusIcon,+} from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import type { ConnectorWithTools } from '@/store/tool/slices/connector/types';++import { isComposioConnection, useOwnConnection } from './useOwnConnection';++interface ConnectionMenuProps {+ agentId: string;+ /** The library offers this tool, so giving up the own connection falls back to it. */+ fallbackConnectionId?: string;+ /** The library's connection, when the agent may take one of its own from it. */+ libraryConnection?: ConnectorWithTools;+ /** The agent's own connection, when the current person may manage it. */+ ownConnection?: ConnectorWithTools;+}++/**+ * The "…" of a tool row: what can be done about the connection it runs on. A row with nothing+ * to choose (a built-in tool, a plugin, a connection someone else manages) has no menu.+ */+const ConnectionMenu = ({+ agentId,+ fallbackConnectionId,+ libraryConnection,+ ownConnection,+}: ConnectionMenuProps) => {+ const { t } = useTranslation('setting');+ const inWorkspace = !!useActiveWorkspaceId();+ const { create, manage, remove, revertToLibrary } = useOwnConnection(agentId);++ const items = ownConnection+ ? [+ {+ icon: <Icon icon={Settings2Icon} />,+ key: 'manage',+ label: t('settingAgent.tools.connection.manage'),+ onClick: () => manage(ownConnection),+ },+ fallbackConnectionId+ ? {+ icon: <Icon icon={LibraryIcon} />,+ key: 'useLibrary',+ label: t(+ inWorkspace+ ? 'settingAgent.tools.connection.useWorkspace'+ : 'settingAgent.tools.connection.useLibrary',+ ),+ onClick: () => revertToLibrary(ownConnection, fallbackConnectionId),+ }+ : {+ danger: true,+ icon: <Icon icon={Trash2Icon} />,+ key: 'remove',+ label: t('settingAgent.tools.remove'),+ onClick: () => remove(ownConnection),+ },+ ]+ : libraryConnection+ ? [+ {+ desc: t('settingAgent.tools.connection.createDesc'),+ icon: <Icon icon={UserRoundPlusIcon} />,+ key: 'create',+ label: t(+ isComposioConnection(libraryConnection)+ ? 'settingAgent.tools.connection.createAccount'+ : 'settingAgent.tools.connection.create',+ ),+ onClick: () => void create(libraryConnection),+ },+ ]+ : [];++ // The slot keeps its width when empty, so the kind labels of every row stay in one column.+ return (+ <Center flex={'none'} width={24}>+ {items.length > 0 ? (+ <DropdownMenu items={items} placement={'bottomRight'}>+ <ActionIcon+ aria-label={t('settingAgent.tools.connection.menu')}+ icon={MoreHorizontalIcon}+ size={'small'}+ title={t('settingAgent.tools.connection.menu')}+ />+ </DropdownMenu>+ ) : null}+ </Center>+ );+};++export default ConnectionMenu;diff --git a/src/features/ProfileEditor/AgentUserTools/ProfileToolPicker.tsx b/src/features/ProfileEditor/AgentUserTools/ProfileToolPicker.tsxdeleted file mode 100644index f88df2d404d..00000000000--- a/src/features/ProfileEditor/AgentUserTools/ProfileToolPicker.tsx+++ /dev/null@@ -1,115 +0,0 @@-'use client';--import { Button, type ItemType } from '@lobehub/ui';-import { PlusIcon } from 'lucide-react';-import { useState } from 'react';-import { useTranslation } from 'react-i18next';--import ActionDropdown from '@/features/ChatInput/ActionBar/components/ActionDropdown';-import ToolItem from '@/features/ChatInput/ActionBar/Tools/ToolItem';-import { useControls } from '@/features/ChatInput/ActionBar/Tools/useControls';-import { createStore, Provider } from '@/features/ChatInput/store';-import { createSkillStoreModal } from '@/features/SkillStore';--import type { AgentToolProps } from '../AgentTool';-import PluginTag from '../PluginTag';-import ProfilePopoverContent from '../PopoverContent';-import ToolListGroup, { type ToolGroupMeta } from '../ToolListGroup';--interface Props extends Pick<AgentToolProps, 'onOpenDetail' | 'showAuthor'> {- agentId: string;- group: ToolGroupMeta;-}--const LibraryTools = ({ group, onOpenDetail, showAuthor }: Omit<Props, 'agentId'>) => {- const { t } = useTranslation('setting');- const tools = useControls();- const [open, setOpen] = useState(false);- const items: ItemType[] = (['lobehub', 'community', 'custom'] as const).flatMap((source) => {- const children = tools.toolOptions- .filter((tool) => tool.group === source)- .map((tool) => ({- key: tool.id,- icon: tool.icon,- searchText: tool.searchText,- popoverContent: tool.detail,- label: tool.connectionAction ?? (- <ToolItem- checked={tool.enabled}- disabled={!tools.canEdit || !tool.canDisable}- id={tool.id}- label={tool.title}- onUpdate={(id, enabled) => tools.setPolicy(id, enabled ? 'auto' : 'disabled')}- />- ),- }));- return children.length- ? [{ children, key: source, label: t(`skillStore.tabs.${source}`), type: 'group' as const }]- : [];- });- return (- <ToolListGroup- {...group}- activeCount={tools.autoCount}- emptyText={t('settingAgent.tools.level.libraryEmpty')}- total={tools.totalCount}- addControl={- <ActionDropdown- maxWidth={400}- menu={{ items: [], style: { maxHeight: 'unset', overflowY: 'visible' } }}- minWidth={400}- open={open}- placement="bottomLeft"- popupProps={{ style: { padding: 0 } }}- trigger="click"- popupRender={() => (- <ProfilePopoverContent- toolsOnly- items={items}- onClose={() => setOpen(false)}- onOpenStore={() => {- setOpen(false);- createSkillStoreModal();- }}- />- )}- positionerProps={{- collisionAvoidance: { align: 'flip', fallbackAxisSide: 'end', side: 'flip' },- collisionBoundary:- typeof document === 'undefined' ? undefined : document.documentElement,- positionMethod: 'fixed',- }}- onOpenChange={setOpen}- >- <Button disabled={!tools.canEdit} icon={PlusIcon} size="small" type="text">- {t('settingAgent.agentTools.add')}- </Button>- </ActionDropdown>- }- rows={tools.activeTools.map(({ id, canDisable }) => (- <PluginTag- enabled- useAllMetaList- disabled={!tools.canEdit || !canDisable}- key={id}- pluginId={id}- removable={false}- showAuthor={showAuthor}- variant="row"- onOpen={onOpenDetail}- onToggle={(on) => void tools.setPolicy(id, on ? 'auto' : 'disabled')}- />- ))}- />- );-};--// The picker and its nested search/memory settings must read and write the-// profile being edited, even when another agent is open in the composer.-const ProfileToolPicker = ({ agentId, ...props }: Props) => (- <Provider createStore={() => createStore({ agentId })} key={agentId}>- <LibraryTools {...props} />- </Provider>-);--export default ProfileToolPicker;diff --git a/src/features/ProfileEditor/AgentUserTools/RunPriorityHint.tsx b/src/features/ProfileEditor/AgentUserTools/RunPriorityHint.tsxdeleted file mode 100644index 802960b0754..00000000000--- a/src/features/ProfileEditor/AgentUserTools/RunPriorityHint.tsx+++ /dev/null@@ -1,51 +0,0 @@-'use client';--import { Flexbox, Icon, Tooltip } from '@lobehub/ui';-import { InfoIcon } from 'lucide-react';-import { memo } from 'react';-import { useTranslation } from 'react-i18next';--import { useAgentStore } from '@/store/agent';-import { agentByIdSelectors } from '@/store/agent/selectors';--interface RunPriorityHintProps {- agentId?: string;-}--/**- * The "Run priority" hint shown in the top-right of the Model & Tools panel.- * The tooltip is context-aware:- * - Personal agent: agent-exclusive tools win over the user's tools.- * - Workspace agent: the agent-scoped tools win, falling back to the- * workspace's user-scoped tools.- */-const RunPriorityHint = memo<RunPriorityHintProps>(({ agentId }) => {- const { t } = useTranslation('setting');- const activeAgentId = useAgentStore((s) => s.activeAgentId);- const effectiveAgentId = agentId || activeAgentId || '';- const isWorkspaceAgent = useAgentStore(agentByIdSelectors.isWorkspaceAgentById(effectiveAgentId));-- return (- <Tooltip- title={t(- isWorkspaceAgent- ? 'settingAgent.agentTools.priorityTooltipWorkspace'- : 'settingAgent.agentTools.priorityTooltip',- )}- >- <Flexbox- horizontal- align={'center'}- gap={4}- style={{ cursor: 'help', fontSize: 12, opacity: 0.55 }}- >- <Icon icon={InfoIcon} size={14} />- {t('settingAgent.agentTools.priorityHint')}- </Flexbox>- </Tooltip>- );-});--RunPriorityHint.displayName = 'RunPriorityHint';--export default RunPriorityHint;diff --git a/src/features/ProfileEditor/AgentUserTools/UserToolsSection.test.tsx b/src/features/ProfileEditor/AgentUserTools/UserToolsSection.test.tsxdeleted file mode 100644index 97528fa8e7b..00000000000--- a/src/features/ProfileEditor/AgentUserTools/UserToolsSection.test.tsx+++ /dev/null@@ -1,206 +0,0 @@-/**- * @vitest-environment happy-dom- */-import { render, screen } from '@testing-library/react';-import type { ReactNode } from 'react';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import UserToolsSection from './UserToolsSection';--// Regression for the profile "double display" bug: an agent-scoped connector-// (e.g. a Composio account bound to this agent) is pinned into `config.plugins`-// for runtime gating. It is rendered in the "Agent Tools" section above; it must-// NOT also be counted/shown in this base ("Workspace/User") section — where,-// lacking a base-dimension manifest, it rendered as an extra "uninstalled" chip-// and inflated the header count.--const mocks = vi.hoisted(() => ({- toolState: {- // connectorSelectors.agentConnectors(agentId) reads s.agentConnectors[agentId]- agentConnectors: {} as Record<- string,- Array<{ agentId: string; id: string; identifier: string }>- >,- builtinTools: [] as Array<{- hidden?: boolean;- identifier: string;- manifest: { api: never[]; identifier: string; meta: { title: string }; systemRole: string };- type: 'builtin';- }>,- connectors: [] as unknown[],- },- agentConfig: { plugins: [] } as {- chatConfig?: { skillActivateMode?: 'auto' | 'manual' };- plugins: unknown[];- },-}));--// Personal vs workspace only changes the label, not the count under test.-vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({- useActiveWorkspaceId: () => 'ws-1',-}));--// The chips themselves are rendered by AgentTool; stub it so this test isolates-// the header count wiring. The shared visibility predicate has focused coverage.-vi.mock('@/features/ProfileEditor/AgentTool', () => ({ default: () => null }));-vi.mock('@/features/ProfileEditor/PluginTag', () => ({ default: () => null }));--vi.mock('@lobehub/ui', async (importOriginal) => {- const actual = await importOriginal<Record<string, unknown>>();- const factories: ((original: typeof importOriginal) => unknown)[] = [- async (importOriginal) => ({- ...(await importOriginal<object>()),- Text: ({ children }: { children: ReactNode }) => <span data-testid="label">{children}</span>,- }),- async (importOriginal) => ({- ...(await importOriginal<object>()),- Text: ({ children }: { children: ReactNode }) => <span data-testid="label">{children}</span>,- }),- ];- const merged: Record<string, unknown> = { ...actual };- for (const factory of factories) {- const part = (await factory(importOriginal)) as Record<string, unknown>;- for (const [key, value] of Object.entries(part)) if (value !== actual[key]) merged[key] = value;- }- return merged;-});--// Apply the real selectors against the mock state.-vi.mock('@/store/tool', () => ({- useToolStore: (sel: (s: unknown) => unknown) => sel(mocks.toolState),-}));-vi.mock('@/store/agent', () => ({- useAgentStore: (sel: (s: unknown) => unknown) => sel(undefined),-}));-vi.mock('@/store/agent/selectors', () => ({- agentSelectors: { getAgentConfigById: () => () => mocks.agentConfig },-}));--const renderSection = () =>- render(- <UserToolsSection- agentId="agent-1"- copyMode={false}- copying={false}- selected={new Set()}- toggleSelected={() => {}}- onCancelCopy={() => {}}- onConfirmCopy={() => {}}- />,- );--const labelText = () => screen.getByTestId('label').textContent;--describe('UserToolsSection — Workspace/User tool count', () => {- beforeEach(() => {- mocks.toolState.agentConnectors = {};- mocks.toolState.builtinTools = [];- mocks.toolState.connectors = [];- mocks.agentConfig = { plugins: [] };- });-- it('does not count an agent-owned connector identifier pinned in config.plugins', () => {- // google-drive is pinned for the agent AND is an agent-owned connector row →- // it belongs to the Agent Tools section, so this section's count must be 0.- mocks.agentConfig = { plugins: [{ identifier: 'google-drive', mode: 'pinned' }] };- mocks.toolState.agentConnectors = {- 'agent-1': [{ agentId: 'agent-1', id: 'c1', identifier: 'google-drive' }],- };-- renderSection();-- expect(labelText()).toContain('· 0');- });-- it('still counts a genuine base pinned tool that is not an agent connector', () => {- mocks.agentConfig = {- plugins: [- { identifier: 'google-drive', mode: 'pinned' }, // agent-owned → excluded- { identifier: 'some-user-plugin', mode: 'pinned' }, // base → counted- ],- };- mocks.toolState.agentConnectors = {- 'agent-1': [{ agentId: 'agent-1', id: 'c1', identifier: 'google-drive' }],- };-- renderSection();-- expect(labelText()).toContain('· 1');- });-- it('counts a newly connected tool without an agent configuration entry', () => {- mocks.toolState.connectors = [- { identifier: 'notion', sourceType: 'custom', status: 'connected', isEnabled: true },- { identifier: 'slack', sourceType: 'custom', status: 'pending', isEnabled: true },- ];- renderSection();- expect(labelText()).toContain('· 1');- });-- it('counts a connector turned on with an auto entry and leaves out one turned off', () => {- // A connector is two-state: on is an explicit `auto` entry, never a pin.- mocks.agentConfig = {- plugins: [- { identifier: 'gmail', mode: 'auto' },- { identifier: 'slack', mode: 'disabled' },- ],- };-- renderSection();-- expect(labelText()).toContain('· 1');- });-- it('does not count Web Browsing even when a legacy plugin entry is pinned', () => {- mocks.agentConfig = {- plugins: [- { identifier: 'lobe-web-browsing', mode: 'pinned' },- { identifier: 'some-user-plugin', mode: 'pinned' },- ],- };- mocks.toolState.builtinTools = [- {- hidden: true,- identifier: 'lobe-web-browsing',- manifest: {- api: [],- identifier: 'lobe-web-browsing',- meta: { title: 'Web Browsing' },- systemRole: '',- },- type: 'builtin',- },- ];-- renderSection();-- expect(labelText()).toContain('· 1');- });-- it.each(['auto', 'manual'] as const)(- 'counts a pinned Skill Store in %s mode',- (skillActivateMode) => {- mocks.agentConfig = {- chatConfig: { skillActivateMode },- plugins: [{ identifier: 'lobe-skill-store', mode: 'pinned' }],- };- mocks.toolState.builtinTools = [- {- hidden: true,- identifier: 'lobe-skill-store',- manifest: {- api: [],- identifier: 'lobe-skill-store',- meta: { title: 'Skill Store' },- systemRole: '',- },- type: 'builtin',- },- ];-- renderSection();-- expect(labelText()).toContain('· 1');- },- );-});diff --git a/src/features/ProfileEditor/AgentUserTools/UserToolsSection.tsx b/src/features/ProfileEditor/AgentUserTools/UserToolsSection.tsxdeleted file mode 100644index 753f6fd1696..00000000000--- a/src/features/ProfileEditor/AgentUserTools/UserToolsSection.tsx+++ /dev/null@@ -1,163 +0,0 @@-'use client';--import { getConnectorMode, getOptedInPluginIds } from '@lobechat/types';-import { Button, Flexbox, Text } from '@lobehub/ui';-import isEqual from 'fast-deep-equal';-import { memo, useMemo } from 'react';-import { useTranslation } from 'react-i18next';--import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';-import type { AgentToolProps } from '@/features/ProfileEditor/AgentTool';-import SharedAgentTool from '@/features/ProfileEditor/AgentTool';-import PluginTag from '@/features/ProfileEditor/PluginTag';-import { getVisibleProfileToolIds } from '@/features/ProfileEditor/profileToolVisibility';-import { getConnectedConnectorIds } from '@/helpers/toolEngineering/connectorActivation';-import { useAgentStore } from '@/store/agent';-import { agentSelectors } from '@/store/agent/selectors';-import { useToolStore } from '@/store/tool';-import { builtinToolSelectors } from '@/store/tool/selectors';-import { connectorSelectors } from '@/store/tool/slices/connector';--interface Props extends AgentToolProps {- agentId: string;- copying: boolean;- copyMode: boolean;- onCancelCopy: () => void;- onConfirmCopy: () => void;- selected: Set<string>;- toggleSelected: (id: string) => void;- /** `list` shows one row per tool under a heading supplied by the caller. */- variant?: 'chip' | 'list';-}--/**- * The "User Tools" section (bottom of the tools area). Normally the user's- * pinned tools (SharedAgentTool). In copy mode, the user's connectors become- * selectable chips so several can be copied into the agent at once.- */-const UserToolsSection = memo<Props>(- ({- agentId,- copyMode,- copying,- onCancelCopy,- onConfirmCopy,- selected,- toggleSelected,- variant = 'chip',- ...toolProps- }) => {- const { t } = useTranslation('setting');- const userConnectors = useToolStore(connectorSelectors.connectorList, isEqual);- const config = useAgentStore(agentSelectors.getAgentConfigById(agentId), isEqual);- const isManualSkillMode = config?.chatConfig?.skillActivateMode === 'manual';- // Agent-owned/linked connector identifiers are shown in the Agent Tools- // section above (and excluded from this section's chips in `AgentTool`), so- // exclude them from the count too — otherwise the header would count a tool- // that renders in the section above, not here.- const agentConnectors = useToolStore(connectorSelectors.agentConnectors(agentId), isEqual);- const agentConnectorIdentifiers = useMemo(- () => new Set(agentConnectors.map((c) => c.identifier)),- [agentConnectors],- );- const nonProfileConfigurableBuiltinToolIds = useToolStore(- builtinToolSelectors.nonProfileConfigurableBuiltinToolIds({- isManualMode: isManualSkillMode,- }),- isEqual,- );- const nonProfileConfigurableBuiltinToolIdentifiers = useMemo(- () => new Set(nonProfileConfigurableBuiltinToolIds),- [nonProfileConfigurableBuiltinToolIds],- );- const connectedIds = useToolStore((s) => getConnectedConnectorIds(s, agentId), isEqual);- const userToolCount = getVisibleProfileToolIds(- [- ...new Set([- ...getOptedInPluginIds(config?.plugins),- ...connectedIds.filter(- (id) => getConnectorMode(config?.plugins, id, config?.chatConfig) === 'auto',- ),- ]),- ],- {- agentConnectorIdentifiers,- nonConfigurableBuiltinToolIdentifiers: nonProfileConfigurableBuiltinToolIdentifiers,- },- ).length;- // In a workspace, this section's base tools are the WORKSPACE dimension- // (`connector.list` is workspace-scoped), not the caller's personal tools —- // label it so the user knows the tools are shared workspace-scoped, not- // their private ones. Personal mode keeps the "User Tools" label.- const activeWorkspaceId = useActiveWorkspaceId();- const baseToolsLabel = activeWorkspaceId- ? t('settingAgent.agentTools.tabWorkspace')- : t('settingAgent.agentTools.tabUser');-- // Copyable = the user's own base connectors (not agent-owned, not mounted).- const copyable = userConnectors.filter((c) => !c.agentId && !c.metadata?.mountedByAgentId);-- if (copyMode) {- return (- <Flexbox gap={8}>- <Flexbox horizontal align={'center'} justify={'space-between'}>- <Text style={{ fontSize: 12 }} type={'secondary'}>- {t('settingAgent.agentTools.copyPick')}- </Text>- <Flexbox horizontal gap={8}>- <Button disabled={copying} size={'small'} type={'text'} onClick={onCancelCopy}>- {t('cancel', { ns: 'common' })}- </Button>- <Button- disabled={selected.size === 0 || copying}- loading={copying}- size={'small'}- type={'primary'}- onClick={onConfirmCopy}- >- {t('settingAgent.agentTools.copyConfirm', { count: selected.size })}- </Button>- </Flexbox>- </Flexbox>- <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>- {copyable.length === 0 && (- <Text style={{ fontSize: 12 }} type={'secondary'}>- {t('settingAgent.agentTools.pickerEmpty')}- </Text>- )}- {copyable.map((c) => (- <PluginTag- selectable- key={c.id}- pluginId={c.identifier}- selected={selected.has(c.id)}- onSelect={() => toggleSelected(c.id)}- />- ))}- </Flexbox>- </Flexbox>- );- }-- return (- <Flexbox gap={8}>- {variant === 'chip' && (- <Text style={{ fontSize: 12, fontWeight: 500 }} type={'secondary'}>- {baseToolsLabel} · {userToolCount}- </Text>- )}- <SharedAgentTool- {...toolProps}- excludeAgentConnectors- agentId={agentId}- showAuthor={!!activeWorkspaceId}- variant={variant}- />- </Flexbox>- );- },-);--UserToolsSection.displayName = 'UserToolsSection';--export default UserToolsSection;diff --git a/src/features/ProfileEditor/AgentUserTools/agentToolRows.test.ts b/src/features/ProfileEditor/AgentUserTools/agentToolRows.test.tsnew file mode 100644index 00000000000..f6820b76883--- /dev/null+++ b/src/features/ProfileEditor/AgentUserTools/agentToolRows.test.ts@@ -0,0 +1,171 @@+import { describe, expect, it } from 'vitest';++import type { ConnectorWithTools } from '@/store/tool/slices/connector/types';++import { buildAgentToolRows, countAvailableTools } from './agentToolRows';++const AGENT = 'agt_1';++const connector = (+ identifier: string,+ overrides: Partial<ConnectorWithTools> = {},+): ConnectorWithTools => ({+ agentId: AGENT,+ credentials: null,+ id: `row-${identifier}`,+ identifier,+ isEnabled: true,+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://example.com/mcp',+ metadata: null,+ name: identifier,+ sourceType: 'custom',+ status: 'connected',+ tools: [],+ ...overrides,+});++const option = (id: string, enabled: boolean, canDisable = true) => ({ canDisable, enabled, id });++describe('buildAgentToolRows', () => {+ it('lists the tools that are on, in the order the library lists them', () => {+ const rows = buildAgentToolRows({+ agentConnectors: [],+ agentId: AGENT,+ libraryOptions: [+ option('search', true, false),+ option('notion', false),+ option('linear', true),+ ],+ plugins: [{ identifier: 'linear', mode: 'auto' }],+ });++ expect(rows.map((row) => row.id)).toEqual(['search', 'linear']);+ expect(rows.every((row) => row.inLibrary && !row.ownConnection)).toBe(true);+ expect(rows[0].canDisable).toBe(false);+ });++ it('lists a tool once when the agent has its own connection and the library has one too', () => {+ const own = connector('notion');+ const rows = buildAgentToolRows({+ agentConnectors: [own],+ agentId: AGENT,+ libraryOptions: [option('notion', true), option('linear', true)],+ plugins: [+ { identifier: 'notion', mode: 'auto' },+ { identifier: 'linear', mode: 'auto' },+ ],+ });++ expect(rows.map((row) => row.id)).toEqual(['notion', 'linear']);+ expect(rows[0]).toMatchObject({ enabled: true, inLibrary: true, ownConnection: own });+ expect(rows[1].ownConnection).toBeUndefined();+ });++ it.each(['auto', 'disabled'] as const)(+ 'keeps the own account switch editable and reflects its %s mode when the library account needs authorization',+ (mode) => {+ const own = connector('gmail', { metadata: { composio: { status: 'ACTIVE' } } });+ const rows = buildAgentToolRows({+ agentConnectors: [own],+ agentId: AGENT,+ libraryOptions: [option('gmail', false, false)],+ plugins: [{ identifier: 'gmail', mode }],+ });++ expect(rows).toMatchObject([+ { canDisable: true, enabled: mode === 'auto', ownConnection: own },+ ]);+ },+ );++ it('keeps a tool with its own connection in place when it is turned off', () => {+ const rows = buildAgentToolRows({+ agentConnectors: [connector('notion')],+ agentId: AGENT,+ libraryOptions: [option('notion', false), option('linear', true)],+ plugins: [{ identifier: 'notion', mode: 'disabled' }],+ });++ expect(rows.map((row) => [row.id, row.enabled])).toEqual([+ ['notion', false],+ ['linear', true],+ ]);+ });++ it('lets a tool on its own connection be switched whatever state the library connection is in', () => {+ // A library connection awaiting authorization cannot be switched; the agent's own+ // connection works without it.+ const rows = buildAgentToolRows({+ agentConnectors: [connector('gmail')],+ agentId: AGENT,+ libraryOptions: [option('gmail', true, false), option('search', true, false)],+ plugins: [{ identifier: 'gmail', mode: 'auto' }],+ });++ expect(rows.map((row) => [row.id, row.canDisable])).toEqual([+ ['gmail', true],+ ['search', false],+ ]);+ });++ it('adds the tools only this agent has after the library ones, with their own switch', () => {+ const rows = buildAgentToolRows({+ agentConnectors: [connector('sentry'), connector('jira')],+ agentId: AGENT,+ libraryOptions: [option('search', true)],+ plugins: [{ identifier: 'sentry', mode: 'auto' }],+ });++ expect(rows.map((row) => [row.id, row.enabled, row.inLibrary])).toEqual([+ ['search', true, true],+ ['sentry', true, false],+ ['jira', true, false],+ ]);+ });++ it('keeps unconfigured own connectors off in a custom toolset, including those also in the library', () => {+ const rows = buildAgentToolRows({+ agentConnectors: [connector('sentry'), connector('jira')],+ agentId: AGENT,+ chatConfig: { toolMode: 'custom' },+ libraryOptions: [option('jira', false)],+ plugins: [],+ });++ expect(rows.map(({ id, enabled }) => [id, enabled])).toEqual([+ ['jira', false],+ ['sentry', false],+ ]);+ });++ it('treats a library connection lent to the agent as the library connection', () => {+ const lent = connector('notion', {+ agentId: null,+ metadata: { mountedByAgentId: AGENT },+ });+ const rows = buildAgentToolRows({+ agentConnectors: [lent],+ agentId: AGENT,+ libraryOptions: [option('notion', true)],+ plugins: [{ identifier: 'notion', mode: 'auto' }],+ });++ expect(rows).toEqual([+ { canDisable: true, enabled: true, id: 'notion', inLibrary: true, ownConnection: undefined },+ ]);+ });+});++describe('countAvailableTools', () => {+ it('counts the tools only this agent has on top of the library total', () => {+ const rows = buildAgentToolRows({+ agentConnectors: [connector('notion'), connector('sentry')],+ agentId: AGENT,+ libraryOptions: [option('notion', true)],+ plugins: [],+ });++ expect(countAvailableTools(rows, 26)).toBe(27);+ });+});diff --git a/src/features/ProfileEditor/AgentUserTools/agentToolRows.ts b/src/features/ProfileEditor/AgentUserTools/agentToolRows.tsnew file mode 100644index 00000000000..9b1c4f203e9--- /dev/null+++ b/src/features/ProfileEditor/AgentUserTools/agentToolRows.ts@@ -0,0 +1,90 @@+import { type AgentPluginEntry, getConnectorMode } from '@lobechat/types';++import type { ConnectorWithTools } from '@/store/tool/slices/connector/types';++/** A tool the library offers this agent, in the order the library lists it. */+export interface LibraryToolOption {+ canDisable: boolean;+ enabled: boolean;+ id: string;+}++/** One row of the agent's tool list: one tool, whichever connection serves it. */+export interface AgentToolRow {+ canDisable: boolean;+ enabled: boolean;+ id: string;+ /** The library offers this tool, so the agent can go back to the library's connection. */+ inLibrary: boolean;+ /** The agent's own connection for this tool; its runs use it instead of the library's. */+ ownConnection?: ConnectorWithTools;+}++interface BuildAgentToolRowsParams {+ agentConnectors: ConnectorWithTools[];+ agentId: string;+ chatConfig?: Parameters<typeof getConnectorMode>[2];+ libraryOptions: LibraryToolOption[];+ plugins: AgentPluginEntry[] | undefined;+}++/**+ * The agent's tools as one list. A tool is listed once however many connections exist for it:+ * the agent's switch is kept per tool, and a run uses the agent's own connection when it has+ * one, the library's otherwise.+ *+ * A row shows when the tool is on, or when the agent holds its own connection for it — that+ * connection exists only here, so it stays visible while off. Rows keep the library's order,+ * and tools the library does not offer follow.+ */+export const buildAgentToolRows = ({+ agentConnectors,+ agentId,+ chatConfig,+ libraryOptions,+ plugins,+}: BuildAgentToolRowsParams): AgentToolRow[] => {+ // A library connection another flow lent to the agent is still the library's.+ const owned = new Map(+ agentConnectors.filter((c) => c.agentId === agentId).map((c) => [c.identifier, c] as const),+ );++ const rows: AgentToolRow[] = [];+ const listed = new Set<string>();++ for (const option of libraryOptions) {+ if (listed.has(option.id)) continue;+ const ownConnection = owned.get(option.id);+ if (!option.enabled && !ownConnection) continue;++ listed.add(option.id);+ rows.push({+ // The library's own state (a connection awaiting authorization, say) does not hold a+ // tool the agent runs on its own connection.+ canDisable: ownConnection ? true : option.canDisable,+ enabled: ownConnection+ ? getConnectorMode(plugins, option.id, chatConfig) === 'auto'+ : option.enabled,+ id: option.id,+ inLibrary: true,+ ownConnection,+ });+ }++ for (const [identifier, ownConnection] of owned) {+ if (listed.has(identifier)) continue;+ rows.push({+ canDisable: true,+ enabled: getConnectorMode(plugins, identifier, chatConfig) === 'auto',+ id: identifier,+ inLibrary: false,+ ownConnection,+ });+ }++ return rows;+};++/** How many tools the agent could turn on: the library's, plus the ones only it has. */+export const countAvailableTools = (rows: AgentToolRow[], libraryTotal: number): number =>+ libraryTotal + rows.filter((row) => !row.inLibrary).length;diff --git a/src/features/ProfileEditor/AgentUserTools/index.tsx b/src/features/ProfileEditor/AgentUserTools/index.tsxindex 513de2cb909..5d11f3ac02f 100644--- a/src/features/ProfileEditor/AgentUserTools/index.tsx+++ b/src/features/ProfileEditor/AgentUserTools/index.tsx@@ -1,181 +1,62 @@'use client';-import { upsertConnectorEnabled } from '@lobechat/types';-import { Button, Flexbox } from '@lobehub/ui';-import isEqual from 'fast-deep-equal';-import { memo, useEffect, useState } from 'react';+import { Button } from '@lobehub/ui';+import { memo } from 'react';import { useTranslation } from 'react-i18next';import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';-import { type AgentToolProps } from '@/features/ProfileEditor/AgentTool';+import SharedAgentTool, { type AgentToolProps } from '@/features/ProfileEditor/AgentTool';import { type ToolGroupMeta } from '@/features/ProfileEditor/ToolListGroup';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { useAgentStore } from '@/store/agent';-import { agentSelectors } from '@/store/agent/selectors';-import { useToolStore } from '@/store/tool';-import { connectorSelectors } from '@/store/tool/slices/connector';-import AgentToolsSection from './AgentToolsSection';-import ProfileToolPicker from './ProfileToolPicker';-import RunPriorityHint from './RunPriorityHint';-import UserToolsSection from './UserToolsSection';+import AgentToolList from './AgentToolList';/**- * The profile "Model & Tools" tools area — a single page with two stacked- * sections: Agent Tools (top, connectors bound to this agent) and User Tools- * (bottom, the user's pinned tools). Agent tools resolve with priority over- * same-named user tools at runtime.+ * What the agent can act with, as one list per page: its tools and connectors, or its skills.+ * Each row is something the agent has turned on; the library is where they are installed,+ * connected and shared. A connector row also says when the agent signs in with a connection of+ * its own instead of the library's.*/-const AgentUserTools = memo<AgentToolProps & { variant?: 'chip' | 'list' }>((props) => {- const { agentId, variant = 'chip', ...toolProps } = props;+const AgentUserTools = memo<AgentToolProps>((props) => {+ const { agentId, ...toolProps } = props;const { t } = useTranslation('setting');const navigate = useWorkspaceAwareNavigate();- const activeWorkspaceId = useActiveWorkspaceId();+ const inWorkspace = !!useActiveWorkspaceId();const activeAgentId = useAgentStore((s) => s.activeAgentId);const effectiveAgentId = agentId || activeAgentId || '';- const isInit = useToolStore(connectorSelectors.isAgentConnectorsInit(effectiveAgentId));- const fetchAgentConnectors = useToolStore((s) => s.fetchAgentConnectors);- const copyConnectorToAgent = useToolStore((s) => s.copyConnectorToAgent);- const userConnectors = useToolStore(connectorSelectors.connectorList, isEqual);- const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);-- useEffect(() => {- if (effectiveAgentId && !isInit) fetchAgentConnectors(effectiveAgentId);- }, [effectiveAgentId, isInit, fetchAgentConnectors]);-- const [copyMode, setCopyMode] = useState(false);- const [copying, setCopying] = useState(false);- const [selected, setSelected] = useState<Set<string>>(() => new Set());-- const toggleSelected = (id: string) =>- setSelected((prev) => {- const next = new Set(prev);- if (next.has(id)) next.delete(id);- else next.add(id);- return next;- });-- const resetCopy = () => {- setCopyMode(false);- setSelected(new Set());+ const isSkills = toolProps.kind === 'skills';+ const group: ToolGroupMeta = {+ extra: (+ <Button+ size={'small'}+ type={'text'}+ onClick={() => navigate(isSkills ? '/settings/skill' : '/settings/connector')}+ >+ {t('settingAgent.tools.manageLibrary')}+ </Button>+ ),+ plain: true,+ title: t(+ isSkills ? 'settingAgent.skillsPage.group.title' : 'settingAgent.toolsPage.group.title',+ ),};- const handleConfirmCopy = async () => {- setCopying(true);- try {- const identifiers: string[] = [];- for (const id of selected) {- const conn = userConnectors.find((c) => c.id === id);- if (!conn) continue;- await copyConnectorToAgent(id, effectiveAgentId);- identifiers.push(conn.identifier);- }- // Turn the copied tools on for the agent so the runtime resolves them.- if (identifiers.length > 0) {- const config = agentSelectors.getAgentConfigById(effectiveAgentId)(- useAgentStore.getState(),- );- let plugins = config?.plugins;- for (const identifier of identifiers)- plugins = upsertConnectorEnabled(plugins, identifier, true);- await updateAgentConfigById(effectiveAgentId, { plugins });- }- resetCopy();- } finally {- setCopying(false);- }- };-- if (variant === 'list') {- // Two levels, named for what they mean to the person: what belongs to this agent alone,- // and what it borrows from the library every agent shares. Skills only ever come from the- // library, so their page has the one list.- const isSkills = toolProps.kind === 'skills';- const agentGroup: ToolGroupMeta = {- desc: t('settingAgent.tools.level.agentDesc'),- extra: <RunPriorityHint agentId={effectiveAgentId} />,- title: t('settingAgent.agentTools.tabAgent'),- };- const libraryGroup: ToolGroupMeta = {- plain: isSkills,- desc: isSkills- ? t('settingAgent.skillsPage.group.desc')- : t(- activeWorkspaceId- ? 'settingAgent.tools.level.workspaceDesc'- : 'settingAgent.tools.level.libraryDesc',- ),- extra: (- <Button size={'small'} type={'text'} onClick={() => navigate('/settings/skill')}>- {t('settingAgent.tools.manageLibrary')}- </Button>- ),- title: isSkills- ? t('settingAgent.skillsPage.group.title')- : t(- activeWorkspaceId- ? 'settingAgent.agentTools.tabWorkspace'- : 'settingAgent.agentTools.tabUser',- ),- };-+ if (isSkills)return (- <Flexbox gap={16} width={'100%'}>- {!isSkills && (- <AgentToolsSection- agentId={effectiveAgentId}- group={agentGroup}- variant={'list'}- onOpenDetail={toolProps.onOpenDetail}- onStartCopy={() => setCopyMode(true)}- />- )}- {toolProps.kind === 'tools' && !copyMode ? (- <ProfileToolPicker- agentId={effectiveAgentId}- group={libraryGroup}- showAuthor={!!activeWorkspaceId}- onOpenDetail={toolProps.onOpenDetail}- />- ) : (- <UserToolsSection- {...toolProps}- agentId={effectiveAgentId}- copyMode={copyMode}- copying={copying}- group={libraryGroup}- selected={selected}- toggleSelected={toggleSelected}- variant={'list'}- onCancelCopy={resetCopy}- onConfirmCopy={handleConfirmCopy}- />- )}- </Flexbox>- );- }-- return (- <Flexbox gap={16} width={'100%'}>- <AgentToolsSection- agentId={effectiveAgentId}- variant={variant}- onStartCopy={() => setCopyMode(true)}- />-- <UserToolsSection+ <SharedAgentTool{...toolProps}+ excludeAgentConnectorsagentId={effectiveAgentId}- copyMode={copyMode}- copying={copying}- selected={selected}- toggleSelected={toggleSelected}- variant={variant}- onCancelCopy={resetCopy}- onConfirmCopy={handleConfirmCopy}+ group={group}+ showAuthor={inWorkspace}+ variant={'list'}/>- </Flexbox>+ );++ return (+ <AgentToolList agentId={effectiveAgentId} group={group} onOpenDetail={toolProps.onOpenDetail} />);});diff --git a/src/features/ProfileEditor/AgentUserTools/useOwnConnection.test.ts b/src/features/ProfileEditor/AgentUserTools/useOwnConnection.test.tsnew file mode 100644index 00000000000..cee920f202e--- /dev/null+++ b/src/features/ProfileEditor/AgentUserTools/useOwnConnection.test.ts@@ -0,0 +1,230 @@+/**+ * @vitest-environment happy-dom+ */+import { renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useItemDetailStore } from '@/features/ProfileEditor/itemDetailStore';+import type { ConnectorWithTools } from '@/store/tool/slices/connector/types';++import { ownConnectionSettingsPath, useOwnConnection } from './useOwnConnection';++const AGENT = 'agt_1';++const mocks = vi.hoisted(() => ({+ calls: [] as string[],+ chatConfig: {} as { toolMode?: 'custom' },+ connectors: [] as ConnectorWithTools[],+ fetchConnectors: vi.fn(),+ confirm: vi.fn(),+ copyConnectorToAgent: vi.fn(),+ detachConnectorFromAgent: vi.fn(),+ navigate: vi.fn(),+ openAgentStore: vi.fn(),+ plugins: [] as unknown[],+ toastError: vi.fn(),+ toastSuccess: vi.fn(),+ updateAgentConfigById: vi.fn(),+}));++vi.mock('@lobehub/ui', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ // Confirming is the user's part; the test answers yes.+ confirmModal: (options: { onOk: () => Promise<void> }) => {+ mocks.confirm(options);+ return options.onOk();+ },+ toast: { error: mocks.toastError, success: mocks.toastSuccess },+}));+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ useActiveWorkspaceId: () => null,+}));+vi.mock('@/features/AgentSkillStore', () => ({+ createAgentSkillStoreModal: mocks.openAgentStore,+}));+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({+ useWorkspaceAwareNavigate: () => mocks.navigate,+}));+vi.mock('@/store/agent', () => {+ const state = () => ({ updateAgentConfigById: mocks.updateAgentConfigById });+ return {+ useAgentStore: Object.assign((selector: (s: unknown) => unknown) => selector(state()), {+ getState: state,+ }),+ };+});+vi.mock('@/store/agent/selectors', () => ({+ agentSelectors: {+ getAgentConfigById: () => () => ({ chatConfig: mocks.chatConfig, plugins: mocks.plugins }),+ },+}));+vi.mock('@/store/tool', () => {+ const state = () => ({+ connectors: mocks.connectors,+ copyConnectorToAgent: mocks.copyConnectorToAgent,+ detachConnectorFromAgent: mocks.detachConnectorFromAgent,+ fetchConnectors: mocks.fetchConnectors,+ });+ return {+ useToolStore: Object.assign((selector: (s: unknown) => unknown) => selector(state()), {+ getState: state,+ }),+ };+});++const connector = (overrides: Partial<ConnectorWithTools> = {}): ConnectorWithTools => ({+ agentId: AGENT,+ credentials: null,+ id: 'row-own',+ identifier: 'notion',+ isEnabled: true,+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://example.com/mcp',+ metadata: null,+ name: 'Notion',+ sourceType: 'custom',+ status: 'connected',+ tools: [],+ ...overrides,+});++const setup = () => renderHook(() => useOwnConnection(AGENT)).result.current;++beforeEach(() => {+ vi.clearAllMocks();+ mocks.calls.length = 0;+ mocks.chatConfig = {};+ mocks.connectors = [connector({ agentId: null, id: 'row-lib' })];+ mocks.fetchConnectors.mockResolvedValue(undefined);+ mocks.plugins = [{ identifier: 'notion', mode: 'auto' }];+ mocks.copyConnectorToAgent.mockResolvedValue('row-own');+ mocks.detachConnectorFromAgent.mockImplementation(async () => {+ mocks.calls.push('detach');+ });+ mocks.updateAgentConfigById.mockImplementation(async () => {+ mocks.calls.push('update');+ });+});++describe('useOwnConnection', () => {+ it('gives the agent its own connection by copying the library one', async () => {+ const library = connector({ agentId: null, id: 'row-lib' });++ await setup().create(library);++ expect(mocks.copyConnectorToAgent).toHaveBeenCalledWith('row-lib', AGENT);+ expect(mocks.toastSuccess).toHaveBeenCalled();+ expect(mocks.openAgentStore).not.toHaveBeenCalled();+ });++ it('connects a second account instead of copying a Composio connection', async () => {+ const library = connector({+ agentId: null,+ id: 'row-lib',+ metadata: { composio: { connectedAccountId: 'ca_1' } },+ });++ await setup().create(library);++ // A copy would share the Composio account, and removing either would sign out both.+ expect(mocks.copyConnectorToAgent).not.toHaveBeenCalled();+ expect(mocks.openAgentStore).toHaveBeenCalledWith(AGENT);+ });++ it('says so when the own connection could not be set up', async () => {+ mocks.copyConnectorToAgent.mockRejectedValue(new Error('CONFLICT'));++ await setup().create(connector({ agentId: null, id: 'row-lib' }));++ expect(mocks.toastError).toHaveBeenCalled();+ expect(mocks.toastSuccess).not.toHaveBeenCalled();+ });++ it('keeps the own connection if the library connection was mounted elsewhere before confirmation', async () => {+ mocks.fetchConnectors.mockImplementation(async () => {+ mocks.connectors = [+ connector({ agentId: null, id: 'row-lib', metadata: { mountedByAgentId: 'other-agent' } }),+ ];+ });++ await setup().revertToLibrary(connector(), 'row-lib');++ expect(mocks.detachConnectorFromAgent).not.toHaveBeenCalled();+ expect(mocks.updateAgentConfigById).not.toHaveBeenCalled();+ expect(mocks.toastError).toHaveBeenCalled();+ });++ it('preserves both the connection and plugin configuration if the fresh read fails', async () => {+ mocks.fetchConnectors.mockRejectedValueOnce(new Error('offline'));++ await setup().revertToLibrary(connector(), 'row-lib');++ expect(mocks.detachConnectorFromAgent).not.toHaveBeenCalled();+ expect(mocks.updateAgentConfigById).not.toHaveBeenCalled();+ expect(mocks.toastError).toHaveBeenCalled();+ });++ it('preserves an implicit off switch when reverting to the library in a custom toolset', async () => {+ mocks.plugins = [];+ mocks.chatConfig = { toolMode: 'custom' };++ await setup().revertToLibrary(connector(), 'row-lib');++ expect(mocks.updateAgentConfigById).toHaveBeenCalledWith(AGENT, {+ plugins: [{ identifier: 'notion', mode: 'disabled' }],+ });+ });++ it('keeps the tool on when the agent goes back to the library connection', async () => {+ await setup().revertToLibrary(connector(), 'row-lib');++ expect(mocks.detachConnectorFromAgent).toHaveBeenCalledWith('row-own', AGENT, 'delete');+ // Deleting the connection takes the tool off the agent on the server, so the switch is+ // written again afterwards.+ expect(mocks.calls).toEqual(['detach', 'update']);+ expect(mocks.updateAgentConfigById).toHaveBeenCalledWith(AGENT, {+ plugins: [{ identifier: 'notion', mode: 'auto' }],+ });+ });++ it('leaves the tool off when it was off before going back to the library connection', async () => {+ mocks.plugins = [{ identifier: 'notion', mode: 'disabled' }];++ await setup().revertToLibrary(connector(), 'row-lib');++ expect(mocks.updateAgentConfigById).toHaveBeenCalledWith(AGENT, {+ plugins: [{ identifier: 'notion', mode: 'disabled' }],+ });+ });++ it('removes a tool only this agent has together with its connection', async () => {+ await setup().remove(connector({ identifier: 'sentry', id: 'row-sentry' }));++ expect(mocks.updateAgentConfigById).toHaveBeenCalledWith(AGENT, {+ plugins: [{ identifier: 'notion', mode: 'auto' }],+ });+ expect(mocks.detachConnectorFromAgent).toHaveBeenCalledWith('row-sentry', AGENT, 'delete');+ expect(mocks.calls).toEqual(['update', 'detach']);+ });++ it('closes the details of a tool whose connection just changed, and leaves other details open', async () => {+ const detail = { icon: null, tag: 'Custom connector', title: 'Notion', tools: [] };+ useItemDetailStore.getState().open({ ...detail, identifier: 'notion' });+ await setup().revertToLibrary(connector(), 'row-lib');+ expect(useItemDetailStore.getState().detail).toBeUndefined();++ useItemDetailStore.getState().open({ ...detail, identifier: 'linear' });+ await setup().revertToLibrary(connector(), 'row-lib');+ expect(useItemDetailStore.getState().detail?.identifier).toBe('linear');+ useItemDetailStore.getState().close();+ });++ it('opens the library on the agent’s own connection to manage it', () => {+ setup().manage(connector());++ expect(mocks.navigate).toHaveBeenCalledWith(ownConnectionSettingsPath('row-own'));+ expect(ownConnectionSettingsPath('row-own')).toBe(+ '/settings/connector?open=agent-connector%3Arow-own',+ );+ });+});diff --git a/src/features/ProfileEditor/AgentUserTools/useOwnConnection.ts b/src/features/ProfileEditor/AgentUserTools/useOwnConnection.tsnew file mode 100644index 00000000000..c42d5afb617--- /dev/null+++ b/src/features/ProfileEditor/AgentUserTools/useOwnConnection.ts@@ -0,0 +1,143 @@+import { hasCallableMcpEndpoint } from '@lobechat/const';+import { getConnectorMode, upsertConnectorEnabled, upsertPluginMode } from '@lobechat/types';+import { confirmModal, toast } from '@lobehub/ui';+import { useTranslation } from 'react-i18next';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { createAgentSkillStoreModal } from '@/features/AgentSkillStore';+import { useItemDetailStore } from '@/features/ProfileEditor/itemDetailStore';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { useAgentStore } from '@/store/agent';+import { agentSelectors } from '@/store/agent/selectors';+import { useToolStore } from '@/store/tool';+import { isLibraryConnectorForAgent } from '@/store/tool/slices/connector/selectors';+import type { ConnectorWithTools } from '@/store/tool/slices/connector/types';++/** Where the library lists the agent's own connections, opened on one of them. */+export const ownConnectionSettingsPath = (connectorId: string) =>+ `/settings/connector?open=${encodeURIComponent(`agent-connector:${connectorId}`)}`;++/**+ * A Composio connection is an account held by Composio; a copy would point two connections at+ * that one account, and removing either would sign the other out. Its own connection is a+ * second account instead.+ */+export const isComposioConnection = (connector: ConnectorWithTools) =>+ !!connector.metadata && 'composio' in connector.metadata && !!connector.metadata.composio;++export const isAvailableLibraryConnection = (row: ConnectorWithTools, agentId: string) =>+ isLibraryConnectorForAgent(row, agentId) &&+ row.isEnabled &&+ row.status === 'connected' &&+ (isComposioConnection(row) || hasCallableMcpEndpoint(row));++/**+ * What an agent can do about the connection one of its tools runs on: get its own instead of+ * the library's, manage it, or give it up.+ */+export const useOwnConnection = (agentId: string) => {+ const { t } = useTranslation('setting');+ const navigate = useWorkspaceAwareNavigate();+ const inWorkspace = !!useActiveWorkspaceId();+ const copyConnectorToAgent = useToolStore((s) => s.copyConnectorToAgent);+ const detachConnectorFromAgent = useToolStore((s) => s.detachConnectorFromAgent);+ const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);++ const readConfig = () => agentSelectors.getAgentConfigById(agentId)(useAgentStore.getState());++ // The side panel describes the connection as it was when the row was opened.+ const closeStaleDetail = (identifier: string) => {+ const { close, detail } = useItemDetailStore.getState();+ if (detail?.identifier === identifier) close();+ };++ /** Give the agent a connection of its own, starting from the library's. */+ const create = async (library: ConnectorWithTools) => {+ if (isComposioConnection(library)) {+ createAgentSkillStoreModal(agentId);+ return;+ }+ try {+ await copyConnectorToAgent(library.id, agentId);+ closeStaleDetail(library.identifier);+ toast.success({+ description: t('settingAgent.tools.connection.createdDesc'),+ title: t('settingAgent.tools.connection.created', { name: library.name }),+ });+ } catch (error) {+ console.error('[AgentTools] own connection failed:', error);+ toast.error(t('settingAgent.tools.connection.createFailed', { name: library.name }));+ }+ };++ const manage = (own: ConnectorWithTools) => navigate(ownConnectionSettingsPath(own.id));++ /** Drop the agent's own connection; the tool stays on and runs on the library's again. */+ const revertToLibrary = (own: ConnectorWithTools, fallbackConnectionId: string) =>+ confirmModal({+ cancelText: t('cancel', { ns: 'common' }),+ content: t(+ inWorkspace+ ? 'settingAgent.tools.connection.useWorkspaceConfirm.desc'+ : 'settingAgent.tools.connection.useLibraryConfirm.desc',+ ),+ okButtonProps: { danger: true },+ okText: t(+ inWorkspace+ ? 'settingAgent.tools.connection.useWorkspace'+ : 'settingAgent.tools.connection.useLibrary',+ ),+ onOk: async () => {+ // The library row may have been removed or mounted elsewhere while the dialog was open.+ const { fetchConnectors } = useToolStore.getState();+ try {+ await fetchConnectors();+ } catch {+ toast.error(t('settingAgent.tools.connection.switchFailed', { name: own.name }));+ return;+ }+ const fallback = useToolStore+ .getState()+ .connectors.find((row) => row.id === fallbackConnectionId);+ if (+ !fallback ||+ fallback.identifier !== own.identifier ||+ !isAvailableLibraryConnection(fallback, agentId)+ ) {+ toast.error(t('settingAgent.tools.connection.switchFailed', { name: own.name }));+ return;+ }++ const config = readConfig();+ const enabled =+ getConnectorMode(config?.plugins, own.identifier, config?.chatConfig) === 'auto';+ await detachConnectorFromAgent(own.id, agentId, 'delete');+ // Deleting an agent's connection also takes its tool off the agent. The tool is still+ // in the library, so put the switch back where it was.+ await updateAgentConfigById(agentId, {+ plugins: upsertConnectorEnabled(readConfig()?.plugins, own.identifier, enabled),+ });+ closeStaleDetail(own.identifier);+ },+ title: t('settingAgent.tools.connection.useLibraryConfirm.title', { name: own.name }),+ });++ /** Remove a tool only this agent has, together with its connection. */+ const remove = (own: ConnectorWithTools) =>+ confirmModal({+ cancelText: t('cancel', { ns: 'common' }),+ content: t('settingAgent.tools.connection.removeConfirm.desc'),+ okButtonProps: { danger: true },+ okText: t('settingAgent.tools.remove'),+ onOk: async () => {+ await updateAgentConfigById(agentId, {+ plugins: upsertPluginMode(readConfig()?.plugins, own.identifier, 'auto'),+ });+ await detachConnectorFromAgent(own.id, agentId, 'delete');+ closeStaleDetail(own.identifier);+ },+ title: t('settingAgent.tools.connection.removeConfirm.title', { name: own.name }),+ });++ return { create, manage, remove, revertToLibrary };+};diff --git a/src/features/ProfileEditor/ItemDetailPanel.tsx b/src/features/ProfileEditor/ItemDetailPanel.tsxindex e2ed3d10987..287422a9da5 100644--- a/src/features/ProfileEditor/ItemDetailPanel.tsx+++ b/src/features/ProfileEditor/ItemDetailPanel.tsx@@ -7,8 +7,19 @@ import { useTranslation } from 'react-i18next';import { useItemDetailStore } from './itemDetailStore';+/** Which connection a tool runs on for this agent. */+export interface ItemConnection {+ /** One sentence on what that means for the agent. */+ desc: string;+ /** Shown beside the name in the list; left out when the connection is the usual one. */+ label?: string;+ title: string;+}+/** What the side panel shows about one tool, connector or skill. */export interface ItemDetail {+ /** Which connection it runs on, for an item that signs in somewhere. */+ connection?: ItemConnection;description?: string;icon: ReactNode;identifier: string;@@ -76,6 +87,15 @@ const ItemDetailDock = memo(() => {{detail.description ? <Text type={'secondary'}>{detail.description}</Text> : null}+ {detail.connection ? (+ <Flexbox gap={4}>+ <Text style={{ fontWeight: 500 }}>{detail.connection.title}</Text>+ <Text fontSize={12} type={'secondary'}>+ {detail.connection.desc}+ </Text>+ </Flexbox>+ ) : null}+{detail.tools.length > 0 ? (<Flexbox gap={10}><Text style={{ fontWeight: 500 }}>diff --git a/src/features/ProfileEditor/PluginTag.test.tsx b/src/features/ProfileEditor/PluginTag.test.tsxindex 532744d92a7..6891e50aac2 100644--- a/src/features/ProfileEditor/PluginTag.test.tsx+++ b/src/features/ProfileEditor/PluginTag.test.tsx@@ -311,6 +311,48 @@ describe('PluginTag row variant', () => {expect(screen.getByText('Community')).toBeTruthy();});+ it('says when the agent runs an item on its own connection, in the row and its details', () => {+ mocks.agentConnectors = [+ { authorizedByAvatar: null, authorizedByName: null, identifier: 'gmail', name: 'Gmail' },+ ];+ const connection = { desc: 'Signs in separately', label: 'Own connection', title: 'Own' };+ const onOpen = vi.fn();+ render(+ <PluginTag+ agentId="agt-1"+ connection={connection}+ pluginId="gmail"+ variant="row"+ onOpen={onOpen}+ />,+ );++ expect(screen.getByText('Own connection')).toBeTruthy();+ fireEvent.click(screen.getByText('Gmail'));+ expect(onOpen).toHaveBeenCalledWith(expect.objectContaining({ connection }));+ });++ it('keeps the usual connection out of the row and says it in the details only', () => {+ mocks.agentConnectors = [+ { authorizedByAvatar: null, authorizedByName: null, identifier: 'gmail', name: 'Gmail' },+ ];+ const connection = { desc: 'Shared by your agents', title: 'Library connection' };+ const onOpen = vi.fn();+ render(+ <PluginTag+ agentId="agt-1"+ connection={connection}+ pluginId="gmail"+ variant="row"+ onOpen={onOpen}+ />,+ );++ expect(screen.queryByText('Library connection')).toBeNull();+ fireEvent.click(screen.getByText('Gmail'));+ expect(onOpen).toHaveBeenCalledWith(expect.objectContaining({ connection }));+ });+it('offers removal only when the row is removable and editable', () => {const { rerender } = render(<PluginTag pluginId="gmail" variant="row" />);expect(screen.queryByLabelText('settingAgent.tools.remove')).toBeTruthy();diff --git a/src/features/ProfileEditor/PluginTag.tsx b/src/features/ProfileEditor/PluginTag.tsxindex 0af906a3cdb..17f2326f1a9 100644--- a/src/features/ProfileEditor/PluginTag.tsx+++ b/src/features/ProfileEditor/PluginTag.tsx@@ -37,7 +37,7 @@ import {import { type LobeToolMetaWithAvailability } from '@/store/tool/slices/builtin/selectors';import { connectorSelectors } from '@/store/tool/slices/connector/selectors';-import { type ItemDetail } from './ItemDetailPanel';+import { type ItemConnection, type ItemDetail } from './ItemDetailPanel';import ItemRow from './ItemRow';/**@@ -106,6 +106,11 @@ export interface PluginTagProps {* so an agent-exclusive connector doesn't render as "Not Installed".*/agentId?: string;+ /**+ * In a row, which connection the item runs on for this agent, when that is worth saying:+ * a short label beside the name, and a sentence about it in the item's details.+ */+ connection?: ItemConnection;disabled?: boolean;/** In a row, an on/off switch for the item; `onToggle` makes it appear. */enabled?: boolean;@@ -174,6 +179,7 @@ export interface PluginTagProps {const PluginTag = memo<PluginTagProps>(({agentId,+ connection,pluginId,onRemove,onSelect,@@ -552,12 +558,18 @@ const PluginTag = memo<PluginTagProps>(/></Tooltip>) : null}+ {connection?.label ? (+ <Tooltip title={connection.desc}>+ <Tag style={{ flex: 'none', margin: 0 }}>{connection.label}</Tag>+ </Tooltip>+ ) : null}</>}onClick={onOpen? () =>onOpen({+ connection,description,icon: renderIcon(),identifier,diff --git a/src/features/ProfileEditor/PopoverContent.tsx b/src/features/ProfileEditor/PopoverContent.tsxindex b062e00993d..36fa61302ab 100644--- a/src/features/ProfileEditor/PopoverContent.tsx+++ b/src/features/ProfileEditor/PopoverContent.tsx@@ -1,6 +1,6 @@import { type ItemType } from '@lobehub/ui';import { createStaticStyles, cssVar, Flexbox, Icon, SearchBar, stopPropagation } from '@lobehub/ui';-import { ChevronRight, ExternalLink, Settings, Store } from 'lucide-react';+import { ChevronRight, ExternalLink, Settings, Store, UserRoundPlus } from 'lucide-react';import { memo, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -62,11 +62,14 @@ const styles = createStaticStyles(({ css }) => ({interface PopoverContentProps {items: ItemType[];onClose?: () => void;+ /** Connects an app for this agent alone, with an account the library does not hold. */+ onConnectForAgent?: () => void;onOpenStore: () => void;toolsOnly?: boolean;}-const PopoverContent = memo<PopoverContentProps>(({ items, onOpenStore, onClose, toolsOnly }) => {+const PopoverContent = memo<PopoverContentProps>((props) => {+ const { items, onOpenStore, onClose, onConnectForAgent, toolsOnly } = props;const { t } = useTranslation('setting');const navigate = useWorkspaceAwareNavigate();const [searchKeyword, setSearchKeyword] = useState('');@@ -96,6 +99,22 @@ const PopoverContent = memo<PopoverContentProps>(({ items, onOpenStore, onClose,{isEmpty ? <Empty /> : <ToolsList items={filteredItems} />}</ScrollSignalProvider><div className={styles.footer}>+ {onConnectForAgent ? (+ <div+ className={toolsListStyles.item}+ role="button"+ tabIndex={0}+ onClick={onConnectForAgent}+ >+ <div className={toolsListStyles.itemIcon}>+ <Icon icon={UserRoundPlus} size={SKILL_ICON_SIZE} />+ </div>+ <div className={toolsListStyles.itemContent}>+ {t('settingAgent.tools.connection.connectForAgent')}+ </div>+ <Icon className={styles.trailingIcon} icon={ChevronRight} size={16} />+ </div>+ ) : null}<div className={toolsListStyles.item} role="button" tabIndex={0} onClick={onOpenStore}><div className={toolsListStyles.itemIcon}><Icon icon={Store} size={SKILL_ICON_SIZE} />diff --git a/src/features/ProfileEditor/ToolListGroup.test.tsx b/src/features/ProfileEditor/ToolListGroup.test.tsxindex 46c376f8dfb..165750f571f 100644--- a/src/features/ProfileEditor/ToolListGroup.test.tsx+++ b/src/features/ProfileEditor/ToolListGroup.test.tsx@@ -5,11 +5,12 @@ import ToolListGroup, { TOOL_ROWS_VISIBLE } from './ToolListGroup';const rows = (n: number) => Array.from({ length: n }, (_, i) => <div key={i}>row-{i}</div>);-const renderGroup = (count: number) =>+const renderGroup = (count: number, fold?: boolean) =>render(<ToolListGroupaddControl={<button type="button">add</button>}emptyText="nothing yet"+ fold={fold}rows={rows(count)}title="Group"/>,@@ -43,4 +44,12 @@ describe('ToolListGroup', () => {fireEvent.click(screen.getByText('settingAgent.tools.showLess'));expect(screen.getAllByText(/^row-/)).toHaveLength(TOOL_ROWS_VISIBLE);});++ it('shows every row of a long list when the list is the page itself', () => {+ const total = TOOL_ROWS_VISIBLE + 5;+ renderGroup(total, false);++ expect(screen.getAllByText(/^row-/)).toHaveLength(total);+ expect(screen.queryByText('settingAgent.tools.showAll')).toBeNull();+ });});diff --git a/src/features/ProfileEditor/ToolListGroup.tsx b/src/features/ProfileEditor/ToolListGroup.tsxindex 56162814aab..69eca8f90f6 100644--- a/src/features/ProfileEditor/ToolListGroup.tsx+++ b/src/features/ProfileEditor/ToolListGroup.tsx@@ -39,6 +39,12 @@ interface ToolListGroupProps extends ToolGroupMeta {/** The control that adds one more; it closes the list as a row of its own. */addControl: ReactNode;emptyText: string;+ /**+ * Fold a long list after a few rows. Turn off where the list is the page itself, so nothing+ * the person came to find sits behind a click.+ * @default true+ */+ fold?: boolean;/** One element per tool or skill, each with its own key. */rows: ReactElement[];/** How many exist to choose from; shows as "N of M turned on" instead of a bare count. */@@ -67,11 +73,11 @@ Row.displayName = 'ToolListRow';* scannable, and one row opens the rest.*/const ToolListGroup = memo<ToolListGroupProps>(- ({ activeCount, addControl, desc, emptyText, extra, plain, rows, title, total }) => {+ ({ activeCount, addControl, desc, emptyText, extra, fold = true, plain, rows, title, total }) => {const { t } = useTranslation('setting');const form = useForm();const [expanded, setExpanded] = useState(false);- const foldable = rows.length > TOOL_ROWS_VISIBLE;+ const foldable = fold && rows.length > TOOL_ROWS_VISIBLE;const visible = foldable && !expanded ? rows.slice(0, TOOL_ROWS_VISIBLE) : rows;const content = (diff --git a/src/features/Settings/skill/features/SkillDetail/index.test.tsx b/src/features/Settings/skill/features/SkillDetail/index.test.tsxindex e9437bde3fe..c6deb7cfc7d 100644--- a/src/features/Settings/skill/features/SkillDetail/index.test.tsx+++ b/src/features/Settings/skill/features/SkillDetail/index.test.tsx@@ -22,10 +22,12 @@ const mocks = vi.hoisted(() => {connectors: [] as Array<{ id: string; identifier: string }>,createComposioConnection: vi.fn(),deleteAgentSkill: vi.fn(),+ useFetchAgentBoundConnectors: vi.fn(() => ({ isValidating: false })),fetchConnectors: vi.fn(),getLobehubSkillAuthorizeUrl: vi.fn(),installBuiltinTool: vi.fn(),installedBuiltinIds: [] as string[],+ isAgentBoundInit: false,installedPlugins: [] as Array<{customParams?: { mcp?: Record<string, unknown> };identifier: string;@@ -361,4 +363,17 @@ describe('SkillDetail', () => {);expect(screen.getByRole('button', { name: 'Connect' })).toBeInTheDocument();});++ it('loads the agents’ connectors when an agent connector’s detail is opened by link', () => {+ render(<SkillDetail identifier="row-1" type="agent-connector" />);++ expect(mocks.toolState.useFetchAgentBoundConnectors).toHaveBeenCalledWith(true);+ expect(screen.getByTestId('connector-detail')).toHaveTextContent('row-1');+ });++ it('leaves the agent connector query disabled for other details', () => {+ render(<SkillDetail identifier="agent-skill-1" type="agent-skill" />);++ expect(mocks.toolState.useFetchAgentBoundConnectors).toHaveBeenCalledWith(false);+ });});diff --git a/src/features/Settings/skill/features/SkillDetail/index.tsx b/src/features/Settings/skill/features/SkillDetail/index.tsxindex 8d82d5e60bf..269b31399c4 100644--- a/src/features/Settings/skill/features/SkillDetail/index.tsx+++ b/src/features/Settings/skill/features/SkillDetail/index.tsx@@ -12,6 +12,7 @@ import { lazy, memo, Suspense, useCallback, useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';import useSWR from 'swr';+import AsyncBoundary from '@/components/AsyncBoundary';import { ConnectorDetail, CustomConnectorModal } from '@/features/Connectors';import { useSkillConnect } from '@/features/SkillStore/SkillList/LobeHub/useSkillConnect';import { usePermission } from '@/hooks/usePermission';@@ -192,6 +193,11 @@ const SkillDetail = memo<SkillDetailProps>(({ identifier, type, onDelete }) => {? (s.agentBoundConnectors ?? []).find((c) => c.id === identifier): undefined,);+ // The list loads the agents' connectors, but a detail opened by link (or after a reload)+ // mounts while the list is hidden, where the list's effects never run.+ const isAgentBoundInit = useToolStore((s) => s.isAgentBoundInit);+ const useFetchAgentBoundConnectors = useToolStore((s) => s.useFetchAgentBoundConnectors);+ const agentBoundSync = useFetchAgentBoundConnectors(type === 'agent-connector');// Creator attribution for the row-level manage gate: agent skills carry it// on the skill row; connector-backed types on the connector row.@@ -412,28 +418,35 @@ const SkillDetail = memo<SkillDetailProps>(({ identifier, type, onDelete }) => {if (type === 'agent-connector') {const usageAgentId = agentBoundConnector?.agentId;return (- <ConnectorDetail- connectorId={identifier}- agentTitle={agentDisplayName({- name: agentBoundConnector?.agentName,- title: agentBoundConnector?.agentTitle,- })}- middleSlot={- usageAgentId ? (- <Suspense fallback={null}>- <AgentConnectorUsage- agentAvatar={agentBoundConnector?.agentAvatar}- agentId={usageAgentId}- agentTitle={agentDisplayName({- name: agentBoundConnector?.agentName,- title: agentBoundConnector?.agentTitle,- })}- />- </Suspense>- ) : undefined- }- onDelete={onDelete}- />+ <AsyncBoundary+ data={isAgentBoundInit || undefined}+ error={agentBoundSync.error}+ isLoading={agentBoundSync.isValidating}+ onRetry={agentBoundSync.revalidate}+ >+ <ConnectorDetail+ connectorId={identifier}+ agentTitle={agentDisplayName({+ name: agentBoundConnector?.agentName,+ title: agentBoundConnector?.agentTitle,+ })}+ middleSlot={+ usageAgentId ? (+ <Suspense fallback={null}>+ <AgentConnectorUsage+ agentAvatar={agentBoundConnector?.agentAvatar}+ agentId={usageAgentId}+ agentTitle={agentDisplayName({+ name: agentBoundConnector?.agentName,+ title: agentBoundConnector?.agentTitle,+ })}+ />+ </Suspense>+ ) : undefined+ }+ onDelete={onDelete}+ />+ </AsyncBoundary>);}diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/AgentTool.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/AgentTool.tsxdeleted file mode 100644index 6a758728330..00000000000--- a/src/routes/(main)/agent/profile/features/ProfileEditor/AgentTool.tsx+++ /dev/null@@ -1,15 +0,0 @@-'use client';--import AgentUserTools from '@/features/ProfileEditor/AgentUserTools';--/**- * Tools area for the agent profile editor — an Agent Tools / User Tools tabbed- * view (agent-scoped connectors vs the user's pinned tools).- * - filterAvailableInWeb: Filter out desktop-only tools in web version- * - useAllMetaList: Include eligible hidden tools- */-const AgentTool = () => {- return <AgentUserTools filterAvailableInWeb useAllMetaList />;-};--export default AgentTool;diff --git a/src/routes/(main)/agent/profile/features/ToolsEditor/index.tsx b/src/routes/(main)/agent/profile/features/ToolsEditor/index.tsxindex 10abc93fb4d..85bf6e34e7f 100644--- a/src/routes/(main)/agent/profile/features/ToolsEditor/index.tsx+++ b/src/routes/(main)/agent/profile/features/ToolsEditor/index.tsx@@ -8,8 +8,7 @@ import AgentUserTools from '@/features/ProfileEditor/AgentUserTools';import { useItemDetailStore } from '@/features/ProfileEditor/itemDetailStore';/**- * The Tools page: the tools and connectors the agent can act with, as two lists — the ones that- * belong to this agent alone, and the ones it borrows from the library every agent shares. A row+ * The Tools page: the tools and connectors the agent can act with, as one plain list. A row* opens its details in the page's right-hand panel.*/const ToolsEditor = memo(() => {@@ -20,7 +19,8 @@ const ToolsEditor = memo(() => {useEffect(() => useItemDetailStore.getState().close, []);return (- <Flexbox gap={32} paddingBlock={'8px 48px'}>+ // ProfileArea's WideScreenContainer owns the centered column and wide-screen preference.+ <Flexbox gap={24} paddingBlock={'8px 48px'}><Flexbox gap={4}><Text fontSize={24} weight={600}>{t('settingAgent.toolsPage.title')}diff --git a/src/store/tool/slices/connector/action.ts b/src/store/tool/slices/connector/action.tsindex 36ca859cd02..f6ffde42128 100644--- a/src/store/tool/slices/connector/action.ts+++ b/src/store/tool/slices/connector/action.ts@@ -15,6 +15,7 @@ import {createReplicaSlice,linkReplicaEntity,type ReplicaLens,+ type ReplicaSyncResult,} from '@/libs/replica';import { subscribeCacheScope } from '@/libs/replica/cacheScopeEvents';import { useClientDataSWR } from '@/libs/swr';@@ -159,6 +160,11 @@ export class ConnectorActionImpl {});this.#agentConnectors = createReplicaSlice(agentConnectorsResource, {actionPrefix: 'agentConnectors',+ effects: {+ onApplied: (_rows, { agentId }, { scope }) => {+ this.#confirmed.add(`${scope}|${agentId}`);+ },+ },entity: connectorsEntity,fetcher: fetchAgentConnectorList,get,@@ -173,12 +179,8 @@ export class ConnectorActionImpl {this.#agentConnectors,]);- // These three resources have no `useSync` mount, so nothing re-renders them- // on a cache-scope switch and the engine only resets on its *next* dispatch- // — which the gated consumers never make, because the init flag they check- // is still set. Drop the previous identity's views the moment the scope- // changes. The store is an app-lifetime singleton, so the subscription is- // never torn down.+ // Imperative consumers also read these views, even when no sync hook is mounted.+ // Clear every previous identity's rows and init flags as soon as the scope changes.subscribeCacheScope((scope) => this.#dropStaleScope(scope));}@@ -262,6 +264,12 @@ export class ConnectorActionImpl {{ revalidateIfStale: false, revalidateOnFocus: false },);+ useFetchAgentConnectors = (agentId: string): ReplicaSyncResult =>+ this.#agentConnectors.useSync(agentId ? { agentId } : null);++ useFetchAgentBoundConnectors = (enabled: boolean): ReplicaSyncResult =>+ this.#agentBoundConnectors.useSync(LIST_PARAMS, { enabled });+/*** Refresh the connector lists after a mutation. Always refreshes the base* list; also refreshes the agent-bound aggregate when it has been loaded (the@@ -308,13 +316,12 @@ export class ConnectorActionImpl {const params = { agentId };const pending = this.#agentConnectors.fetch(params, { fresh: true });// Awaited together, so a request that fails while storage paints is still handled- const [, result] = await Promise.all([+ await Promise.all([this.#get().agentConnectorsInit[agentId]? undefined: this.#agentConnectors.hydrate(params, scope),pending,]);- if (result.applied) this.#confirmed.add(`${scope}|${agentId}`);};/**diff --git a/src/store/tool/slices/connector/replica.test.ts b/src/store/tool/slices/connector/replica.test.tsindex bc0a32bf1bc..2a24683720c 100644--- a/src/store/tool/slices/connector/replica.test.ts+++ b/src/store/tool/slices/connector/replica.test.ts@@ -9,7 +9,7 @@*/import { randomUUID } from 'node:crypto';-import { cleanup } from '@testing-library/react';+import { cleanup, renderHook, waitFor } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { cacheScope } from '@/libs/replica';@@ -100,6 +100,34 @@ describe('connector slice replica', () => {vi.clearAllMocks();});+ it('loads the active agent bucket once for mounted readers and enables the aggregate on demand', async () => {+ listByAgentQuery.mockImplementation(async ({ agentId }) => [connector(agentId)]);+ listAgentBoundQuery.mockResolvedValue([connector('owned')]);+ listQuery.mockResolvedValue([]);+ await useToolStore.getState().fetchConnectors();++ const { rerender } = renderHook(+ ({ agentId, showDetail }) => {+ const store = useToolStore.getState();+ store.useFetchAgentConnectors(agentId);+ store.useFetchAgentConnectors(agentId);+ store.useFetchAgentBoundConnectors(showDetail);+ },+ { initialProps: { agentId: 'a1', showDetail: false } },+ );++ await waitFor(() => expect(useToolStore.getState().isConnectorListConfirmed('a1')).toBe(true));+ expect(listByAgentQuery).toHaveBeenCalledExactlyOnceWith({ agentId: 'a1' });+ expect(listAgentBoundQuery).not.toHaveBeenCalled();++ rerender({ agentId: 'a2', showDetail: true });+ await waitFor(() => {+ expect(useToolStore.getState().agentConnectors.a2).toEqual([connector('a2')]);+ expect(useToolStore.getState().agentBoundConnectors).toEqual([connector('owned')]);+ });+ expect(useToolStore.getState().agentConnectors.a1).toEqual([connector('a1')]);+ });+it('paints the persisted list before the network answers', async () => {await connectorsResource.storage!.set({ queryKey: LIST_STORAGE_KEY, scope },diff --git a/src/store/tool/slices/connector/selectors.ts b/src/store/tool/slices/connector/selectors.tsindex df7b40ebd9d..4565c1dba36 100644--- a/src/store/tool/slices/connector/selectors.ts+++ b/src/store/tool/slices/connector/selectors.ts@@ -144,13 +144,15 @@ const agentConnectors =(s: ToolStore): ConnectorWithTools[] =>s.agentConnectors?.[agentId] ?? [];-/** Mounted (locked) to an agent other than `agentId`; without one, to any agent. */-const isMountedByAnotherAgent = (connector: ConnectorWithTools, agentId?: string) => {+/** A base connection is available to every agent until one agent mounts it. */+export const isLibraryConnectorForAgent = (connector: ConnectorWithTools, agentId?: string) => {const mountedBy = connector.metadata?.mountedByAgentId;-- return typeof mountedBy === 'string' && mountedBy !== '' && mountedBy !== agentId;+ return !connector.agentId && (!mountedBy || mountedBy === agentId);};+const userMcpConnectorsForAgent = (agentId: string) => (s: ToolStoreState) =>+ userMcpConnectors(s).filter((connector) => isLibraryConnectorForAgent(connector, agentId));+/** Connected MCP rows a particular agent can use, with its own rows taking precedence. */const connectedMcpConnectorsForAgent = (s: ToolStoreState,@@ -159,7 +161,7 @@ const connectedMcpConnectorsForAgent = (const agentRows = s.agentConnectors?.[agentId] ?? [];const overridden = new Set(agentRows.map((row) => row.identifier));const baseRows = (s.connectors ?? []).filter(- (row) => !overridden.has(row.identifier) && !isMountedByAnotherAgent(row, agentId),+ (row) => !overridden.has(row.identifier) && isLibraryConnectorForAgent(row, agentId),);return executableMcpConnectors({connectors: [...agentRows, ...baseRows],@@ -186,7 +188,7 @@ const connectorByIdentifierForAgent =// A base connector another agent mounted serves only that agent, as the// server's scope rule has it (`ConnectorModel.scopePredicate`)(s.connectors ?? []).find(- (c) => c.identifier === identifier && !isMountedByAnotherAgent(c, agentId),+ (c) => c.identifier === identifier && isLibraryConnectorForAgent(c, agentId),));};@@ -196,32 +198,6 @@ const isAgentConnectorsInit =(s: ToolStore): boolean =>s.agentConnectorsInit?.[agentId] ?? false;-/**- * The badge kind of an agent tool, derived from its scope + whether a same-named- * user connector exists:- * - `agentOnly` — agent-owned, no user connector of the same identifier;- * - `copy` — agent-owned, and the user also has one of the same identifier;- * - `linked` — a user-owned row this agent has mounted (referenced + locked).- */-type AgentToolBadge = 'agentOnly' | 'copy' | 'linked';-const agentToolBadge =- (agentId: string, connector: ConnectorWithTools) =>- (s: ToolStore): AgentToolBadge => {- if (connector.agentId !== agentId) return 'linked'; // mounted user row- const hasUserSame = (s.connectors ?? []).some(- (c) => c.identifier === connector.identifier && !c.agentId,- );- return hasUserSame ? 'copy' : 'agentOnly';- };--/** Identifiers of user connectors that an agent has overridden (owns a same-named tool). */-const agentOverriddenIdentifiers =- (agentId: string) =>- (s: ToolStore): Set<string> => {- const owned = (s.agentConnectors?.[agentId] ?? []).filter((c) => c.agentId === agentId);- return new Set(owned.map((c) => c.identifier));- };-export const connectorSelectors = {/*** An account's name on one connector. Account ids are unique per connector@@ -250,8 +226,6 @@ export const connectorSelectors = {)(s)?.links?.find((link) => link.id === linkId)?.name,agentBoundConnectors,agentConnectors,- agentOverriddenIdentifiers,- agentToolBadge,connectedConnectors,connectorById,connectorByIdentifier,@@ -283,4 +257,5 @@ export const connectorSelectors = {},notConnectedConnectors,userMcpConnectors,+ userMcpConnectorsForAgent,};