🤯 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-dimension connectors in unified settings + workspace scope isolation tests (LOBE-11682 / LOBE-11681) (#17215)
LiJian80e55c28193a
diff --git a/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts b/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.tsindex 5ed3d60e41c..f615af7248f 100644--- a/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts+++ b/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts@@ -1,6 +1,7 @@// @vitest-environment nodeimport { beforeEach, describe, expect, it, vi } from 'vitest';+import { AgentModel } from '@/database/models/agent';import { ConnectorModel } from '@/database/models/connector';import { ConnectorToolModel } from '@/database/models/connectorTool';import { PluginModel } from '@/database/models/plugin';@@ -11,6 +12,7 @@ import { connectorRouter } from '../connector';// so the relative import order doesn't matter functionally — the mocks below// are still active when the router module is evaluated. They live below the// imports to satisfy `import-x/first` without disabling the rule.+vi.mock('@/database/models/agent', () => ({ AgentModel: vi.fn() }));vi.mock('@/database/models/connector', () => ({ ConnectorModel: vi.fn() }));vi.mock('@/database/models/connectorTool', () => ({ ConnectorToolModel: vi.fn() }));vi.mock('@/database/models/plugin', () => ({ PluginModel: vi.fn() }));@@ -256,3 +258,134 @@ describe('connectorRouter.create — sourceType handling on existing rows', () =expect(connectorModelMock.update).not.toHaveBeenCalled();});});++describe('connectorRouter.delete — agent connector unpins from the owning agent (LOBE-11682)', () => {+ // Deleting an agent-owned connector must also remove its tool from that+ // agent's `plugins`, so the unified settings delete matches the agent-profile+ // delete (row + pin) and never leaves a dangling pin. Done server-side so the+ // unified page needs no access to an arbitrary agent's config.+ let connectorModelMock: any;+ let agentModelMock: any;++ const DELETE_ID = '11111111-1111-4111-8111-111111111111';++ beforeEach(() => {+ vi.clearAllMocks();+ connectorModelMock = {+ delete: vi.fn().mockResolvedValue(undefined),+ findById: vi.fn(),+ };+ agentModelMock = {+ getAgentConfigById: vi.fn(),+ update: vi.fn().mockResolvedValue(undefined),+ };+ vi.mocked(ConnectorModel).mockImplementation(() => connectorModelMock);+ vi.mocked(ConnectorToolModel).mockImplementation(() => ({}) as any);+ vi.mocked(PluginModel).mockImplementation(() => ({}) as any);+ vi.mocked(AgentModel).mockImplementation(() => agentModelMock);+ });++ const caller = () =>+ connectorRouter.createCaller({+ serverDB: {},+ userId: 'user_test',+ workspaceId: null,+ } as any);++ it('deletes the row and strips the identifier from the owning agent plugins', async () => {+ connectorModelMock.findById.mockResolvedValueOnce({+ agentId: 'agent-1',+ id: 'c1',+ identifier: 'gmail',+ userId: 'user_test',+ });+ agentModelMock.getAgentConfigById.mockResolvedValueOnce({ plugins: ['gmail', 'notion'] });++ await caller().delete({ id: DELETE_ID });++ expect(connectorModelMock.delete).toHaveBeenCalledWith(DELETE_ID);+ expect(agentModelMock.getAgentConfigById).toHaveBeenCalledWith('agent-1');+ // 'gmail' removed, 'notion' preserved.+ expect(agentModelMock.update).toHaveBeenCalledWith('agent-1', { plugins: ['notion'] });+ });++ it('leaves the agent config untouched for a base (non-agent) connector', async () => {+ connectorModelMock.findById.mockResolvedValueOnce({+ agentId: null,+ id: 'c2',+ identifier: 'notion',+ userId: 'user_test',+ });++ await caller().delete({ id: DELETE_ID });++ expect(connectorModelMock.delete).toHaveBeenCalledWith(DELETE_ID);+ expect(agentModelMock.getAgentConfigById).not.toHaveBeenCalled();+ expect(agentModelMock.update).not.toHaveBeenCalled();+ });++ it('is a no-op on the agent when the connector row is already gone', async () => {+ connectorModelMock.findById.mockResolvedValueOnce(null);++ await caller().delete({ id: DELETE_ID });++ expect(connectorModelMock.delete).not.toHaveBeenCalled();+ expect(agentModelMock.update).not.toHaveBeenCalled();+ });+});++describe('connectorRouter.listAgentBound — hides connectors of unseen agents (LOBE-11681)', () => {+ // `queryAllAgentScoped` filters only by `workspace_id`, so a member could+ // otherwise see connectors owned by another member's PRIVATE agent. Gate the+ // result on the visibility-aware agent set (`getAgentAvatarsByIds`).+ let connectorModelMock: any;+ let connectorToolModelMock: any;+ let agentModelMock: any;++ beforeEach(() => {+ vi.clearAllMocks();+ connectorModelMock = { queryAllAgentScoped: vi.fn() };+ connectorToolModelMock = { queryByConnector: vi.fn().mockResolvedValue([]) };+ agentModelMock = { getAgentAvatarsByIds: vi.fn() };+ vi.mocked(ConnectorModel).mockImplementation(() => connectorModelMock);+ vi.mocked(ConnectorToolModel).mockImplementation(() => connectorToolModelMock);+ vi.mocked(PluginModel).mockImplementation(() => ({}) as any);+ vi.mocked(AgentModel).mockImplementation(() => agentModelMock);+ });++ const caller = () =>+ connectorRouter.createCaller({+ serverDB: {},+ userId: 'user_test',+ workspaceId: 'ws-1',+ } as any);++ it('drops rows whose owning agent is not in the visible set', async () => {+ connectorModelMock.queryAllAgentScoped.mockResolvedValueOnce([+ {+ agentId: 'agent-visible',+ credentials: null,+ id: 'c-visible',+ identifier: 'gmail',+ oidcConfig: null,+ },+ {+ agentId: 'agent-private',+ credentials: null,+ id: 'c-private',+ identifier: 'notion',+ oidcConfig: null,+ },+ ]);+ // AgentModel.ownership() (visibility-aware) only returns the visible agent —+ // the other member's private agent is absent.+ agentModelMock.getAgentAvatarsByIds.mockResolvedValueOnce([+ { avatar: null, id: 'agent-visible', title: 'Visible Agent' },+ ]);++ const result = await caller().listAgentBound();++ expect(result.map((r: any) => r.id)).toEqual(['c-visible']);+ expect(result[0].agentTitle).toBe('Visible Agent');+ });+});diff --git a/apps/server/src/routers/lambda/connector.ts b/apps/server/src/routers/lambda/connector.tsindex c98f47e494f..7019f5dab51 100644--- a/apps/server/src/routers/lambda/connector.ts+++ b/apps/server/src/routers/lambda/connector.ts@@ -1,3 +1,4 @@+import { upsertPluginMode } from '@lobechat/types';import { TRPCError } from '@trpc/server';import { z } from 'zod';@@ -159,6 +160,55 @@ export const connectorRouter = router({);}),+ /**+ * List every agent-OWNED connector in the current scope (all agents at once),+ * so the unified connector-settings page can show "which connector belongs to+ * which agent" without querying one agent at a time. Each row keeps its+ * `agentId` and is enriched with the owning agent's `agentTitle`/`agentAvatar`+ * for attribution badges. Scope-correct via `ConnectorModel.ownership()` (and+ * `AgentModel.ownership()` for the titles) — a workspace context only returns+ * that workspace's agent connectors (LOBE-11681 / LOBE-11682).+ */+ listAgentBound: connectorProcedure.query(async ({ ctx }) => {+ const connectors = await ctx.connectorModel.queryAllAgentScoped();++ // Resolve owning-agent display info in one scoped query (workspace-aware),+ // instead of loading each agent's config client-side from a page that isn't+ // in any agent's context.+ const agentIds = [+ ...new Set(connectors.map((c) => c.agentId).filter((id): id is string => !!id)),+ ];+ const agentModel = new AgentModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);+ // `getAgentAvatarsByIds` applies `AgentModel.ownership()` (visibility-aware):+ // in a workspace it returns only agents visible to the caller — public ones+ // plus their own private agents. A `user_connectors` row is scoped only by+ // `workspace_id`, so on its own it would surface connectors owned by another+ // member's PRIVATE agent. Gate on the visible-agent set so private-agent+ // connector inventory never leaks across members (LOBE-11681).+ const agentMetas = agentIds.length > 0 ? await agentModel.getAgentAvatarsByIds(agentIds) : [];+ const agentMetaById = new Map(agentMetas.map((m) => [m.id, m]));++ return Promise.all(+ connectors+ .filter((c) => !!c.agentId && agentMetaById.has(c.agentId))+ .map(async (c) => {+ const tools = await ctx.connectorToolModel.queryByConnector(c.id);+ const { credentials: _credentials, oidcConfig, ...rest } = c;+ const safeOidcConfig = oidcConfig+ ? { ...oidcConfig, clientSecret: undefined }+ : oidcConfig;+ const meta = agentMetaById.get(c.agentId!);+ return {+ ...rest,+ agentAvatar: meta?.avatar ?? null,+ agentTitle: meta?.title ?? null,+ oidcConfig: safeOidcConfig,+ tools,+ };+ }),+ );+ }),+/*** Return the connector record with decrypted user-set credentials so the* edit form can pre-fill accurately. Only the connector owner can call this@@ -565,6 +615,26 @@ export const connectorRouter = router({if (!target) return;assertWorkspaceRowManageable(ctx, target.userId, 'connector');await ctx.connectorModel.delete(input.id);++ // Agent-owned connector: also unpin its tool from the owning agent's+ // `plugins`, so deleting it here matches the agent-profile delete (row ++ // pin) and never leaves a dangling pin. Done server-side because the+ // unified settings page has no safe access to an arbitrary agent's config+ // (mirrors the profile page's client-side unpin, `upsertPluginMode(...,+ // 'auto')`). Idempotent: re-running on an already-unpinned agent is a no-op.+ if (target.agentId) {+ const agentModel = new AgentModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);+ const config = await agentModel.getAgentConfigById(target.agentId);+ if (config) {+ await agentModel.update(target.agentId, {+ plugins: upsertPluginMode(+ config.plugins ?? undefined,+ target.identifier,+ 'auto',+ ) as any,+ });+ }+ }}),/**diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex fa5b087051c..4f33bf45257 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -34,6 +34,8 @@"accountDeletion.sectionTitle": "Account Deletion","accountDeletion.title": "Delete Account","advancedSettings": "Advanced Settings",+ "agentConnectorUsage.goToAgent": "Go to agent",+ "agentConnectorUsage.label": "Used by agent","agentCronJobs.addJob": "Add Scheduled Task","agentCronJobs.clearTopics": "Clear Topics","agentCronJobs.clearTopicsFailed": "Failed to clear topics",@@ -942,6 +944,7 @@"settingsSearch.tabKeywords.storage": "storage, files, import, export, backup, reset, clear data, account deletion, delete account","settingsSearch.tabKeywords.systemTools": "system tools, built-in tools","settingsSearch.tabKeywords.usage": "usage, consumption, quota, spend, statistics",+ "skillGroup.agentConnectors": "Agent Connectors","skillGroup.builtinSkills": "Built-in Skills","skillGroup.builtinTools": "Built-in Tools","skillGroup.communityConnectors": "OAuth Connectors",diff --git a/locales/en-US/tool.json b/locales/en-US/tool.jsonindex 7dfd7c42e7f..4020bdc11d1 100644--- a/locales/en-US/tool.json+++ b/locales/en-US/tool.json@@ -69,7 +69,10 @@"codeInterpreter.returnValue": "Return Value:","connector.actionFailed": "Operation failed, please try again","connector.add.title": "Add Custom Connector",+ "connector.deleteAccountConfirmContent": "This removes the connector and its authorization from your account. Any agent that uses it will need to be re-authorized afterwards.",+ "connector.deleteAgentConfirmContent": "This connector belongs to the agent “{{agent}}”. Deleting it will also remove this tool from that agent.","connector.manageOnlyCreator": "Only the creator or a workspace owner can manage this connector",+ "connector.thisAgent": "this agent","dalle.autoGenerate": "Auto Generate","dalle.downloading": "The image links generated by DALL·E3 are only valid for 1 hour, caching the images locally...","dalle.generate": "Generate",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex 9e2ee2669f0..0eb5d8cad97 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -34,6 +34,8 @@"accountDeletion.sectionTitle": "账号注销","accountDeletion.title": "注销账号","advancedSettings": "进阶配置",+ "agentConnectorUsage.goToAgent": "前往使用",+ "agentConnectorUsage.label": "被此助理使用","agentCronJobs.addJob": "添加定时任务","agentCronJobs.clearTopics": "清除话题","agentCronJobs.clearTopicsFailed": "清除话题失败",@@ -942,6 +944,7 @@"settingsSearch.tabKeywords.storage": "存储,文件,导入,导出,备份,重置,清除数据,注销,删除账号","settingsSearch.tabKeywords.systemTools": "系统工具,内置工具","settingsSearch.tabKeywords.usage": "用量,消耗,配额,花费,统计",+ "skillGroup.agentConnectors": "助理连接器","skillGroup.builtinSkills": "内置技能","skillGroup.builtinTools": "内置工具","skillGroup.communityConnectors": "OAuth 连接器",diff --git a/locales/zh-CN/tool.json b/locales/zh-CN/tool.jsonindex 6bdfaf7650e..379490e826c 100644--- a/locales/zh-CN/tool.json+++ b/locales/zh-CN/tool.json@@ -69,7 +69,10 @@"codeInterpreter.returnValue": "返回值:","connector.actionFailed": "操作失败,请重试","connector.add.title": "添加自定义连接器",+ "connector.deleteAccountConfirmContent": "此操作会移除该连接器及其在你账号下的授权。之后任何使用它的助理都需要重新授权。",+ "connector.deleteAgentConfirmContent": "该连接器归属于助理「{{agent}}」。删除它会同时把这个工具从该助理中移除。","connector.manageOnlyCreator": "仅创建者或工作区 Owner 可以管理此连接器",+ "connector.thisAgent": "该助理","dalle.autoGenerate": "自动生成","dalle.downloading": "DALL·E3 生成的图片链接仅在 1 小时内有效,正在本地缓存图片...","dalle.generate": "生成",diff --git a/packages/database/src/models/__tests__/connectorAgentScope.test.ts b/packages/database/src/models/__tests__/connectorAgentScope.test.tsindex ce24495fd53..ce9a53fff63 100644--- a/packages/database/src/models/__tests__/connectorAgentScope.test.ts+++ b/packages/database/src/models/__tests__/connectorAgentScope.test.ts@@ -347,3 +347,101 @@ describe('ConnectorModel agent-scoped resolution', () => {});});});++// The agent-binding mutations (bindAgent / copyToAgent / mountToAgent) load the+// target connector via `findById` before attaching it, and rely on its scoped+// `ownership()` filter to reject cross-scope rows — that is what enforces+// "workspace agent ⇒ workspace-only tools, personal agent ⇒ personal-only"+// (LOBE-11681). These lock that filter so a future refactor can't silently let+// a personal connector be bound to a workspace agent (or vice versa).+describe('ConnectorModel scope isolation (workspace vs personal) — LOBE-11681', () => {+ it('a workspace-scoped model cannot findById a personal connector', async () => {+ const personal = await insertConnector({+ identifier: 'gmail',+ name: 'Personal',+ workspaceId: null,+ });++ const wsModel = new ConnectorModel(serverDB, userId, workspaceId);+ expect(await wsModel.findById(personal.id)).toBeNull();+ });++ it('a personal-scoped model cannot findById a workspace connector', async () => {+ const wsConnector = await insertConnector({+ identifier: 'gmail',+ name: 'Workspace',+ workspaceId,+ });++ const personalModel = new ConnectorModel(serverDB, userId);+ expect(await personalModel.findById(wsConnector.id)).toBeNull();+ });++ it('findById resolves a same-scope row (control)', async () => {+ const personal = await insertConnector({+ identifier: 'gmail',+ name: 'Personal',+ workspaceId: null,+ });+ const wsConnector = await insertConnector({ identifier: 'notion', name: 'WS', workspaceId });++ const personalModel = new ConnectorModel(serverDB, userId);+ const wsModel = new ConnectorModel(serverDB, userId, workspaceId);++ expect((await personalModel.findById(personal.id))?.id).toBe(personal.id);+ expect((await wsModel.findById(wsConnector.id))?.id).toBe(wsConnector.id);+ });+});++// `queryAllAgentScoped` powers the unified connector-settings page (LOBE-11682):+// it lists every agent-OWNED connector across all agents in one scope, and must+// stay scope-correct (no personal↔workspace leak — the LOBE-11681 invariant).+describe('ConnectorModel.queryAllAgentScoped — LOBE-11682', () => {+ it('returns agent-owned rows across all agents and excludes base rows', async () => {+ const ownedA = await insertConnector({ agentId: agentA, identifier: 'gmail', name: 'A' });+ const ownedB = await insertConnector({ agentId: agentB, identifier: 'slack', name: 'B' });+ // base (agent_id NULL) row must NOT appear+ await insertConnector({ identifier: 'notion', name: 'Base' });++ const model = new ConnectorModel(serverDB, userId);+ const rows = await model.queryAllAgentScoped();++ expect(rows.map((r) => r.id).sort()).toEqual([ownedA.id, ownedB.id].sort());+ expect(rows.every((r) => r.agentId !== null)).toBe(true);+ });++ it('is scope-isolated: a personal-scoped model excludes workspace agent rows', async () => {+ await insertConnector({ agentId: agentA, identifier: 'gmail', name: 'WS-owned', workspaceId });+ const personalOwned = await insertConnector({+ agentId: agentB,+ identifier: 'slack',+ name: 'Personal-owned',+ workspaceId: null,+ });++ const personalModel = new ConnectorModel(serverDB, userId);+ const rows = await personalModel.queryAllAgentScoped();++ expect(rows.map((r) => r.id)).toEqual([personalOwned.id]);+ });++ it('is scope-isolated: a workspace-scoped model excludes personal agent rows', async () => {+ const wsOwned = await insertConnector({+ agentId: agentA,+ identifier: 'gmail',+ name: 'WS-owned',+ workspaceId,+ });+ await insertConnector({+ agentId: agentB,+ identifier: 'slack',+ name: 'Personal-owned',+ workspaceId: null,+ });++ const wsModel = new ConnectorModel(serverDB, userId, workspaceId);+ const rows = await wsModel.queryAllAgentScoped();++ expect(rows.map((r) => r.id)).toEqual([wsOwned.id]);+ });+});diff --git a/packages/database/src/models/connector.ts b/packages/database/src/models/connector.tsindex f21672aa149..e876ed608d3 100644--- a/packages/database/src/models/connector.ts+++ b/packages/database/src/models/connector.ts@@ -1,4 +1,4 @@-import { and, eq, inArray, isNull, or, sql } from 'drizzle-orm';+import { and, eq, inArray, isNotNull, isNull, or, sql } from 'drizzle-orm';import type {ConnectorCredentials,@@ -207,6 +207,31 @@ export class ConnectorModel {return Promise.all(rows.map((r) => decryptRow(r, gateKeeper)));};+ /**+ * All agent-OWNED connector rows (`agent_id IS NOT NULL`) within the current+ * scope — i.e. every connector that belongs to some agent, across all agents.+ * Powers the unified connector-settings view (LOBE-11682) which lists "which+ * connector is bound to which agent" in one place, instead of one agent at a+ * time via {@link queryByAgent}.+ *+ * Scope-correct by construction: {@link ownership} carries the `workspace_id`+ * predicate, so in a workspace context this only returns rows owned by that+ * workspace's agents and never leaks personal-dimension rows (and vice versa)+ * — the LOBE-11681 invariant applied to the aggregate view. Mounted/linked+ * base rows (`agent_id IS NULL`) are intentionally excluded; they already show+ * under the base {@link query} list.+ */+ queryAllAgentScoped = async (+ gateKeeper: GateKeeper | undefined = this.gateKeeper,+ ): Promise<DecryptedConnector[]> => {+ const rows = await this.db+ .select()+ .from(userConnectors)+ .where(and(this.ownership(), isNotNull(userConnectors.agentId)));++ return Promise.all(rows.map((r) => decryptRow(r, gateKeeper)));+ };+/*** Base (non-agent) rows for the given identifiers. Excludes agent-scoped rows;* use {@link resolveByIdentifiers} for agent-aware runtime resolution.diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 64ef81e3401..5d2e4a1b430 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -13,6 +13,8 @@ export default {'agentImport.modal.knowledgeNotice': 'Knowledge bindings and files are not copied yet.','agentImport.success': 'Agent copied to {{name}}.','agentImport.title': 'Copy to Workspace',+ 'agentConnectorUsage.goToAgent': 'Go to agent',+ 'agentConnectorUsage.label': 'Used by agent','accountDeletion.cancelButton': 'Cancel Deletion','accountDeletion.cancelConfirmTitle': 'Cancel account deletion request?','accountDeletion.cancelFailed': 'Failed to cancel deletion request',@@ -1074,6 +1076,7 @@ export default {'Select a voice for the current agent, different TTS services support different voices','settingTTS.voice.preview': 'Voice Preview','settingTTS.voice.title': 'Text-to-Speech Voice',+ 'skillGroup.agentConnectors': 'Agent Connectors','skillGroup.builtinSkills': 'Built-in Skills','skillGroup.builtinTools': 'Built-in Tools','skillGroup.communityConnectors': 'OAuth Connectors',diff --git a/packages/locales/src/default/tool.ts b/packages/locales/src/default/tool.tsindex 12bdbb1908a..7c1ace07c41 100644--- a/packages/locales/src/default/tool.ts+++ b/packages/locales/src/default/tool.ts@@ -72,7 +72,12 @@ export default {'codeInterpreter.returnValue': 'Return Value:','connector.actionFailed': 'Operation failed, please try again','connector.add.title': 'Add Custom Connector',+ 'connector.deleteAccountConfirmContent':+ 'This removes the connector and its authorization from your account. Any agent that uses it will need to be re-authorized afterwards.',+ 'connector.deleteAgentConfirmContent':+ 'This connector belongs to the agent “{{agent}}”. Deleting it will also remove this tool from that agent.','connector.manageOnlyCreator': 'Only the creator or a workspace owner can manage this connector',+ 'connector.thisAgent': 'this agent','dalle.autoGenerate': 'Auto Generate','dalle.downloading':'The image links generated by DALL·E3 are only valid for 1 hour, caching the images locally...',diff --git a/src/features/Connectors/ConnectorDetail/index.tsx b/src/features/Connectors/ConnectorDetail/index.tsxindex f9e1a4d159c..2e90f4799fb 100644--- a/src/features/Connectors/ConnectorDetail/index.tsx+++ b/src/features/Connectors/ConnectorDetail/index.tsx@@ -18,8 +18,20 @@ import { getLocalizedConnectorDetail } from './localization';import ToolPermissionGroup from './ToolPermissionGroup';interface ConnectorDetailProps {+ /**+ * Title of the owning agent when this is an agent-dimension connector. Drives+ * the delete/uninstall confirmation copy — deleting an agent connector also+ * removes its tool from that agent (LOBE-11682).+ */+ agentTitle?: string | null;connectorId: string;lifecycleActions?: ReactNode;+ /**+ * Extra content rendered between the description and the tool-permission list.+ * Used by the unified settings' agent connectors to show the owning agent ++ * a jump-to-use action (LOBE-11682).+ */+ middleSlot?: ReactNode;onDelete?: () => void;}@@ -38,7 +50,7 @@ const ManageTooltip = ({ children, title }: { children: ReactNode; title?: strin);const ConnectorDetail = memo<ConnectorDetailProps>(- ({ connectorId, lifecycleActions, onDelete }) => {+ ({ agentTitle, connectorId, lifecycleActions, middleSlot, onDelete }) => {const { t } = useTranslation('tool');const { t: ts } = useTranslation('setting');const { message } = App.useApp();@@ -75,6 +87,20 @@ const ConnectorDetail = memo<ConnectorDetailProps>('Only the creator or a workspace owner can manage this connector',);+ // Deleting/uninstalling revokes the user's authorization; spell out the+ // consequence. For an agent-owned connector it ALSO unpins the tool from+ // that agent (server-side, see `connector.delete`) — surface that instead.+ const deleteConfirmContent = connector?.agentId+ ? t('connector.deleteAgentConfirmContent', {+ agent: agentTitle || t('connector.thisAgent', 'this agent'),+ defaultValue:+ 'This connector belongs to the agent “{{agent}}”. Deleting it will also remove this tool from that agent.',+ })+ : t('connector.deleteAccountConfirmContent', {+ defaultValue:+ 'This removes the connector and its authorization from your account. Any agent that uses it will need to be re-authorized afterwards.',+ });+const notifyActionError = useCallback((error: unknown) => {const httpStatus = (error as { data?: { httpStatus?: number } })?.data?.httpStatus;@@ -120,6 +146,7 @@ const ConnectorDetail = memo<ConnectorDetailProps>(const handleUninstall = () => {if (!connector) return;confirmModal({+ content: deleteConfirmContent,okButtonProps: { danger: true },onOk: async () => {try {@@ -273,6 +300,7 @@ const ConnectorDetail = memo<ConnectorDetailProps>(size="small"onClick={() => {confirmModal({+ content: deleteConfirmContent,okButtonProps: { danger: true },onOk: async () => {try {@@ -334,6 +362,8 @@ const ConnectorDetail = memo<ConnectorDetailProps>(</div>)}+ {middleSlot}+{hasTools ? (<div style={{ flex: 1, overflowY: 'auto' }}><ToolPermissionGroupdiff --git a/src/routes/(main)/settings/skill/features/AgentConnectorItem.tsx b/src/routes/(main)/settings/skill/features/AgentConnectorItem.tsxnew file mode 100644index 00000000000..1bd967a6c80--- /dev/null+++ b/src/routes/(main)/settings/skill/features/AgentConnectorItem.tsx@@ -0,0 +1,54 @@+'use client';++import { getComposioAppByIdentifier, getLobehubSkillProviderById } from '@lobechat/const';+import { Avatar, Icon, Tag } from '@lobehub/ui';+import { McpIcon } from '@lobehub/ui/icons';+import { cssVar } from 'antd-style';+import { memo } from 'react';++import NavItem from '@/features/NavPanel/components/NavItem';+import type { AgentBoundConnector } from '@/store/tool/slices/connector/types';++/**+ * A row in the unified settings' "Agent Connectors" section (LOBE-11682).+ *+ * Rendered identically to the base connector rows (same NavItem + the same brand+ * icon a base Composio/LobeHub connector of this identifier would show), so the+ * only visual difference is a tag naming the owning agent. Selectable — clicking+ * routes to the shared ConnectorDetail on the right, keyed by connector id to+ * avoid the identifier collision an agent connector can have with a base one.+ */+const AgentConnectorItem = memo<{+ connector: AgentBoundConnector;+ isSelected?: boolean;+ onSelect?: () => void;+}>(({ connector, isSelected, onSelect }) => {+ // Resolve the same brand icon a base connector of this identifier would use;+ // fall back to the generic MCP icon for custom/unknown connectors.+ const brand =+ getComposioAppByIdentifier(connector.identifier) ??+ getLobehubSkillProviderById(connector.identifier);++ const renderIcon = () => {+ if (brand) {+ const { icon, label } = brand;+ if (typeof icon === 'string') return <Avatar alt={label} avatar={icon} size={18} />;+ return <Icon fill={cssVar.colorText} icon={icon} size={18} />;+ }+ return <Icon icon={McpIcon} size={18} />;+ };++ return (+ <NavItem+ active={isSelected}+ extra={connector.agentTitle ? <Tag size="small">{connector.agentTitle}</Tag> : undefined}+ icon={renderIcon}+ title={brand?.label || connector.name || connector.identifier}+ onClick={onSelect}+ />+ );+});++AgentConnectorItem.displayName = 'AgentConnectorItem';++export default AgentConnectorItem;diff --git a/src/routes/(main)/settings/skill/features/AgentConnectorUsage.tsx b/src/routes/(main)/settings/skill/features/AgentConnectorUsage.tsxnew file mode 100644index 00000000000..0d7fb225e96--- /dev/null+++ b/src/routes/(main)/settings/skill/features/AgentConnectorUsage.tsx@@ -0,0 +1,61 @@+'use client';++import { Avatar, Flexbox, Icon, Text } from '@lobehub/ui';+import { Button } from '@lobehub/ui/base-ui';+import { ArrowUpRight } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { useNavigateToAgent } from '@/hooks/useNavigateToAgent';++/**+ * Shown inside ConnectorDetail for agent-owned connectors (LOBE-11682), between+ * the description and the tool-permission list: which agent owns this connector,+ * plus a one-click jump to go use that agent.+ */+const AgentConnectorUsage = memo<{+ agentAvatar?: string | null;+ agentId: string;+ agentTitle?: string | null;+}>(({ agentId, agentTitle, agentAvatar }) => {+ const { t } = useTranslation('setting');+ const navigateToAgent = useNavigateToAgent();++ return (+ <Flexbox+ horizontal+ align="center"+ gap={12}+ justify="space-between"+ style={{+ background: 'var(--ant-color-fill-quaternary)',+ borderRadius: 8,+ marginBottom: 16,+ padding: '10px 12px',+ }}+ >+ <Flexbox horizontal align="center" gap={10} style={{ flex: 1, overflow: 'hidden' }}>+ <Avatar avatar={agentAvatar || undefined} size={32} title={agentTitle || undefined} />+ <Flexbox style={{ overflow: 'hidden' }}>+ <Text style={{ fontSize: 12 }} type="secondary">+ {t('agentConnectorUsage.label')}+ </Text>+ <Text ellipsis style={{ fontSize: 14, fontWeight: 500 }}>+ {agentTitle || t('skillGroup.agentConnectors')}+ </Text>+ </Flexbox>+ </Flexbox>+ <Button+ icon={<Icon icon={ArrowUpRight} size={14} />}+ size="small"+ onClick={() => navigateToAgent(agentId)}+ >+ {t('agentConnectorUsage.goToAgent')}+ </Button>+ </Flexbox>+ );+});++AgentConnectorUsage.displayName = 'AgentConnectorUsage';++export default AgentConnectorUsage;diff --git a/src/routes/(main)/settings/skill/features/SkillDetail/index.tsx b/src/routes/(main)/settings/skill/features/SkillDetail/index.tsxindex 1179259aaef..4a85086aaeb 100644--- a/src/routes/(main)/settings/skill/features/SkillDetail/index.tsx+++ b/src/routes/(main)/settings/skill/features/SkillDetail/index.tsx@@ -23,9 +23,18 @@ import { pluginSelectors } from '@/store/tool/slices/plugin/selectors';import { getLocalizedBuiltinSkillDetail, getNoPermissionsTitle } from './localization';const AgentSkillDetail = lazy(() => import('@/features/AgentSkillDetail'));+// Lazy so `SkillDetail`'s static import graph stays free of the agent-navigation+// chain (`useNavigateToAgent` → chat store); only agent connectors need it.+const AgentConnectorUsage = lazy(() => import('../AgentConnectorUsage'));export type ToolDetailType =- 'agent-skill' | 'builtin' | 'builtin-skill' | 'lobehub-connector' | 'mcp-connector' | 'plugin';+ | 'agent-connector'+ | 'agent-skill'+ | 'builtin'+ | 'builtin-skill'+ | 'lobehub-connector'+ | 'mcp-connector'+ | 'plugin';const styles = createStaticStyles(({ css, cssVar }) => ({description: css`@@ -181,6 +190,13 @@ const SkillDetail = memo<SkillDetailProps>(({ identifier, type, onDelete }) => {const uninstallBuiltinTool = useToolStore((s) => s.uninstallBuiltinTool);const deleteAgentSkill = useToolStore((s) => s.deleteAgentSkill);const connector = useToolStore(connectorSelectors.connectorByIdentifier(identifier));+ // For agent connectors the `identifier` slot carries the connector id; resolve+ // the row from the agent-bound pool to show its owning-agent usage block.+ const agentBoundConnector = useToolStore((s) =>+ type === 'agent-connector'+ ? (s.agentBoundConnectors ?? []).find((c) => c.id === identifier)+ : undefined,+ );// Creator attribution for the row-level manage gate: agent skills carry it// on the skill row; connector-backed types on the connector row.@@ -381,6 +397,33 @@ const SkillDetail = memo<SkillDetailProps>(({ identifier, type, onDelete }) => {);}+ // Agent-owned connector (unified settings, LOBE-11682): the `identifier` slot+ // carries the connector id (not the slug — agent connectors can share a slug+ // with a base connector). Reuse the same ConnectorDetail as base connectors so+ // tool-permission editing, sync and delete behave identically; it resolves the+ // row from the agent-bound pool via the id-aware connector selectors.+ if (type === 'agent-connector') {+ const usageAgentId = agentBoundConnector?.agentId;+ return (+ <ConnectorDetail+ agentTitle={agentBoundConnector?.agentTitle}+ connectorId={identifier}+ middleSlot={+ usageAgentId ? (+ <Suspense fallback={null}>+ <AgentConnectorUsage+ agentAvatar={agentBoundConnector?.agentAvatar}+ agentId={usageAgentId}+ agentTitle={agentBoundConnector?.agentTitle}+ />+ </Suspense>+ ) : undefined+ }+ onDelete={onDelete}+ />+ );+ }+if (type === 'builtin-skill') {return (<div style={{ flex: 1, overflow: 'auto' }}>diff --git a/src/routes/(main)/settings/skill/features/SkillList.tsx b/src/routes/(main)/settings/skill/features/SkillList.tsxindex 9f388be06cb..2a450600782 100644--- a/src/routes/(main)/settings/skill/features/SkillList.tsx+++ b/src/routes/(main)/settings/skill/features/SkillList.tsx@@ -36,6 +36,7 @@ import { connectorSelectors } from '@/store/tool/slices/connector';import { LobehubSkillStatus } from '@/store/tool/slices/lobehubSkillStore/types';import { type LobeToolType } from '@/types/tool/tool';+import AgentConnectorItem from './AgentConnectorItem';import AgentSkillItem from './AgentSkillItem';import BuiltinSkillItem from './BuiltinSkillItem';import ComposioSkillItem from './ComposioSkillItem';@@ -104,6 +105,9 @@ const SkillList = memo<SkillListProps>(const customConnectors = useToolStore(connectorSelectors.customConnectors, isEqual);const isConnectorsInit = useToolStore((s) => s.isConnectorsInit);const fetchConnectors = useToolStore((s) => s.fetchConnectors);+ const agentBoundConnectors = useToolStore(connectorSelectors.agentBoundConnectors, isEqual);+ const isAgentBoundInit = useToolStore((s) => s.isAgentBoundInit);+ const fetchAgentBoundConnectors = useToolStore((s) => s.fetchAgentBoundConnectors);const allBuiltinTools = useToolStore((s) => s.builtinTools, isEqual);const uninstalledBuiltinTools = useToolStore(builtinToolSelectors.uninstalledBuiltinTools,@@ -145,6 +149,13 @@ const SkillList = memo<SkillListProps>(if (!isConnectorsInit) fetchConnectors();}, [isConnectorsInit, fetchConnectors]);+ // Load agent-owned connectors (across all agents) for the Agent Connectors+ // section — connector view only (LOBE-11682).+ const isConnectorView = viewMode === 'connector';+ useEffect(() => {+ if (isConnectorView && !isAgentBoundInit) fetchAgentBoundConnectors();+ }, [isConnectorView, isAgentBoundInit, fetchAgentBoundConnectors]);+const getLobehubSkillServerByProvider = (providerId: string) => {return allLobehubSkillServers.find((server) => server.identifier === providerId);};@@ -334,7 +345,8 @@ const SkillList = memo<SkillListProps>(marketAgentSkills.length > 0 ||userAgentSkills.length > 0 ||communityMCPs.length > 0 ||- customMCPs.length > 0;+ customMCPs.length > 0 ||+ agentBoundConnectors.length > 0;// A failed fetch must read as a failure with Retry, never as the "no skills"// empty (error gated ahead of empty).@@ -447,8 +459,6 @@ const SkillList = memo<SkillListProps>();};- const isConnectorView = viewMode === 'connector';-// Connectors tab: tools/MCP items (provide API-level permissions)// Skills tab: prompt/agent-based skills (show description/content)const hasBuiltinTools = builtinToolItems.length > 0 && isConnectorView;@@ -464,6 +474,8 @@ const SkillList = memo<SkillListProps>(const hasCustomSkills = userAgentSkills.length > 0 && !isConnectorView;// Lobehub/Composio OAuth skills go in Connectors tab (they provide tools)const hasCommunityConnectors = communitySkillItems.length > 0 && isConnectorView;+ // Agent-owned connectors (across all agents) — connector view only.+ const hasAgentConnectors = isConnectorView && agentBoundConnectors.length > 0;return (<div className={styles.container}>@@ -572,6 +584,20 @@ const SkillList = memo<SkillListProps>(</>,)}+ {hasAgentConnectors &&+ renderSection(+ 'agentConnectors',+ t('skillGroup.agentConnectors', 'Agent Connectors'),+ agentBoundConnectors.map((c) => (+ <AgentConnectorItem+ connector={c}+ isSelected={selectedIdentifier === c.id}+ key={c.id}+ onSelect={onSelect ? () => onSelect(c.id, 'agent-connector') : undefined}+ />+ )),+ )}+{hasCustomSkills &&renderSection('customSkills',diff --git a/src/store/tool/slices/connector/action.ts b/src/store/tool/slices/connector/action.tsindex 0de9371d873..eceedf73763 100644--- a/src/store/tool/slices/connector/action.ts+++ b/src/store/tool/slices/connector/action.ts@@ -11,10 +11,12 @@ export const createConnectorSlice = (set: Setter, get: () => ToolStore, _api?: uexport class ConnectorActionImpl {readonly #set: Setter;+ readonly #get: () => ToolStore;- constructor(set: Setter, _get: () => ToolStore, _api?: unknown) {+ constructor(set: Setter, get: () => ToolStore, _api?: unknown) {void _api;this.#set = set;+ this.#get = get;}fetchConnectors = async (): Promise<void> => {@@ -22,6 +24,34 @@ export class ConnectorActionImpl {this.#set({ connectors: data as any, isConnectorsInit: true }, false, 'fetchConnectors');};+ /**+ * Refresh the connector lists after a mutation. Always refreshes the base+ * list; also refreshes the agent-bound aggregate when it has been loaded (the+ * unified settings page), so a connector-detail action on an agent connector+ * (delete / sync / permission reset) updates that list too. On base-only+ * pages `isAgentBoundInit` is false, so this stays a single query.+ */+ #refreshConnectorLists = async (): Promise<void> => {+ const tasks = [this.fetchConnectors()];+ if (this.#get().isAgentBoundInit) tasks.push(this.fetchAgentBoundConnectors());+ await Promise.all(tasks);+ };++ /**+ * Fetch every agent-owned connector across all agents (the flat aggregate for+ * the unified connector-settings page, LOBE-11682). Each row is enriched+ * server-side with the owning agent's title/avatar. Scope-correct: a workspace+ * context only returns that workspace's agent connectors (LOBE-11681).+ */+ fetchAgentBoundConnectors = async (): Promise<void> => {+ const data = await lambdaClient.connector.listAgentBound.query();+ this.#set(+ { agentBoundConnectors: data as any, isAgentBoundInit: true },+ false,+ 'fetchAgentBoundConnectors',+ );+ };+/*** Fetch an agent's own tools (agent-owned + mounted) for the "Agent Tools"* tab. Stored keyed by agentId.@@ -99,7 +129,7 @@ export class ConnectorActionImpl {deleteConnector = async (id: string): Promise<void> => {await lambdaClient.connector.delete.mutate({ id });- await this.fetchConnectors();+ await this.#refreshConnectorLists();};updateConnector = async (@@ -121,7 +151,7 @@ export class ConnectorActionImpl {},): Promise<void> => {await lambdaClient.connector.update.mutate({ id, patch: patch as any });- await this.fetchConnectors();+ await this.#refreshConnectorLists();};syncConnectorTools = async (id: string): Promise<void> => {@@ -132,7 +162,7 @@ export class ConnectorActionImpl {);try {await lambdaClient.connector.syncTools.mutate({ id });- await this.fetchConnectors();+ await this.#refreshConnectorLists();} finally {this.#set((s) => ({ connectorSyncing: { ...s.connectorSyncing, [id]: false } }),@@ -147,7 +177,7 @@ export class ConnectorActionImpl {id,patch: { isEnabled: false },});- await this.fetchConnectors();+ await this.#refreshConnectorLists();};/**@@ -155,7 +185,7 @@ export class ConnectorActionImpl {*/resetConnectorPermissions = async (id: string): Promise<void> => {await lambdaClient.connector.resetPermissions.mutate({ id });- await this.fetchConnectors();+ await this.#refreshConnectorLists();};/**@@ -201,13 +231,21 @@ export class ConnectorActionImpl {toolId: string,permission: ConnectorToolPermission,): Promise<void> => {- // Optimistic update+ // Optimistic update — patch the tool in whichever list holds it (base+ // connectors and agent-bound connectors are separate arrays).+ const patchTools = <+ T extends { tools: Array<{ id: string; permission: ConnectorToolPermission }> },+ >(+ list: T[],+ ): T[] =>+ list.map((c) => ({+ ...c,+ tools: c.tools.map((t) => (t.id === toolId ? { ...t, permission } : t)),+ }));this.#set((s) => ({- connectors: s.connectors.map((c) => ({- ...c,- tools: c.tools.map((t) => (t.id === toolId ? { ...t, permission } : t)),- })),+ agentBoundConnectors: patchTools(s.agentBoundConnectors ?? []),+ connectors: patchTools(s.connectors),}),false,'updateToolPermission/optimistic',@@ -217,7 +255,7 @@ export class ConnectorActionImpl {await lambdaClient.connector.updateToolPermission.mutate({ permission, toolId });} catch {// Roll back on error- await this.fetchConnectors();+ await this.#refreshConnectorLists();}};}diff --git a/src/store/tool/slices/connector/initialState.ts b/src/store/tool/slices/connector/initialState.tsindex cc75d1a6005..45121c08bf3 100644--- a/src/store/tool/slices/connector/initialState.ts+++ b/src/store/tool/slices/connector/initialState.ts@@ -1,20 +1,29 @@-import type { ConnectorWithTools } from './types';+import type { AgentBoundConnector, ConnectorWithTools } from './types';export interface ConnectorState {+ /**+ * All agent-owned connectors across every agent in the current scope, for the+ * unified connector-settings page (LOBE-11682). Distinct from `agentConnectors`+ * (keyed per-agent, includes mounted rows) — this is the flat aggregate.+ */+ agentBoundConnectors: AgentBoundConnector[];/** Agent-scoped connectors (owned + mounted), keyed by agentId. */agentConnectors: Record<string, ConnectorWithTools[]>;agentConnectorsInit: Record<string, boolean>;connectorCreating: boolean;connectors: ConnectorWithTools[];connectorSyncing: Record<string, boolean>;+ isAgentBoundInit: boolean;isConnectorsInit: boolean;}export const initialConnectorState: ConnectorState = {+ agentBoundConnectors: [],agentConnectors: {},agentConnectorsInit: {},connectorCreating: false,connectors: [],connectorSyncing: {},+ isAgentBoundInit: false,isConnectorsInit: false,};diff --git a/src/store/tool/slices/connector/selectors.ts b/src/store/tool/slices/connector/selectors.tsindex 7a48fb91958..cd87e5b16bc 100644--- a/src/store/tool/slices/connector/selectors.ts+++ b/src/store/tool/slices/connector/selectors.ts@@ -1,14 +1,27 @@import type { ToolStore } from '../../store';-import type { ConnectorTool, ConnectorWithTools } from './types';+import type { AgentBoundConnector, ConnectorTool, ConnectorWithTools } from './types';// `?? []` tolerates a partially-initialized store (e.g. in unit-test mocks);// the real store always seeds `connectors: []` via initialState.const connectorList = (s: ToolStore): ConnectorWithTools[] => s.connectors ?? [];+/** All agent-owned connectors across agents, for the unified settings page. */+const agentBoundConnectors = (s: ToolStore): AgentBoundConnector[] => s.agentBoundConnectors ?? [];++// By-id lookups span both pools: base connectors (`s.connectors`) and the+// agent-bound aggregate (`s.agentBoundConnectors`). The unified settings page+// reuses ConnectorDetail (keyed by connector id) for agent connectors, so the+// detail panel must resolve either kind. Ids are UUIDs — no collision.+const allById =+ (id: string) =>+ (s: ToolStore): ConnectorWithTools | undefined =>+ (s.connectors ?? []).find((c) => c.id === id) ??+ (s.agentBoundConnectors ?? []).find((c) => c.id === id);+const connectorById =(id: string) =>(s: ToolStore): ConnectorWithTools | undefined =>- (s.connectors ?? []).find((c) => c.id === id);+ allById(id)(s);const connectorByIdentifier =(identifier: string) =>@@ -38,7 +51,7 @@ interface GroupedTools {const connectorToolsGrouped =(connectorId: string) =>(s: ToolStore): GroupedTools => {- const connector = (s.connectors ?? []).find((c) => c.id === connectorId);+ const connector = allById(connectorId)(s);if (!connector) return { createTools: [], deleteTools: [], readTools: [], updateTools: [] };// Show ALL tools in the settings UI (including disabled ones so users can re-enable them).@@ -94,6 +107,7 @@ const agentOverriddenIdentifiers =};export const connectorSelectors = {+ agentBoundConnectors,agentConnectors,agentOverriddenIdentifiers,agentToolBadge,diff --git a/src/store/tool/slices/connector/types.ts b/src/store/tool/slices/connector/types.tsindex 5eb99ca821a..acc474256d3 100644--- a/src/store/tool/slices/connector/types.ts+++ b/src/store/tool/slices/connector/types.ts@@ -28,3 +28,13 @@ export interface ConnectorWithTools {/** Creator attribution — drives the workspace row-level manage gate. */userId?: string | null;}++/**+ * An agent-owned connector as returned by `connector.listAgentBound`, enriched+ * with the owning agent's display info for the unified settings attribution+ * badge (LOBE-11682). Server-resolved so the page needs no per-agent loading.+ */+export interface AgentBoundConnector extends ConnectorWithTools {+ agentAvatar: string | null;+ agentTitle: string | null;+}