🤯 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(connector): workspace setting for who manages connectors, with in-place failure feedback (#21653)
Lobehub Coder7d58f0431b65
diff --git a/apps/server/src/routers/lambda/__tests__/composio.workspaceScope.test.ts b/apps/server/src/routers/lambda/__tests__/composio.workspaceScope.test.tsindex cf5ee8c60df..b397061f8e1 100644--- a/apps/server/src/routers/lambda/__tests__/composio.workspaceScope.test.ts+++ b/apps/server/src/routers/lambda/__tests__/composio.workspaceScope.test.ts@@ -15,6 +15,14 @@ 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() }));+const workspaceMocks = vi.hoisted(() => ({+ getConnectorMemberManage: vi.fn(async () => 'all_members' as const),+}));+vi.mock('@/database/models/workspace', () => ({+ WorkspaceModel: vi.fn(function () {+ return workspaceMocks;+ }),+}));// A pre-configured auth config short-circuits the discovery branch.vi.mock('@/config/composio', () => ({ getServerComposioAuthConfigId: () => 'auth-cfg-1' }));vi.mock('@/libs/composio', () => ({@@ -50,6 +58,7 @@ describe('composioRouter — workspace scoping (workspace-agent connector bug)',beforeEach(() => {vi.clearAllMocks();+ workspaceMocks.getConnectorMemberManage.mockResolvedValue('all_members');connectorModelMock = {create: vi.fn().mockResolvedValue({ id: 'conn-new' }),findScopedByIdentifier: vi.fn().mockResolvedValue(null),@@ -139,27 +148,51 @@ describe('composioRouter — workspace scoping (workspace-agent connector bug)',expect(agentModelMock.existsOwnedById).toHaveBeenCalledWith('agent-1');});- it('blocks a non-owner member from overwriting another member’s workspace connection', async () => {- // buildWorkspaceWhere makes workspace rows writable workspace-wide; the- // row-level gate must stop a plain member from clobbering another member's- // Composio connection — before any remote account is created.- connectorModelMock.findScopedByIdentifier.mockResolvedValueOnce({+ const memberCaller = () =>+ composioRouter.createCaller({+ serverDB: {},+ userId: 'user_test',+ workspaceId: 'ws-1',+ workspaceRole: 'member',+ } as any);++ it('lets a member reconnect another member’s workspace connection by default', async () => {+ // Shared connectors are co-maintained unless an admin restricted them.+ connectorModelMock.findScopedByIdentifier.mockResolvedValue({id: 'conn-other',identifier: 'gmail',userId: 'another-user',});+ await expect(+ memberCaller().createConnection({ appSlug: 'gmail', identifier: 'gmail', label: 'Gmail' }),+ ).resolves.toBeDefined();+ });++ it('blocks a member from connecting when admins restricted connector management', async () => {+ // Checked before any remote Composio account is created — even for the+ // member's own row and for a brand-new connection.+ workspaceMocks.getConnectorMemberManage.mockResolvedValue('admins_only');++ await expect(+ memberCaller().createConnection({ appSlug: 'gmail', identifier: 'gmail', label: 'Gmail' }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });++ expect(connectorModelMock.create).not.toHaveBeenCalled();+ });++ it('still lets a workspace admin connect when members are restricted', async () => {+ workspaceMocks.getConnectorMemberManage.mockResolvedValue('admins_only');+await expect(composioRouter.createCaller({serverDB: {},userId: 'user_test',workspaceId: 'ws-1',- workspaceRole: 'member',+ workspaceRole: 'admin',} as any).createConnection({ appSlug: 'gmail', identifier: 'gmail', label: 'Gmail' }),- ).rejects.toMatchObject({ code: 'FORBIDDEN' });-- expect(connectorModelMock.create).not.toHaveBeenCalled();+ ).resolves.toBeDefined();});});diff --git a/apps/server/src/routers/lambda/__tests__/connector.managePolicy.test.ts b/apps/server/src/routers/lambda/__tests__/connector.managePolicy.test.tsnew file mode 100644index 00000000000..bb0012fec9b--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/connector.managePolicy.test.ts@@ -0,0 +1,182 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { ConnectorModel } from '@/database/models/connector';+import { ConnectorToolModel } from '@/database/models/connectorTool';++import { connectorRouter } from '../connector';++const mocks = vi.hoisted(() => ({+ auditCreate: vi.fn(),+ getConnectorMemberManage: vi.fn(+ async (): Promise<'admins_only' | 'all_members'> => 'all_members',+ ),+ updateConnectorMemberManage: vi.fn(),+}));++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() }));+vi.mock('@/database/models/workspace', () => ({+ WorkspaceModel: vi.fn(function () {+ return {+ getConnectorMemberManage: mocks.getConnectorMemberManage,+ updateConnectorMemberManage: mocks.updateConnectorMemberManage,+ };+ }),+}));+vi.mock('@/database/models/workspaceAuditLog', () => ({+ WorkspaceAuditLogModel: vi.fn(function () {+ return { create: mocks.auditCreate };+ }),+}));+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({+ KeyVaultsGateKeeper: { initWithEnvKey: async () => ({}) },+}));+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {+ const mod = await vi.importActual<{ trpc: any }>('@/libs/trpc/lambda/init');+ const rank: Record<string, number> = { admin: 2, member: 1, owner: 3, viewer: 0 };+ return {+ requireWorkspaceRoleWhenScoped: (minRole: string) =>+ mod.trpc.middleware(async (opts: any) => {+ const { workspaceId, workspaceRole } = opts.ctx;+ if (workspaceId && (rank[workspaceRole] ?? -1) < rank[minRole]) {+ const { TRPCError } = await import('@trpc/server');+ throw new TRPCError({ code: 'FORBIDDEN', message: `Requires ${minRole}` });+ }+ return opts.next();+ }),+ wsCompatProcedure: mod.trpc.procedure,+ };+});+vi.mock('@/libs/trpc/lambda/middleware', () => ({+ serverDatabase: async (opts: any) =>+ opts.next({ ctx: { ...opts.ctx, serverDB: opts.ctx.serverDB ?? {} } }),+}));++const callerFor = (ctx: Record<string, unknown>) =>+ connectorRouter.createCaller({ serverDB: {}, userId: 'me', ...ctx } as any);++const CONNECTOR_ID = '9f1f6f30-0000-4000-8000-000000000002';++describe('connectorRouter manage policy', () => {+ let connectorModelMock: any;++ beforeEach(() => {+ vi.clearAllMocks();+ mocks.getConnectorMemberManage.mockResolvedValue('all_members');+ connectorModelMock = {+ create: vi.fn().mockResolvedValue({ id: 'created' }),+ findById: vi.fn(),+ findScopedByIdentifier: vi.fn().mockResolvedValue(null),+ update: vi.fn(),+ };+ vi.mocked(ConnectorModel).mockImplementation(function () {+ return connectorModelMock;+ });+ vi.mocked(ConnectorToolModel).mockImplementation(function () {+ return { queryByConnector: vi.fn().mockResolvedValue([]) } as any;+ });+ });++ const createInput = {+ identifier: 'my-mcp',+ mcpConnectionType: 'stdio' as const,+ mcpStdioConfig: { command: 'echo' },+ name: 'My MCP',+ sourceType: 'custom' as const,+ };++ it("does not let a member re-add over another member's connector, even by default", async () => {+ // The upsert would rewrite the command while the row stays the creator's.+ connectorModelMock.findScopedByIdentifier.mockResolvedValue({+ id: CONNECTOR_ID,+ userId: 'someone-else',+ });++ await expect(+ callerFor({ workspaceId: 'ws-1', workspaceRole: 'member' }).create(createInput),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(connectorModelMock.update).not.toHaveBeenCalled();+ });++ it('lets a member add a new workspace connector by default, but not once restricted', async () => {+ const member = callerFor({ workspaceId: 'ws-1', workspaceRole: 'member' });++ await expect(member.create(createInput)).resolves.toEqual({ id: 'created', isNew: true });++ mocks.getConnectorMemberManage.mockResolvedValue('admins_only');+ await expect(member.create(createInput)).rejects.toMatchObject({ code: 'FORBIDDEN' });+ });++ it('keeps the creator able to read their own connector config when members are restricted', async () => {+ // Desktop stdio connectors read their command through getForEdit at run time.+ mocks.getConnectorMemberManage.mockResolvedValue('admins_only');+ connectorModelMock.findById.mockResolvedValue({ id: CONNECTOR_ID, userId: 'me' });++ await expect(+ callerFor({ workspaceId: 'ws-1', workspaceRole: 'member' }).getForEdit({ id: CONNECTOR_ID }),+ ).resolves.toMatchObject({ id: CONNECTOR_ID });+ });++ it('reports what a member may do under each policy', async () => {+ const member = callerFor({ workspaceId: 'ws-1', workspaceRole: 'member' });++ await expect(member.getManagePolicy()).resolves.toEqual({+ canEditPolicy: false,+ canManage: true,+ memberManage: 'all_members',+ });++ mocks.getConnectorMemberManage.mockResolvedValue('admins_only');+ await expect(member.getManagePolicy()).resolves.toEqual({+ canEditPolicy: false,+ canManage: false,+ memberManage: 'admins_only',+ });+ });++ it('lets admins edit the policy and keep managing connectors', async () => {+ mocks.getConnectorMemberManage.mockResolvedValue('admins_only');++ await expect(+ callerFor({ workspaceId: 'ws-1', workspaceRole: 'admin' }).getManagePolicy(),+ ).resolves.toEqual({ canEditPolicy: true, canManage: true, memberManage: 'admins_only' });+ });++ it('updates the policy for an admin and records it in the audit log', async () => {+ await callerFor({ workspaceId: 'ws-1', workspaceRole: 'admin' }).updateManagePolicy({+ memberManage: 'admins_only',+ });++ expect(mocks.updateConnectorMemberManage).toHaveBeenCalledWith('ws-1', 'admins_only');+ expect(mocks.auditCreate).toHaveBeenCalledWith({+ action: 'security.policy_updated',+ metadata: {+ policy: 'connector.member_manage',+ previous: 'all_members',+ value: 'admins_only',+ },+ userId: 'me',+ workspaceId: 'ws-1',+ });+ });++ it('rejects members and restricted API keys', async () => {+ await expect(+ callerFor({ workspaceId: 'ws-1', workspaceRole: 'member' }).updateManagePolicy({+ memberManage: 'admins_only',+ }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ await expect(+ callerFor({+ apiKeyScopes: ['agent:read'],+ workspaceId: 'ws-1',+ workspaceRole: 'owner',+ }).updateManagePolicy({ memberManage: 'admins_only' }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });++ expect(mocks.updateConnectorMemberManage).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/lambda/__tests__/connector.syncToolsFromClientById.test.ts b/apps/server/src/routers/lambda/__tests__/connector.syncToolsFromClientById.test.tsindex c526f347835..27f93733202 100644--- a/apps/server/src/routers/lambda/__tests__/connector.syncToolsFromClientById.test.ts+++ b/apps/server/src/routers/lambda/__tests__/connector.syncToolsFromClientById.test.ts@@ -15,6 +15,14 @@ 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() }));+const workspaceMocks = vi.hoisted(() => ({+ getConnectorMemberManage: vi.fn(async () => 'all_members' as const),+}));+vi.mock('@/database/models/workspace', () => ({+ WorkspaceModel: vi.fn(function () {+ return workspaceMocks;+ }),+}));vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({KeyVaultsGateKeeper: { initWithEnvKey: async () => ({}) },}));@@ -43,6 +51,7 @@ describe('connectorRouter.syncToolsFromClientById', () => {beforeEach(() => {vi.clearAllMocks();+ workspaceMocks.getConnectorMemberManage.mockResolvedValue('all_members');connectorModelMock = {findById: vi.fn().mockResolvedValue({@@ -97,22 +106,36 @@ describe('connectorRouter.syncToolsFromClientById', () => {expect(connectorToolModelMock.upsertMany).not.toHaveBeenCalled();});- it("rejects reporting into another member's workspace connector", async () => {+ const memberCaller = () =>+ connectorRouter.createCaller({+ serverDB: {},+ userId: 'user_test',+ workspaceId: 'ws_1',+ workspaceRole: 'member',+ } as any);++ it("lets a member co-maintain another member's workspace connector by default", async () => {connectorModelMock.findById.mockResolvedValue({id: CONNECTOR_ID,identifier: 'my-local-mcp',userId: 'someone_else',});+ await memberCaller().syncToolsFromClientById({ id: CONNECTOR_ID, tools: [] });++ expect(connectorModelMock.updateStatus).toHaveBeenCalled();+ });++ it('rejects a member when admins restricted connector management', async () => {+ workspaceMocks.getConnectorMemberManage.mockResolvedValue('admins_only');+ connectorModelMock.findById.mockResolvedValue({+ id: CONNECTOR_ID,+ identifier: 'my-local-mcp',+ userId: 'user_test',+ });+await expect(- connectorRouter- .createCaller({- serverDB: {},- userId: 'user_test',- workspaceId: 'ws_1',- workspaceRole: 'member',- } as any)- .syncToolsFromClientById({ id: CONNECTOR_ID, tools: [] }),+ memberCaller().syncToolsFromClientById({ id: CONNECTOR_ID, tools: [] }),).rejects.toMatchObject({ code: 'FORBIDDEN' });expect(connectorToolModelMock.upsertMany).not.toHaveBeenCalled();expect(connectorModelMock.updateStatus).not.toHaveBeenCalled();diff --git a/apps/server/src/routers/lambda/_helpers/connectorManagePolicy.test.ts b/apps/server/src/routers/lambda/_helpers/connectorManagePolicy.test.tsnew file mode 100644index 00000000000..4c220b12579--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/connectorManagePolicy.test.ts@@ -0,0 +1,107 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import {+ assertConnectorCredentialsManageable,+ assertConnectorMaintainable,+ canManageWorkspaceConnectors,+} from './connectorManagePolicy';++const workspaceMocks = vi.hoisted(() => ({+ getConnectorMemberManage: vi.fn(+ async (): Promise<'admins_only' | 'all_members'> => 'all_members',+ ),+}));+vi.mock('@/database/models/workspace', () => ({+ WorkspaceModel: vi.fn(function () {+ return workspaceMocks;+ }),+}));++const ctxFor = (workspaceRole?: string, workspaceId: string | null = 'ws-1') => ({+ serverDB: {} as any,+ userId: 'me',+ workspaceId,+ workspaceRole,+});++describe('connectorManagePolicy', () => {+ beforeEach(() => {+ workspaceMocks.getConnectorMemberManage.mockResolvedValue('all_members');+ });++ describe('canManageWorkspaceConnectors', () => {+ it('always allows personal mode, owners and admins', async () => {+ workspaceMocks.getConnectorMemberManage.mockResolvedValue('admins_only');++ await expect(canManageWorkspaceConnectors(ctxFor(undefined, null))).resolves.toBe(true);+ await expect(canManageWorkspaceConnectors(ctxFor('owner'))).resolves.toBe(true);+ await expect(canManageWorkspaceConnectors(ctxFor('admin'))).resolves.toBe(true);+ });++ it('never allows viewers', async () => {+ await expect(canManageWorkspaceConnectors(ctxFor('viewer'))).resolves.toBe(false);+ });++ it('follows the member policy for members, allowing them by default', async () => {+ await expect(canManageWorkspaceConnectors(ctxFor('member'))).resolves.toBe(true);++ workspaceMocks.getConnectorMemberManage.mockResolvedValue('admins_only');+ await expect(canManageWorkspaceConnectors(ctxFor('member'))).resolves.toBe(false);+ });+ });++ describe('assertConnectorMaintainable', () => {+ it('lets a member maintain a shared row someone else created by default', async () => {+ await expect(+ assertConnectorMaintainable(ctxFor('member'), { userId: 'someone-else' }),+ ).resolves.toBeUndefined();+ });++ it('rejects a member, even the creator, once admins restricted it', async () => {+ workspaceMocks.getConnectorMemberManage.mockResolvedValue('admins_only');++ await expect(+ assertConnectorMaintainable(ctxFor('member'), { userId: 'me' }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ await expect(assertConnectorMaintainable(ctxFor('member'))).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ });++ it('keeps the creator rule for agent-scoped rows', async () => {+ await expect(+ assertConnectorMaintainable(ctxFor('member'), { agentId: 'a1', userId: 'someone-else' }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ await expect(+ assertConnectorMaintainable(ctxFor('member'), { agentId: 'a1', userId: 'me' }),+ ).resolves.toBeUndefined();+ // A new agent row has no creator yet; agent edit rights gate it upstream.+ await expect(+ assertConnectorMaintainable(ctxFor('member'), { agentId: 'a1' }),+ ).resolves.toBeUndefined();+ });+ });++ describe('assertConnectorCredentialsManageable', () => {+ it("keeps another member's stored credentials creator/owner only", async () => {+ await expect(+ assertConnectorCredentialsManageable(ctxFor('member'), { userId: 'someone-else' }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ await expect(+ assertConnectorCredentialsManageable(ctxFor('member'), { userId: 'me' }),+ ).resolves.toBeUndefined();+ await expect(+ assertConnectorCredentialsManageable(ctxFor('owner'), { userId: 'someone-else' }),+ ).resolves.toBeUndefined();+ });++ it('also applies the member policy to the creator', async () => {+ workspaceMocks.getConnectorMemberManage.mockResolvedValue('admins_only');++ await expect(+ assertConnectorCredentialsManageable(ctxFor('member'), { userId: 'me' }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ });+ });+});diff --git a/apps/server/src/routers/lambda/_helpers/connectorManagePolicy.ts b/apps/server/src/routers/lambda/_helpers/connectorManagePolicy.tsnew file mode 100644index 00000000000..4dd74ff3aeb--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/connectorManagePolicy.ts@@ -0,0 +1,83 @@+import type { WorkspaceConnectorMemberManage } from '@lobechat/types';+import { TRPCError } from '@trpc/server';++import { WorkspaceModel } from '@/database/models/workspace';+import type { LobeChatDatabase } from '@/database/type';++import { assertWorkspaceRowManageable } from './assertWorkspaceRowManageable';++interface ConnectorManageCtx {+ serverDB: LobeChatDatabase;+ userId: string;+ workspaceId?: string | null;+ workspaceRole?: string;+}++/** The connector row being changed; omit when the write would create a new one. */+interface ConnectorRowRef {+ agentId?: string | null;+ userId?: string | null;+}++export const isWorkspaceConnectorAdmin = (+ ctx: Pick<ConnectorManageCtx, 'workspaceId' | 'workspaceRole'>,+) => ctx.workspaceRole === 'owner' || ctx.workspaceRole === 'admin';++export const getConnectorMemberManage = (+ ctx: ConnectorManageCtx,+): Promise<WorkspaceConnectorMemberManage> => {+ if (!ctx.workspaceId) return Promise.resolve('all_members');+ return new WorkspaceModel(ctx.serverDB, ctx.userId).getConnectorMemberManage(ctx.workspaceId);+};++/**+ * Whether the caller may maintain the workspace's shared connectors: owners and+ * admins always may, viewers never, and members unless an admin restricted it+ * to `admins_only`. Personal mode always passes.+ */+export const canManageWorkspaceConnectors = async (ctx: ConnectorManageCtx): Promise<boolean> => {+ if (!ctx.workspaceId) return true;+ if (isWorkspaceConnectorAdmin(ctx)) return true;+ if (ctx.workspaceRole === 'viewer') return false;+ return (await getConnectorMemberManage(ctx)) === 'all_members';+};++const forbidden = () =>+ new TRPCError({+ code: 'FORBIDDEN',+ message: 'Only workspace owners and admins can change connectors in this workspace',+ });++/**+ * Gate a maintenance write (connect, re-authorize, edit, sync, remove) on a+ * workspace connector by the workspace's member policy. Shared rows are+ * co-maintained, so the creator does not matter here; agent-scoped rows belong+ * to their agent's setup and keep the creator-or-owner rule.+ */+export const assertConnectorMaintainable = async (+ ctx: ConnectorManageCtx,+ row?: ConnectorRowRef,+): Promise<void> => {+ if (!ctx.workspaceId) return;+ if (row?.agentId) {+ // A new agent row is gated by the caller's edit rights on that agent.+ if (row.userId) assertWorkspaceRowManageable(ctx, row.userId, 'connector');+ return;+ }+ if (!(await canManageWorkspaceConnectors(ctx))) throw forbidden();+};++/**+ * Gate a write that hands a connector's stored credentials to someone else's+ * control (edit-form prefill, binding/copying/mounting it onto an agent). On top+ * of the member policy, only the creator or a workspace owner may do it, since+ * co-maintaining a connector does not mean reading another member's secrets.+ */+export const assertConnectorCredentialsManageable = async (+ ctx: ConnectorManageCtx,+ row: ConnectorRowRef,+): Promise<void> => {+ if (!ctx.workspaceId) return;+ if (!row.agentId && !(await canManageWorkspaceConnectors(ctx))) throw forbidden();+ assertWorkspaceRowManageable(ctx, row.userId, 'connector');+};diff --git a/apps/server/src/routers/lambda/composio.ts b/apps/server/src/routers/lambda/composio.tsindex 5504e658d49..9f6214ab16b 100644--- a/apps/server/src/routers/lambda/composio.ts+++ b/apps/server/src/routers/lambda/composio.ts@@ -25,7 +25,7 @@ import { inferCrudType } from '@/libs/mcp/utils';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';-import { assertWorkspaceRowManageable } from './_helpers/assertWorkspaceRowManageable';+import { assertConnectorMaintainable } from './_helpers/connectorManagePolicy';const composioProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {const { ctx } = opts;@@ -49,22 +49,22 @@ const composioProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts)});// Writes: in a workspace, require at least the member role (blocks viewers).-// Personal mode passes through. Row-level creator/owner enforcement is layered-// on top per-mutation via `assertComposioRowManageable` (mirrors the native-// connector router's connectorWriteProcedure + assertWorkspaceRowManageable).+// Personal mode passes through. The workspace connector policy is layered on+// top per-mutation via `assertComposioRowManageable` (mirrors the native+// connector router's connectorWriteProcedure + assertConnectorMaintainable).const composioWriteProcedure = composioProcedure.use(requireWorkspaceRoleWhenScoped('member'));/**- * Before mutating (overwriting/deleting) a Composio connection in a workspace,- * assert the caller may manage the existing row: creator or workspace owner.- * `buildWorkspaceWhere` makes workspace rows writable workspace-wide, so without- * this any member could overwrite/remove another member's connection by- * identifier/agentId. Checked BEFORE any external side effect (Composio account- * link/delete). No-op in personal mode.+ * Before connecting, re-authorizing or removing a Composio connection in a+ * workspace, assert the caller may maintain it under the workspace connector+ * policy (members co-maintain shared rows unless an admin restricted it;+ * agent-scoped rows keep the creator-or-owner rule). Checked BEFORE any+ * external side effect (Composio account link/delete). No-op in personal mode.*/async function assertComposioRowManageable(ctx: {connectorModel: ConnectorModel;+ serverDB: LobeChatDatabase;userId: string;workspaceId?: string | null;workspaceRole?: string;@@ -74,7 +74,7 @@ async function assertComposioRowManageable(): Promise<void> {if (!ctx.workspaceId) return;const existing = await ctx.connectorModel.findScopedByIdentifier(identifier, agentId);- if (existing) assertWorkspaceRowManageable(ctx, existing.userId, 'connector');+ await assertConnectorMaintainable(ctx, { agentId, userId: existing?.userId });}type ComposioToolInput = {diff --git a/apps/server/src/routers/lambda/connector.getForEdit.test.ts b/apps/server/src/routers/lambda/connector.getForEdit.test.tsindex 0a72f3e4188..55ae544ef18 100644--- a/apps/server/src/routers/lambda/connector.getForEdit.test.ts+++ b/apps/server/src/routers/lambda/connector.getForEdit.test.ts@@ -10,6 +10,14 @@ 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() }));+const workspaceMocks = vi.hoisted(() => ({+ getConnectorMemberManage: vi.fn(async () => 'all_members' as const),+}));+vi.mock('@/database/models/workspace', () => ({+ WorkspaceModel: vi.fn(function () {+ return workspaceMocks;+ }),+}));vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({KeyVaultsGateKeeper: { initWithEnvKey: async () => ({}) },}));diff --git a/apps/server/src/routers/lambda/connector.ts b/apps/server/src/routers/lambda/connector.tsindex 2bfa63fa1f2..74ec51e57ea 100644--- a/apps/server/src/routers/lambda/connector.ts+++ b/apps/server/src/routers/lambda/connector.ts@@ -1,4 +1,5 @@import { getComposioAppByIdentifier } from '@lobechat/const';+import { isFullAccessApiKey } from '@lobechat/const/apiKeyScope';import { upsertPluginMode } from '@lobechat/types';import { TRPCError } from '@trpc/server';import { z } from 'zod';@@ -11,6 +12,8 @@ import { AgentModel } from '@/database/models/agent';import { ConnectorModel } from '@/database/models/connector';import { ConnectorToolModel } from '@/database/models/connectorTool';import { PluginModel } from '@/database/models/plugin';+import { WorkspaceModel } from '@/database/models/workspace';+import { WorkspaceAuditLogModel } from '@/database/models/workspaceAuditLog';import type { ConnectorMetadata, OIDCConfig } from '@/database/schemas';import {ConnectorMcpConnectionType,@@ -49,6 +52,13 @@ import {assertWorkspaceRowManageable,isWorkspaceNonOwner,} from './_helpers/assertWorkspaceRowManageable';+import {+ assertConnectorCredentialsManageable,+ assertConnectorMaintainable,+ canManageWorkspaceConnectors,+ getConnectorMemberManage,+ isWorkspaceConnectorAdmin,+} from './_helpers/connectorManagePolicy';const connectorProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {const { ctx } = opts;@@ -266,8 +276,9 @@ export const connectorRouter = router({.query(async ({ input, ctx }) => {const connector = await ctx.connectorModel.findById(input.id);if (!connector) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });- // Edit-read returns decrypted credentials — same creator/owner gate as- // the mutations that this edit view feeds.+ // Edit-read returns decrypted credentials — creator/owner only. Not gated by+ // the member policy: desktop stdio/local connectors read their config+ // here at run time, so a restriction must not stop the creator using them.assertWorkspaceRowManageable(ctx, connector.userId, 'connector');const { oidcConfig, credentials, ...rest } = connector;@@ -287,6 +298,54 @@ export const connectorRouter = router({*/getRedirectUri: wsCompatProcedure.query(() => ({ redirectUri: getConnectorRedirectUri() })),+ /**+ * The caller's standing under the workspace connector policy: whether they may+ * maintain shared connectors, and whether they may change who can. Lets the+ * settings list disable what the server would reject instead of failing a click.+ */+ getManagePolicy: connectorProcedure.query(async ({ ctx }) => {+ const [canManage, memberManage] = await Promise.all([+ canManageWorkspaceConnectors(ctx),+ getConnectorMemberManage(ctx),+ ]);+ return {+ canEditPolicy: !!ctx.workspaceId && isWorkspaceConnectorAdmin(ctx),+ canManage,+ memberManage,+ };+ }),++ /** Owners and admins choose whether members may maintain shared connectors. */+ updateManagePolicy: connectorProcedure+ .use(requireWorkspaceRoleWhenScoped('admin'))+ .input(z.object({ memberManage: z.enum(['all_members', 'admins_only']) }))+ .mutation(async ({ input, ctx }) => {+ if (!ctx.workspaceId) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Connector policy applies to workspaces only',+ });+ }+ // A restricted API key must not rewrite who may change credentials.+ if (ctx.apiKeyScopes !== undefined && !isFullAccessApiKey(ctx.apiKeyScopes)) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'Restricted API keys cannot change the workspace connector policy',+ });+ }++ const workspaceModel = new WorkspaceModel(ctx.serverDB, ctx.userId);+ const previous = await workspaceModel.getConnectorMemberManage(ctx.workspaceId);+ await workspaceModel.updateConnectorMemberManage(ctx.workspaceId, input.memberManage);+ await new WorkspaceAuditLogModel(ctx.serverDB).create({+ action: 'security.policy_updated',+ metadata: { policy: 'connector.member_manage', previous, value: input.memberManage },+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ return { memberManage: input.memberManage };+ }),+// ── Mutations ─────────────────────────────────────────────────────────────create: connectorWriteProcedure.input(createConnectorSchema).mutation(async ({ input, ctx }) => {@@ -338,10 +397,14 @@ export const connectorRouter = router({// DB indexes are non-unique so multiple same-identifier rows can coexist// across scopes).const existing = await ctx.connectorModel.findScopedByIdentifier(input.identifier, agentId);+ // Adding a workspace connector follows the member policy. Re-adding over+ // someone else's row rewrites its server/command while the row stays theirs+ // (their runs would execute it, and they could read the new credentials), so+ // that keeps the creator-or-owner rule.+ if (existing && existing.userId !== ctx.userId)+ await assertConnectorCredentialsManageable(ctx, existing);+ else await assertConnectorMaintainable(ctx, { agentId, userId: existing?.userId });if (existing) {- // The upsert path rewrites another creator's config/credentials — only- // the creator (or a workspace owner) may re-add over an existing row.- assertWorkspaceRowManageable(ctx, existing.userId, 'connector');await ctx.connectorModel.update(existing.id, {...fields,isEnabled: input.isEnabled ?? true,@@ -385,7 +448,7 @@ export const connectorRouter = router({const connector = await ctx.connectorModel.findById(input.connectorId);if (!connector) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });// Rebinding routes the connector's credentials to the agent — creator/owner only.- assertWorkspaceRowManageable(ctx, connector.userId, 'connector');+ await assertConnectorCredentialsManageable(ctx, connector);const existingAgentRow = await ctx.connectorModel.findScopedByIdentifier(connector.identifier,@@ -413,7 +476,7 @@ export const connectorRouter = router({.mutation(async ({ input, ctx }) => {const connector = await ctx.connectorModel.findById(input.connectorId);if (!connector) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });- assertWorkspaceRowManageable(ctx, connector.userId, 'connector');+ await assertConnectorCredentialsManageable(ctx, connector);if (!connector.agentId) return { id: input.connectorId }; // already base — no-opconst existingBase = await ctx.connectorModel.findScopedByIdentifier(connector.identifier);@@ -445,7 +508,7 @@ export const connectorRouter = router({if (!source) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });// Cloning duplicates the source's encrypted credentials into a row the// agent owner controls — creator/owner only.- assertWorkspaceRowManageable(ctx, source.userId, 'connector');+ await assertConnectorCredentialsManageable(ctx, source);const existing = await ctx.connectorModel.findScopedByIdentifier(source.identifier,@@ -480,7 +543,7 @@ export const connectorRouter = router({if (!connector) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });// Mounting routes the source's credentials to the agent and locks the// row (metadata.mountedByAgentId) — creator/owner only.- assertWorkspaceRowManageable(ctx, connector.userId, 'connector');+ await assertConnectorCredentialsManageable(ctx, connector);if (connector.agentId) {throw new TRPCError({code: 'BAD_REQUEST',@@ -520,7 +583,7 @@ export const connectorRouter = router({const connector = await ctx.connectorModel.findById(input.connectorId);if (!connector) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });// Clearing the mount lock mutates the source row — creator/owner only.- assertWorkspaceRowManageable(ctx, connector.userId, 'connector');+ await assertConnectorCredentialsManageable(ctx, connector);const { mountedByAgentId: _drop, ...restMeta } = connector.metadata ?? {};await ctx.connectorModel.update(input.connectorId, { metadata: restMeta });@@ -541,8 +604,8 @@ export const connectorRouter = router({.mutation(async ({ input, ctx }) => {const connector = await ctx.connectorModel.findById(input.id);if (!connector) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });- // Re-authorizing overwrites the stored OAuth credentials.- assertWorkspaceRowManageable(ctx, connector.userId, 'connector');+ // Re-authorizing replaces the stored OAuth credentials with the caller's.+ await assertConnectorMaintainable(ctx, connector);if (!connector.mcpServerUrl) {throw new TRPCError({ code: 'BAD_REQUEST', message: 'Connector has no MCP server URL' });}@@ -658,7 +721,9 @@ export const connectorRouter = router({.mutation(async ({ input, ctx }) => {const target = await ctx.connectorModel.findById(input.id);if (!target) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });- assertWorkspaceRowManageable(ctx, target.userId, 'connector');+ // A patch may keep the stored credentials while repointing the server+ // URL, which would send them elsewhere — creator/owner only.+ await assertConnectorCredentialsManageable(ctx, target);const { credentials, ...patch } = input.patch;// Preserve the server-owned `composio.linkedByUserId` from the stored row@@ -687,7 +752,7 @@ export const connectorRouter = router({const target = await ctx.connectorModel.findById(input.id);// Missing row → keep the delete idempotent, nothing to authorize.if (!target) return;- assertWorkspaceRowManageable(ctx, target.userId, 'connector');+ await assertConnectorMaintainable(ctx, target);const connectedAccountId = target.metadata?.composio?.connectedAccountId;if (connectedAccountId) {@@ -740,9 +805,8 @@ export const connectorRouter = router({const target = await ctx.connectorModel.findById(input.id);if (!target) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });// Syncing rewrites the connector's tool rows and refreshes OAuth tokens —- // an edit-class operation, so it gets the same creator/owner gate as- // update/delete/reset.- assertWorkspaceRowManageable(ctx, target.userId, 'connector');+ // a maintenance operation, gated like delete/reset.+ await assertConnectorMaintainable(ctx, target);try {return await syncConnectorToolsById(input.id, ctx);} catch (err: any) {@@ -791,7 +855,7 @@ export const connectorRouter = router({const target = await ctx.connectorModel.findById(input.id);if (!target) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });// Permission gates decide what auto-runs for the whole workspace.- assertWorkspaceRowManageable(ctx, target.userId, 'connector');+ await assertConnectorMaintainable(ctx, target);const tools = await ctx.connectorToolModel.queryByConnector(input.id);await Promise.all(@@ -817,7 +881,9 @@ export const connectorRouter = router({const tool = await ctx.connectorToolModel.findById(input.toolId);if (!tool) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector tool not found' });const owner = await ctx.connectorModel.findById(tool.userConnectorId);- assertWorkspaceRowManageable(ctx, owner?.userId, 'connector');+ // A tool whose connector is outside the caller's scope is not theirs to gate.+ if (!owner) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });+ await assertConnectorMaintainable(ctx, owner);await ctx.connectorToolModel.updatePermission(input.toolId, input.permission);}),@@ -895,8 +961,8 @@ export const connectorRouter = router({.mutation(async ({ input, ctx }) => {const target = await ctx.connectorModel.findById(input.id);if (!target) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });- // Same edit-class gate as `syncTools` — rewrites the connector's tool rows.- assertWorkspaceRowManageable(ctx, target.userId, 'connector');+ // Same gate as `syncTools` — rewrites the connector's tool rows.+ await assertConnectorMaintainable(ctx, target);const syncInputs = input.tools.map((t) => ({crudType: inferCrudType(t.toolName),diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 9fc857b2663..97fdc0a27c5 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -2112,6 +2112,23 @@"tools.composio.servers.zendesk.readme": "Integrate with Zendesk to manage support tickets and customer interactions. Create, update, and track support requests, access customer data, and streamline your support operations.","tools.composio.tools": "tools","tools.composio.verifyAuth": "I have completed authentication",+ "tools.connectorFeedback.askAdmin": "Ask an admin to connect",+ "tools.connectorFeedback.askAdminCopied": "Request copied. Send it to a workspace owner or admin.",+ "tools.connectorFeedback.askAdminMessage": "Could you connect {{name}} for our LobeHub workspace? {{url}}",+ "tools.connectorFeedback.connectFailed": "Connection failed: {{reason}}",+ "tools.connectorFeedback.manageOnly": "Only workspace owners and admins can change connectors",+ "tools.connectorFeedback.reason.authIncomplete": "the authorization window closed before access to {{name}} was granted",+ "tools.connectorFeedback.reason.forbidden": "only workspace owners and admins can change connectors here",+ "tools.connectorFeedback.reason.network": "the network connection was interrupted",+ "tools.connectorFeedback.reason.unknown": "something went wrong",+ "tools.connectorFeedback.removeFailed": "Remove failed: {{reason}}. The connector is still here, so you can try again.",+ "tools.connectorFeedback.removeFailedFinal": "Remove failed: {{reason}}",+ "tools.connectorFeedback.restricted": "Connectors in this workspace are managed by its owners and admins.",+ "tools.connectorPolicy.desc": "Choose who can connect, re-authorize and remove the connectors shared in this workspace.",+ "tools.connectorPolicy.options.allMembers": "All members",+ "tools.connectorPolicy.options.onlyAdmins": "Owners and admins",+ "tools.connectorPolicy.title": "Who can manage connectors",+ "tools.connectorPolicy.updateFailed": "Couldn't update who can manage connectors. Please try again.","tools.disabled": "The current model does not support function calls and cannot use the skill","tools.legacyConnector.configure": "Configure","tools.legacyConnector.upgradeDesc": "This connector still uses the legacy plugin format. Configure it to finish upgrading, then manage its tool permissions here.",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex 667c7319d08..af0e9c4aa70 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -2112,6 +2112,23 @@"tools.composio.servers.zendesk.readme": "集成 Zendesk 以管理支持工单和客户互动。创建、更新和跟踪支持请求,访问客户数据,并优化您的客服流程。","tools.composio.tools": "个工具","tools.composio.verifyAuth": "我已完成认证",+ "tools.connectorFeedback.askAdmin": "请管理员连接",+ "tools.connectorFeedback.askAdminCopied": "已复制请求,发给工作区 Owner 或管理员即可",+ "tools.connectorFeedback.askAdminMessage": "能帮忙在 LobeHub 工作区连接一下 {{name}} 吗?{{url}}",+ "tools.connectorFeedback.connectFailed": "连接没成功:{{reason}}",+ "tools.connectorFeedback.manageOnly": "仅工作区 Owner 和管理员可修改连接器",+ "tools.connectorFeedback.reason.authIncomplete": "授权窗口被关掉了,还没拿到 {{name}} 的权限",+ "tools.connectorFeedback.reason.forbidden": "这个工作区的连接器仅 Owner 和管理员可修改",+ "tools.connectorFeedback.reason.network": "网络中断了",+ "tools.connectorFeedback.reason.unknown": "出了点问题",+ "tools.connectorFeedback.removeFailed": "删除失败:{{reason}},连接器还在,可以重试",+ "tools.connectorFeedback.removeFailedFinal": "删除失败:{{reason}}",+ "tools.connectorFeedback.restricted": "这个工作区的连接器由 Owner 和管理员维护。",+ "tools.connectorPolicy.desc": "选择谁可以连接、重新授权和删除这个工作区共享的连接器。",+ "tools.connectorPolicy.options.allMembers": "所有成员",+ "tools.connectorPolicy.options.onlyAdmins": "仅 Owner 和管理员",+ "tools.connectorPolicy.title": "连接器管理权限",+ "tools.connectorPolicy.updateFailed": "没能更新连接器管理权限,请重试","tools.disabled": "当前模型不支持函数调用,无法使用技能","tools.legacyConnector.configure": "配置","tools.legacyConnector.upgradeDesc": "此连接器仍在使用旧的插件格式。点击「配置」完成升级后,即可在此管理它的工具权限。",diff --git a/packages/database/src/models/__tests__/workspace.test.ts b/packages/database/src/models/__tests__/workspace.test.tsindex 40730475375..7b34278d6f9 100644--- a/packages/database/src/models/__tests__/workspace.test.ts+++ b/packages/database/src/models/__tests__/workspace.test.ts@@ -336,6 +336,26 @@ describe('WorkspaceModel', () => {});});+ it('defaults connector management to all members and updates it without replacing settings', async () => {+ const workspaceId = await createWorkspace();+ const model = new WorkspaceModel(serverDB, ownerId);++ await expect(model.getConnectorMemberManage(workspaceId)).resolves.toBe('all_members');+ await model.updateApiKeyMemberCreation(workspaceId, 'admins_only');+ await model.updateConnectorMemberManage(workspaceId, 'admins_only');++ await expect(model.getConnectorMemberManage(workspaceId)).resolves.toBe('admins_only');+ await expect(model.getSettings(workspaceId)).resolves.toEqual({+ apiKey: { memberCreation: 'admins_only' },+ connector: { memberManage: 'admins_only' },+ gracePeriodUntil: 123,+ keep: true,+ });++ await model.updateConnectorMemberManage(workspaceId, 'all_members');+ await expect(model.getConnectorMemberManage(workspaceId)).resolves.toBe('all_members');+ });+it('finds a workspace by id and by slug, and returns undefined when missing', async () => {const workspaceId = await createWorkspace();const model = new WorkspaceModel(serverDB, ownerId);diff --git a/packages/database/src/models/workspace.ts b/packages/database/src/models/workspace.tsindex a1a37a45236..5a98f49920b 100644--- a/packages/database/src/models/workspace.ts+++ b/packages/database/src/models/workspace.ts@@ -1,4 +1,7 @@-import type { WorkspaceApiKeyMemberCreation } from '@lobechat/types';+import type {+ WorkspaceApiKeyMemberCreation,+ WorkspaceConnectorMemberManage,+} from '@lobechat/types';import { and, count, desc, eq, isNull, sql } from 'drizzle-orm';import {@@ -81,6 +84,19 @@ export const getWorkspaceApiKeyMemberCreation = (: 'all_members';};+export const getWorkspaceConnectorMemberManage = (+ settings: unknown,+): WorkspaceConnectorMemberManage => {+ if (!settings || typeof settings !== 'object') return 'all_members';++ const connector = (settings as { connector?: unknown }).connector;+ if (!connector || typeof connector !== 'object') return 'all_members';++ return (connector as { memberManage?: unknown }).memberManage === 'admins_only'+ ? 'admins_only'+ : 'all_members';+};+export class WorkspaceModel {protected readonly db: LobeChatDatabase;protected readonly userId: string;@@ -188,6 +204,10 @@ export class WorkspaceModel {return getWorkspaceApiKeyMemberCreation(await this.getSettings(id));};+ getConnectorMemberManage = async (id: string): Promise<WorkspaceConnectorMemberManage> => {+ return getWorkspaceConnectorMemberManage(await this.getSettings(id));+ };+/*** Count every workspace this user belongs to — owned + joined. Reads the* membership table directly because owners are always inserted as members on@@ -254,6 +274,22 @@ export class WorkspaceModel {.where(eq(workspaces.id, id));};+ updateConnectorMemberManage = async (+ id: string,+ memberManage: WorkspaceConnectorMemberManage,+ ) => {+ return this.db+ .update(workspaces)+ .set({+ settings: sql`coalesce(${workspaces.settings}, '{}'::jsonb) || jsonb_build_object(+ 'connector',+ coalesce(${workspaces.settings}->'connector', '{}'::jsonb) || jsonb_build_object('memberManage', ${memberManage}::text)+ )`,+ updatedAt: new Date(),+ })+ .where(eq(workspaces.id, id));+ };+/*** Transfer the unique Owner role and Stripe binding to an existing Admin.* The previous Owner becomes Admin in the same transaction, keepingdiff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 0525e85cb9d..8e260223c65 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -4153,6 +4153,31 @@ When I am ___, I need ___'tools.composio.tools': 'tools','tools.composio.verifyAuth': 'I have completed authentication',+ 'tools.connectorFeedback.askAdmin': 'Ask an admin to connect',+ 'tools.connectorFeedback.askAdminCopied':+ 'Request copied. Send it to a workspace owner or admin.',+ 'tools.connectorFeedback.askAdminMessage':+ 'Could you connect {{name}} for our LobeHub workspace? {{url}}',+ 'tools.connectorFeedback.connectFailed': 'Connection failed: {{reason}}',+ 'tools.connectorFeedback.manageOnly': 'Only workspace owners and admins can change connectors',+ 'tools.connectorFeedback.reason.authIncomplete':+ 'the authorization window closed before access to {{name}} was granted',+ 'tools.connectorFeedback.reason.forbidden':+ 'only workspace owners and admins can change connectors here',+ 'tools.connectorFeedback.reason.network': 'the network connection was interrupted',+ 'tools.connectorFeedback.reason.unknown': 'something went wrong',+ 'tools.connectorFeedback.removeFailed':+ 'Remove failed: {{reason}}. The connector is still here, so you can try again.',+ 'tools.connectorFeedback.removeFailedFinal': 'Remove failed: {{reason}}',+ 'tools.connectorFeedback.restricted':+ 'Connectors in this workspace are managed by its owners and admins.',+ 'tools.connectorPolicy.desc':+ 'Choose who can connect, re-authorize and remove the connectors shared in this workspace.',+ 'tools.connectorPolicy.options.allMembers': 'All members',+ 'tools.connectorPolicy.options.onlyAdmins': 'Owners and admins',+ 'tools.connectorPolicy.title': 'Who can manage connectors',+ 'tools.connectorPolicy.updateFailed':+ "Couldn't update who can manage connectors. Please try again.",'tools.lobehubSkill.authorize': 'Authorize',diff --git a/packages/types/src/apiKey.ts b/packages/types/src/apiKey.tsindex bf6b777080f..75cb9eab54d 100644--- a/packages/types/src/apiKey.ts+++ b/packages/types/src/apiKey.ts@@ -37,3 +37,11 @@ export interface UpdateApiKeyParams {}export type WorkspaceApiKeyMemberCreation = 'admins_only' | 'all_members';++/**+ * Who may connect, re-authorize, sync or remove the workspace's shared+ * connectors. Workspace owners and admins always can; `all_members` (the+ * default) lets every member co-maintain them. Reading or rewriting another+ * member's stored credentials stays with that creator and the workspace owner.+ */+export type WorkspaceConnectorMemberManage = 'admins_only' | 'all_members';diff --git a/src/features/Connectors/ConnectorActionErrorText.tsx b/src/features/Connectors/ConnectorActionErrorText.tsxnew file mode 100644index 00000000000..760f28471b1--- /dev/null+++ b/src/features/Connectors/ConnectorActionErrorText.tsx@@ -0,0 +1,55 @@+'use client';++import { Icon } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { CircleAlert } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { type ConnectorActionError } from '@/utils/connectorActionError';++import { formatConnectorActionError } from './formatConnectorActionError';++const styles = stylex.create({+ error: {+ alignItems: 'flex-start',+ color: cssVar.colorError,+ display: 'flex',+ fontSize: 12,+ gap: 4,+ lineHeight: 1.5,+ wordBreak: 'break-word',+ },+ icon: {+ flex: 'none',+ marginBlockStart: 3,+ },+});++interface ConnectorActionErrorTextProps {+ error: ConnectorActionError;+ /** Display name of the connector, used by reasons that name the app. */+ name: string;+}++/**+ * Red, in-place reason of a failed connect / remove. It stays where the action+ * was taken, so the user still sees what happened after any toast is gone.+ */+const ConnectorActionErrorText = memo<ConnectorActionErrorTextProps>(({ error, name }) => {+ const { t } = useTranslation('setting');++ return (+ <div role={'alert'} {...stylex.props(styles.error)}>+ <span {...stylex.props(styles.icon)}>+ <Icon icon={CircleAlert} size={12} />+ </span>+ <span>{formatConnectorActionError(t, error, name)}</span>+ </div>+ );+});++ConnectorActionErrorText.displayName = 'ConnectorActionErrorText';++export default ConnectorActionErrorText;diff --git a/src/features/Connectors/ConnectorDetail/index.tsx b/src/features/Connectors/ConnectorDetail/index.tsxindex 7d4afa77ff1..482e803968b 100644--- a/src/features/Connectors/ConnectorDetail/index.tsx+++ b/src/features/Connectors/ConnectorDetail/index.tsx@@ -7,10 +7,13 @@ import { useTranslation } from 'react-i18next';import type { ConnectorToolPermission } from '@/database/schemas';import { ConnectorSourceType } from '@/database/schemas';-import { useResourceManageable } from '@/hooks/useResourceManageable';+import { useConnectorManageable } from '@/hooks/useConnectorManagePolicy';+import { refreshConnectorManagePolicy } from '@/services/connectorManagePolicy';import { useToolStore } from '@/store/tool';import { connectorSelectors } from '@/store/tool/slices/connector';+import { type ConnectorActionError, toConnectorActionError } from '@/utils/connectorActionError';+import ConnectorActionErrorText from '../ConnectorActionErrorText';import CustomConnectorModal from '../CustomConnectorModal';import { getLocalizedConnectorDetail } from './localization';import ToolPermissionGroup from './ToolPermissionGroup';@@ -66,6 +69,7 @@ const ConnectorDetail = memo<ConnectorDetailProps>(const resetConnectorPermissions = useToolStore((s) => s.resetConnectorPermissions);const disconnectConnector = useToolStore((s) => s.disconnectConnector);const deleteConnector = useToolStore((s) => s.deleteConnector);+ const forgetComposioConnection = useToolStore((s) => s.forgetComposioConnection);const uninstallBuiltinTool = useToolStore((s) => s.uninstallBuiltinTool);const uninstallMCPPlugin = useToolStore((s) => s.uninstallMCPPlugin);const fetchConnectors = useToolStore((s) => s.fetchConnectors);@@ -75,15 +79,21 @@ const ConnectorDetail = memo<ConnectorDetailProps>(const isBuiltin = connector?.sourceType === ConnectorSourceType.builtin;const isMarketplace = connector?.sourceType === ConnectorSourceType.marketplace;- // Only the creator or a workspace owner may manage this connector — the- // server enforces the same rule, this keeps the UI honest about it.- const canManage = useResourceManageable(connector?.userId);- const manageTooltip = canManage- ? undefined- : t(- 'connector.manageOnlyCreator',- 'Only the creator or a workspace owner can manage this connector',- );+ // Members co-maintain shared connectors unless the workspace restricted it;+ // editing the stored credentials stays with the creator or a workspace+ // owner. The server enforces both, this keeps the UI honest about it.+ const { canManage, canManageCredentials, isPending, restrictedByPolicy } =+ useConnectorManageable(connector);+ const creatorOnlyTooltip = t(+ 'connector.manageOnlyCreator',+ 'Only the creator or a workspace owner can manage this connector',+ );+ const deniedTooltip = restrictedByPolicy+ ? ts('tools.connectorFeedback.manageOnly')+ : creatorOnlyTooltip;+ // While the policy loads the controls are disabled without a reason yet.+ const manageTooltip = canManage || isPending ? undefined : deniedTooltip;+ const credentialsTooltip = canManageCredentials || isPending ? undefined : deniedTooltip;// Deleting/uninstalling revokes the user's authorization; spell out the// consequence. For an agent-owned connector it ALSO unpins the tool from@@ -99,25 +109,44 @@ const ConnectorDetail = memo<ConnectorDetailProps>('This removes the connector and its authorization from your account. Any agent that uses it will need to be re-authorized afterwards.',});+ // A 403 means the cached policy was stale: refetch it so the buttons turn+ // disabled with their hover reason, rather than reporting a permission error+ // for a button that looked usable. Returns whether it was such a rejection.+ const settlePermissionRejection = useCallback((error: unknown) => {+ const httpStatus = (error as { data?: { httpStatus?: number } })?.data?.httpStatus;+ if (httpStatus !== 403) return false;+ void refreshConnectorManagePolicy();+ return true;+ }, []);+const notifyActionError = useCallback((error: unknown) => {- const httpStatus = (error as { data?: { httpStatus?: number } })?.data?.httpStatus;- toast.error(- httpStatus === 403- ? t(- 'connector.manageOnlyCreator',- 'Only the creator or a workspace owner can manage this connector',- )- : t('connector.actionFailed', 'Operation failed, please try again'),- );+ if (settlePermissionRejection(error)) return;+ toast.error(t('connector.actionFailed', 'Operation failed, please try again'));+ },+ [settlePermissionRejection, t],+ );++ // A failed uninstall / delete / disconnect also stays in the panel: the toast+ // is gone long before the user looks back. Keyed by connector so switching+ // to another one never shows a stale reason.+ const [removeError, setRemoveError] = useState<{+ connectorId: string;+ error: ConnectorActionError;+ }>();+ const notifyRemoveError = useCallback(+ (error: unknown) => {+ if (settlePermissionRejection(error)) return;+ notifyActionError(error);+ setRemoveError({ connectorId, error: toConnectorActionError('remove', error) });},- [t],+ [connectorId, notifyActionError, settlePermissionRejection],);- // Custom connector sync hits the remote MCP server with stored credentials- // and rewrites tool rows — creator/owner only (enforced server-side too).- // Builtin/marketplace bootstrap syncs are no-ops for non-managers.- const canSync = canManage || connector?.sourceType !== ConnectorSourceType.custom;+ // Custom connector sync uses the stored credentials (on desktop it reads them+ // through the creator/owner-only edit read), so it follows the credentials+ // gate. Builtin/marketplace bootstrap syncs are no-ops for non-managers.+ const canSync = canManageCredentials || connector?.sourceType !== ConnectorSourceType.custom;const handleSync = useCallback(async () => {if (!connector) return;@@ -147,6 +176,7 @@ const ConnectorDetail = memo<ConnectorDetailProps>(content: deleteConfirmContent,okButtonProps: { danger: true },onOk: async () => {+ setRemoveError(undefined);try {if (isBuiltin) {await uninstallBuiltinTool(connector.identifier);@@ -154,9 +184,13 @@ const ConnectorDetail = memo<ConnectorDetailProps>(await uninstallMCPPlugin(connector.identifier);}await deleteConnector(connectorId);+ // The Composio list does not watch these writes; without this the+ // uninstalled row keeps showing as connected until a reload.+ if (getComposioAppByIdentifier(connector.identifier))+ forgetComposioConnection(connector.identifier);onDelete?.();} catch (error) {- notifyActionError(error);+ notifyRemoveError(error);}},title: t('connector.uninstallConfirm', 'Uninstall this tool?'),@@ -243,7 +277,7 @@ const ConnectorDetail = memo<ConnectorDetailProps>(</Button></ManageTooltip>{/* Sync/Refresh: re-sync tool list from manifest */}- <ManageTooltip title={canSync ? undefined : manageTooltip}>+ <ManageTooltip title={canSync ? undefined : credentialsTooltip}><Buttondisabled={!canSync}icon={<RefreshCwIcon size={14} />}@@ -256,9 +290,9 @@ const ConnectorDetail = memo<ConnectorDetailProps>(</ManageTooltip>{/* Edit button for custom MCP connectors — only http type has a server URL to edit */}{isMcpConnector && connector?.mcpConnectionType === 'http' && (- <ManageTooltip title={manageTooltip}>+ <ManageTooltip title={credentialsTooltip}><Button- disabled={!canManage}+ disabled={!canManageCredentials}icon={<PencilIcon size={14} />}size="small"onClick={() => setCustomModalOpen(true)}@@ -280,10 +314,11 @@ const ConnectorDetail = memo<ConnectorDetailProps>(disabled={!canManage}size="small"onClick={async () => {+ setRemoveError(undefined);try {await disconnectConnector(connectorId);} catch (error) {- notifyActionError(error);+ notifyRemoveError(error);}}}>@@ -301,11 +336,12 @@ const ConnectorDetail = memo<ConnectorDetailProps>(content: deleteConfirmContent,okButtonProps: { danger: true },onOk: async () => {+ setRemoveError(undefined);try {await deleteConnector(connectorId);onDelete?.();} catch (error) {- notifyActionError(error);+ notifyRemoveError(error);}},title: t('connector.deleteConfirm', 'Delete this connector?'),@@ -319,10 +355,10 @@ const ConnectorDetail = memo<ConnectorDetailProps>()}{/* Uninstall for builtin and marketplace tools */}{(isBuiltin || isMarketplace) && (- <ManageTooltip title={manageTooltip}>+ <ManageTooltip title={credentialsTooltip}><Buttondanger- disabled={!canManage}+ disabled={!canManageCredentials}icon={<Trash2 size={14} />}size="small"onClick={handleUninstall}@@ -346,6 +382,12 @@ const ConnectorDetail = memo<ConnectorDetailProps>(padding: 16,}}>+ {removeError?.connectorId === connectorId && (+ <div style={{ marginBottom: 12 }}>+ <ConnectorActionErrorText error={removeError.error} name={connectorName} />+ </div>+ )}+{/* Description */}{connectorDescription && (<divdiff --git a/src/features/Connectors/formatConnectorActionError.test.ts b/src/features/Connectors/formatConnectorActionError.test.tsnew file mode 100644index 00000000000..55cefbc819e--- /dev/null+++ b/src/features/Connectors/formatConnectorActionError.test.ts@@ -0,0 +1,55 @@+import { type TFunction } from 'i18next';+import { describe, expect, it } from 'vitest';++import { formatConnectorActionError } from './formatConnectorActionError';++const t = ((key: string, options?: Record<string, unknown>) =>+ options ? `${key}(${JSON.stringify(options)})` : key) as unknown as TFunction<'setting'>;++describe('formatConnectorActionError', () => {+ it('explains a permission rejection of a connect', () => {+ expect(formatConnectorActionError(t, { action: 'connect', code: 'FORBIDDEN' }, 'Gmail')).toBe(+ 'tools.connectorFeedback.connectFailed({"reason":"tools.connectorFeedback.reason.forbidden"})',+ );+ });++ it('explains a dropped remove and keeps the connector-still-here wording', () => {+ expect(formatConnectorActionError(t, { action: 'remove', code: 'NETWORK' }, 'Gmail')).toBe(+ 'tools.connectorFeedback.removeFailed({"reason":"tools.connectorFeedback.reason.network"})',+ );+ });++ it('does not invite a retry when a removal is forbidden', () => {+ expect(formatConnectorActionError(t, { action: 'remove', code: 'FORBIDDEN' }, 'Gmail')).toBe(+ 'tools.connectorFeedback.removeFailedFinal({"reason":"tools.connectorFeedback.reason.forbidden"})',+ );+ });++ it('names the app when the OAuth window closed without access', () => {+ expect(+ formatConnectorActionError(t, { action: 'connect', code: 'AUTH_INCOMPLETE' }, 'Gmail'),+ ).toContain('reason.authIncomplete({\\"name\\":\\"Gmail\\"})');+ });++ it('shows an actionable BAD_REQUEST message as-is', () => {+ expect(+ formatConnectorActionError(+ t,+ { action: 'connect', code: 'BAD_REQUEST', message: 'Provide an OAuth Client ID' },+ 'Gmail',+ ),+ ).toBe('tools.connectorFeedback.connectFailed({"reason":"Provide an OAuth Client ID"})');+ });++ it('hides raw upstream output behind a generic reason', () => {+ expect(+ formatConnectorActionError(+ t,+ { action: 'connect', code: 'INTERNAL_SERVER_ERROR', message: '401 {"error":{}}' },+ 'Gmail',+ ),+ ).toBe(+ 'tools.connectorFeedback.connectFailed({"reason":"tools.connectorFeedback.reason.unknown"})',+ );+ });+});diff --git a/src/features/Connectors/formatConnectorActionError.ts b/src/features/Connectors/formatConnectorActionError.tsnew file mode 100644index 00000000000..68436de57e1--- /dev/null+++ b/src/features/Connectors/formatConnectorActionError.ts@@ -0,0 +1,46 @@+import { type TFunction } from 'i18next';++import { type ConnectorActionError } from '@/utils/connectorActionError';++/**+ * Localized, in-row explanation of a failed connector write. A permission+ * rejection, a dropped request and an abandoned OAuth window get plain wording.+ * A `BAD_REQUEST` carries a reason the user can act on (e.g. an OAuth server+ * that rejects registration), so its message is shown as-is; any other failure+ * gets a generic reason instead of raw upstream output.+ */+export const formatConnectorActionError = (+ t: TFunction<'setting'>,+ error: ConnectorActionError,+ name: string,+): string => {+ let reason: string;+ switch (error.code) {+ case 'FORBIDDEN': {+ reason = t('tools.connectorFeedback.reason.forbidden');+ break;+ }+ case 'NETWORK': {+ reason = t('tools.connectorFeedback.reason.network');+ break;+ }+ case 'AUTH_INCOMPLETE': {+ reason = t('tools.connectorFeedback.reason.authIncomplete', { name });+ break;+ }+ case 'BAD_REQUEST': {+ reason = error.message || t('tools.connectorFeedback.reason.unknown');+ break;+ }+ default: {+ reason = t('tools.connectorFeedback.reason.unknown');+ }+ }++ if (error.action === 'connect') return t('tools.connectorFeedback.connectFailed', { reason });++ // A permission rejection will fail again, so do not invite a retry.+ return error.code === 'FORBIDDEN'+ ? t('tools.connectorFeedback.removeFailedFinal', { reason })+ : t('tools.connectorFeedback.removeFailed', { reason });+};diff --git a/src/features/Settings/skill/features/ComposioSkillItem.tsx b/src/features/Settings/skill/features/ComposioSkillItem.tsxindex bcbbd55fad1..95c35023ce7 100644--- a/src/features/Settings/skill/features/ComposioSkillItem.tsx+++ b/src/features/Settings/skill/features/ComposioSkillItem.tsx@@ -28,8 +28,14 @@ import NavItem from '@/features/NavPanel/components/NavItem';import { usePermission } from '@/hooks/usePermission';import { useToolStore } from '@/store/tool';import { type ComposioServer } from '@/store/tool/slices/composioStore';-import { ComposioServerStatus } from '@/store/tool/slices/composioStore';+import { ComposioServerStatus, composioStoreSelectors } from '@/store/tool/slices/composioStore';+import {+ AskAdminButton,+ DisabledConnect,+ renderConnectorRowDescription,+} from './ConnectorRowFeedback';+import { isSettledByConnection, useConnectorManageGate } from './connectorRowState';import { styles } from './style';const POLL_INTERVAL_MS = 1000;@@ -60,6 +66,13 @@ const ComposioSkillItem = memo<ComposioSkillItemProps>(const refreshComposioConnectionStatus = useToolStore((s) => s.refreshComposioConnectionStatus);const removeComposioConnection = useToolStore((s) => s.removeComposioConnection);const reauthorizeComposioConnection = useToolStore((s) => s.reauthorizeComposioConnection);+ const setServerError = useToolStore((s) => s.setComposioServerError);+ const actionError = useToolStore(composioStoreSelectors.getServerError(serverType.identifier));++ // Without the row-level gate a member's click hits a 403 and looks dead.+ const { access } = useConnectorManageGate(serverType.identifier);+ const canManage = access === 'allowed';+ const isRestricted = access === 'restricted';const cleanup = useCallback(() => {if (windowCheckIntervalRef.current) {@@ -108,9 +121,17 @@ const ComposioSkillItem = memo<ComposioSkillItemProps>(pollIntervalRef.current = null;}setIsWaitingAuth(false);+ // The OAuth window is gone and the connection never became active:+ // say so on the row, the user may not have noticed the popup failed.+ const latest = composioStoreSelectors.getServerByIdentifier(identifier)(+ useToolStore.getState(),+ );+ if (latest?.status !== ComposioServerStatus.ACTIVE) {+ setServerError(identifier, { action: 'connect', code: 'AUTH_INCOMPLETE' });+ }}, POLL_TIMEOUT_MS);},- [refreshComposioConnectionStatus],+ [refreshComposioConnectionStatus, setServerError],);const startWindowMonitor = useCallback(@@ -155,7 +176,7 @@ const ComposioSkillItem = memo<ComposioSkillItemProps>();const handleConnect = async () => {- if (!canCreate || !canEdit) return;+ if (!canCreate || !canEdit || !canManage) return;if (server) return;setIsConnecting(true);@@ -181,7 +202,7 @@ const ComposioSkillItem = memo<ComposioSkillItemProps>(};const handleReauthorize = async () => {- if (!canCreate || !canEdit || !server) return;+ if (!canCreate || !canEdit || !canManage || !server) return;setIsConnecting(true);try {const newServer = await reauthorizeComposioConnection(server.identifier);@@ -196,12 +217,12 @@ const ComposioSkillItem = memo<ComposioSkillItemProps>(};const handleDelete = async () => {- if (!canEdit || !server) return;+ if (!canEdit || !canManage || !server) return;await removeComposioConnection(server.identifier);};const handleDisconnect = () => {- if (!canEdit) return;+ if (!canEdit || !canManage) return;if (!server) return;confirmModal({cancelText: t('cancel', { ns: 'common' }),@@ -261,11 +282,20 @@ const ComposioSkillItem = memo<ComposioSkillItemProps>();}+ if (isRestricted && server?.status !== ComposioServerStatus.ACTIVE) {+ return (+ <Flexbox horizontal align="center" gap={8}>+ <DisabledConnect size="middle" />+ <AskAdminButton name={serverType.label} variant="primary" />+ </Flexbox>+ );+ }+if (!server) {return (<Tooltip title={!canCreate ? createReason : editReason}><Button- disabled={!canCreate || !canEdit}+ disabled={!canCreate || !canEdit || !canManage}icon={<Icon icon={SquareArrowOutUpRight} />}type="default"onClick={handleConnect}@@ -304,8 +334,8 @@ const ComposioSkillItem = memo<ComposioSkillItemProps>(},]}>- <Tooltip title={editReason}>- <LobeButton disabled={!canEdit} icon={MoreHorizontalIcon} />+ <Tooltip title={isRestricted ? t('tools.connectorFeedback.manageOnly') : editReason}>+ <LobeButton disabled={!canEdit || !canManage} icon={MoreHorizontalIcon} /></Tooltip></DropdownMenu>);@@ -326,8 +356,8 @@ const ComposioSkillItem = memo<ComposioSkillItemProps>(},]}>- <Tooltip title={editReason}>- <LobeButton disabled={!canEdit} icon={MoreHorizontalIcon} />+ <Tooltip title={isRestricted ? t('tools.connectorFeedback.manageOnly') : editReason}>+ <LobeButton disabled={!canEdit || !canManage} icon={MoreHorizontalIcon} /></Tooltip></DropdownMenu>);@@ -337,6 +367,20 @@ const ComposioSkillItem = memo<ComposioSkillItemProps>(};const isConnected = server?.status === ComposioServerStatus.ACTIVE;+ const description = renderConnectorRowDescription({+ askAdmin: isRestricted && !isConnected,+ error: actionError,+ name: serverType.label,+ });++ // A connection that became active (also through a later list revalidation,+ // e.g. after a slow OAuth) settles any earlier connect failure. A failed+ // remove leaves the row active on purpose, so its reason stays.+ const hasStaleConnectError = isSettledByConnection(isConnected, actionError);+ useEffect(() => {+ if (hasStaleConnectError) setServerError(serverType.identifier, undefined);+ }, [hasStaleConnectError, serverType.identifier, setServerError]);+const isPending = server?.status === ComposioServerStatus.PENDING_AUTH;const isError = server?.status === ComposioServerStatus.ERROR;@@ -357,11 +401,14 @@ const ComposioSkillItem = memo<ComposioSkillItemProps>(</Tooltip>);}+ if (isRestricted) {+ return <DisabledConnect />;+ }if (isPending || isError) {return (<Tooltip title={!canCreate ? createReason : editReason}><Button- disabled={!canCreate || !canEdit}+ disabled={!canCreate || !canEdit || !canManage}icon={<Icon icon={SquareArrowOutUpRight} />}size="small"type="text"@@ -375,7 +422,7 @@ const ComposioSkillItem = memo<ComposioSkillItemProps>(return (<Tooltip title={!canCreate ? createReason : editReason}><Button- disabled={!canCreate || !canEdit}+ disabled={!canCreate || !canEdit || !canManage}icon={<Icon icon={SquareArrowOutUpRight} />}size="small"type="text"@@ -396,6 +443,7 @@ const ComposioSkillItem = memo<ComposioSkillItemProps>(return (<NavItemactive={isSelected}+ description={description}extra={renderNavExtra()}icon={renderNavIcon}title={serverType.label}diff --git a/src/features/Settings/skill/features/ConnectorManagePolicy.tsx b/src/features/Settings/skill/features/ConnectorManagePolicy.tsxnew file mode 100644index 00000000000..80f273c934b--- /dev/null+++ b/src/features/Settings/skill/features/ConnectorManagePolicy.tsx@@ -0,0 +1,82 @@+'use client';++import { type WorkspaceConnectorMemberManage } from '@lobechat/types';+import { Flexbox, Select, Text, toast } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useConnectorManagePolicy } from '@/hooks/useConnectorManagePolicy';+import { updateConnectorManagePolicy } from '@/services/connectorManagePolicy';++const styles = stylex.create({+ root: {+ borderBlockEndColor: cssVar.colorBorderSecondary,+ borderBlockEndStyle: 'solid',+ borderBlockEndWidth: 1,+ flexShrink: 0,+ paddingBlock: 10,+ paddingInline: 16,+ },+});++/**+ * Workspace owners and admins choose whether members may maintain the shared+ * connectors. A restricted member gets one line saying so here instead of a+ * repeated label on every row, which only offers "Ask an admin".+ */+const ConnectorManagePolicy = memo(() => {+ const { t } = useTranslation('setting');+ const { data: policy } = useConnectorManagePolicy();+ const [updating, setUpdating] = useState(false);++ if (!policy) return null;++ if (!policy.canEditPolicy) {+ if (policy.canManage) return null;+ return (+ <Text fontSize={12} type={'secondary'} {...stylex.props(styles.root)}>+ {t('tools.connectorFeedback.restricted')}+ </Text>+ );+ }++ const handleChange = async (value: WorkspaceConnectorMemberManage) => {+ setUpdating(true);+ try {+ await updateConnectorManagePolicy(value);+ } catch {+ toast.error(t('tools.connectorPolicy.updateFailed'));+ } finally {+ setUpdating(false);+ }+ };++ return (+ <Flexbox gap={8} {...stylex.props(styles.root)}>+ <Flexbox gap={2}>+ <Text strong fontSize={13}>+ {t('tools.connectorPolicy.title')}+ </Text>+ <Text fontSize={12} type={'secondary'}>+ {t('tools.connectorPolicy.desc')}+ </Text>+ </Flexbox>+ <Select+ disabled={updating}+ size={'small'}+ value={policy.memberManage}+ options={[+ { label: t('tools.connectorPolicy.options.allMembers'), value: 'all_members' },+ { label: t('tools.connectorPolicy.options.onlyAdmins'), value: 'admins_only' },+ ]}+ onChange={(value) => void handleChange(value as WorkspaceConnectorMemberManage)}+ />+ </Flexbox>+ );+});++ConnectorManagePolicy.displayName = 'ConnectorManagePolicy';++export default ConnectorManagePolicy;diff --git a/src/features/Settings/skill/features/ConnectorRowFeedback.tsx b/src/features/Settings/skill/features/ConnectorRowFeedback.tsxnew file mode 100644index 00000000000..247f98bc683--- /dev/null+++ b/src/features/Settings/skill/features/ConnectorRowFeedback.tsx@@ -0,0 +1,108 @@+'use client';++import { Button, copyToClipboard, Flexbox, Icon, toast, Tooltip } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';+import { SquareArrowOutUpRight } from 'lucide-react';+import { memo, type ReactNode } from 'react';+import { useTranslation } from 'react-i18next';++import ConnectorActionErrorText from '@/features/Connectors/ConnectorActionErrorText';+import { type ConnectorActionError } from '@/utils/connectorActionError';++const styles = stylex.create({+ tooltipAnchor: {+ display: 'inline-flex',+ },+});++interface ConnectorRowDescriptionProps {+ /**+ * The workspace restricted connectors to owners and admins: offer "Ask an+ * admin", so the member knows the integration exists and whom to ask.+ */+ askAdmin?: boolean;+ error?: ConnectorActionError;+ name: string;+}++/**+ * Second line of a connector row: the "Ask an admin" entry and the last failure+ * kept in place. Returns `undefined` when there is nothing to show, so the row+ * keeps its single-line layout.+ */+export const renderConnectorRowDescription = ({+ askAdmin,+ error,+ name,+}: ConnectorRowDescriptionProps): ReactNode => {+ if (!askAdmin && !error) return undefined;++ return (+ <Flexbox gap={2}>+ {askAdmin && <AskAdminButton name={name} />}+ {error && <ConnectorActionErrorText error={error} name={name} />}+ </Flexbox>+ );+};++interface AskAdminButtonProps {+ name: string;+ /** `link` fits the row's second line; `primary` stands next to a full-size Connect. */+ variant?: 'link' | 'primary';+}++/** Copies a ready-to-send request for a workspace owner or admin to connect `name`. */+export const AskAdminButton = memo<AskAdminButtonProps>(({ name, variant = 'link' }) => {+ const { t } = useTranslation('setting');++ const handleAskAdmin = async () => {+ await copyToClipboard(+ t('tools.connectorFeedback.askAdminMessage', { name, url: window.location.href }),+ );+ toast.success(t('tools.connectorFeedback.askAdminCopied'));+ };++ return (+ <Button+ size={'small'}+ style={variant === 'link' ? { flex: 'none', height: 'auto', padding: 0 } : undefined}+ type={variant}+ onClick={handleAskAdmin}+ >+ {t('tools.connectorFeedback.askAdmin')}+ </Button>+ );+});++AskAdminButton.displayName = 'AskAdminButton';++interface DisabledConnectProps {+ size?: 'small' | 'middle';+}++/**+ * The Connect button a member restricted by the workspace policy sees: still+ * visible (so the integration reads as supported) but disabled, with a tooltip+ * saying who can change it.+ */+export const DisabledConnect = memo<DisabledConnectProps>(({ size = 'small' }) => {+ const { t } = useTranslation('setting');++ return (+ <Tooltip title={t('tools.connectorFeedback.manageOnly')}>+ {/* Disabled buttons swallow hover events; the wrapper anchors the tooltip. */}+ <span {...stylex.props(styles.tooltipAnchor)}>+ <Button+ disabled+ icon={<Icon icon={SquareArrowOutUpRight} />}+ size={size}+ type={size === 'small' ? 'text' : 'default'}+ >+ {t('tools.composio.connect')}+ </Button>+ </span>+ </Tooltip>+ );+});++DisabledConnect.displayName = 'DisabledConnect';diff --git a/src/features/Settings/skill/features/LeftPanel.tsx b/src/features/Settings/skill/features/LeftPanel.tsxindex 22566889974..f1dc57aa986 100644--- a/src/features/Settings/skill/features/LeftPanel.tsx+++ b/src/features/Settings/skill/features/LeftPanel.tsx@@ -1,6 +1,14 @@'use client';-import { Button, createStaticStyles, DropdownMenu, Flexbox, Icon, Text } from '@lobehub/ui';+import {+ Button,+ createStaticStyles,+ DropdownMenu,+ Flexbox,+ Icon,+ Text,+ Tooltip,+} from '@lobehub/ui';import { GithubIcon } from '@lobehub/ui/icons';import { FileArchive, Grid2x2Plus, Link, Store } from 'lucide-react';import { memo, useCallback, useState } from 'react';@@ -11,7 +19,9 @@ import { createSkillStoreModal } from '@/features/SkillStore';import { openImportFromGithubModal } from '@/features/SkillStore/SkillList/ImportFromGithubModal';import { openImportFromUrlModal } from '@/features/SkillStore/SkillList/ImportFromUrlModal';import { openUploadSkillModal } from '@/features/SkillStore/SkillList/UploadSkillModal';+import { useConnectorManageable } from '@/hooks/useConnectorManagePolicy';+import ConnectorManagePolicy from './ConnectorManagePolicy';import { type ToolDetailType } from './SkillDetail';import SkillList, { type SkillViewMode } from './SkillList';@@ -42,6 +52,9 @@ const styles = createStaticStyles(({ css, cssVar }) => ({min-width: 260px;border-inline-end: 1px solid ${cssVar.colorBorderSecondary};`,+ tooltipAnchor: css`+ display: inline-flex;+ `,}));interface LeftPanelProps {@@ -63,6 +76,8 @@ const LeftPanel = memo<LeftPanelProps>(}, []);const isConnectorView = viewMode === 'connector';+ // Adding a workspace connector follows the same member policy as editing one.+ const { canManage: canAddConnector, isPending: isPolicyPending } = useConnectorManageable();return (<>@@ -80,15 +95,26 @@ const LeftPanel = memo<LeftPanelProps>(<div style={{ display: 'flex', gap: 6 }} onClick={(e) => e.stopPropagation()}>{isConnectorView ? (// Connector view: single action to add a custom OAuth connector.- <Button- icon={Grid2x2Plus}- size="small"- title={t('connector.add.title', {- defaultValue: 'Add Custom Connector',- ns: 'tool',- })}- onClick={() => setShowAddConnector(true)}- />+ <Tooltip+ title={+ canAddConnector || isPolicyPending+ ? t('connector.add.title', {+ defaultValue: 'Add Custom Connector',+ ns: 'tool',+ })+ : t('tools.connectorFeedback.manageOnly')+ }+ >+ {/* Disabled buttons swallow hover events; the wrapper anchors the tooltip. */}+ <span className={styles.tooltipAnchor}>+ <Button+ disabled={!canAddConnector}+ icon={Grid2x2Plus}+ size="small"+ onClick={() => setShowAddConnector(true)}+ />+ </span>+ </Tooltip>) : (// Skill view: import a skill from a URL, GitHub, or a zip upload.<DropdownMenu@@ -143,6 +169,8 @@ const LeftPanel = memo<LeftPanelProps>(</div></div>+ {isConnectorView && <ConnectorManagePolicy />}+<div className={styles.body}><SkillListselectedIdentifier={selectedIdentifier}diff --git a/src/features/Settings/skill/features/LobehubSkillItem.tsx b/src/features/Settings/skill/features/LobehubSkillItem.tsxindex f4eaee5715f..756eb0ba3f7 100644--- a/src/features/Settings/skill/features/LobehubSkillItem.tsx+++ b/src/features/Settings/skill/features/LobehubSkillItem.tsx@@ -21,9 +21,13 @@ import NavItem from '@/features/NavPanel/components/NavItem';import { createLobehubSkillDetailModal } from '@/features/SkillStore/SkillDetail';import { usePermission } from '@/hooks/usePermission';import { useToolStore } from '@/store/tool';+import { lobehubSkillStoreSelectors } from '@/store/tool/slices/lobehubSkillStore/selectors';import { type LobehubSkillServer } from '@/store/tool/slices/lobehubSkillStore/types';import { LobehubSkillStatus } from '@/store/tool/slices/lobehubSkillStore/types';+import { toConnectorActionError } from '@/utils/connectorActionError';+import { renderConnectorRowDescription } from './ConnectorRowFeedback';+import { isSettledByConnection } from './connectorRowState';import { styles } from './style';const POLL_INTERVAL_MS = 1000;@@ -53,6 +57,19 @@ const LobehubSkillItem = memo<LobehubSkillItemProps>(const checkStatus = useToolStore((s) => s.checkLobehubSkillStatus);const revokeConnect = useToolStore((s) => s.revokeLobehubSkill);const getAuthorizeUrl = useToolStore((s) => s.getLobehubSkillAuthorizeUrl);+ const setActionError = useToolStore((s) => s.setLobehubSkillError);+ const actionError = useToolStore(lobehubSkillStoreSelectors.getServerError(provider.id));++ // The OAuth window is gone and the provider is still not connected: keep the+ // reason on the row, the user may not have noticed the popup failed.+ const reportIfNotConnected = useCallback(() => {+ const latest = lobehubSkillStoreSelectors.getServerByIdentifier(provider.id)(+ useToolStore.getState(),+ );+ if (latest?.status !== LobehubSkillStatus.CONNECTED) {+ setActionError(provider.id, { action: 'connect', code: 'AUTH_INCOMPLETE' });+ }+ }, [provider.id, setActionError]);const cleanup = useCallback(() => {if (windowCheckIntervalRef.current) {@@ -100,8 +117,9 @@ const LobehubSkillItem = memo<LobehubSkillItemProps>(pollIntervalRef.current = null;}setIsWaitingAuth(false);+ reportIfNotConnected();}, POLL_TIMEOUT_MS);- }, [checkStatus, provider.id]);+ }, [checkStatus, provider.id, reportIfNotConnected]);const startWindowMonitor = useCallback((oauthWindow: Window) => {@@ -115,6 +133,7 @@ const LobehubSkillItem = memo<LobehubSkillItemProps>(oauthWindowRef.current = null;await checkStatus(provider.id);setIsWaitingAuth(false);+ reportIfNotConnected();}} catch {console.info(@@ -128,7 +147,7 @@ const LobehubSkillItem = memo<LobehubSkillItemProps>(}}, 500);},- [checkStatus, provider.id, startFallbackPolling],+ [checkStatus, provider.id, reportIfNotConnected, startFallbackPolling],);const openOAuthWindow = useCallback(@@ -169,6 +188,7 @@ const LobehubSkillItem = memo<LobehubSkillItemProps>(if (server?.isConnected) return;setIsConnecting(true);+ setActionError(provider.id, undefined);try {// Skip redirectUri on desktop (app:// protocol) since the system browser can't navigate to itconst redirectUri = window.location.protocol.startsWith('http')@@ -178,6 +198,7 @@ const LobehubSkillItem = memo<LobehubSkillItemProps>(openOAuthWindow(authorizeUrl);} catch (error) {console.error('[LobehubSkill] Failed to get authorize URL:', error);+ setActionError(provider.id, toConnectorActionError('connect', error));} finally {setIsConnecting(false);}@@ -284,6 +305,14 @@ const LobehubSkillItem = memo<LobehubSkillItemProps>(};const isConnected = server?.status === LobehubSkillStatus.CONNECTED;+ const description = renderConnectorRowDescription({ error: actionError, name: provider.label });++ // Becoming connected settles an earlier connect failure; a failed disconnect+ // leaves the row connected on purpose, so its reason stays.+ const hasStaleConnectError = isSettledByConnection(isConnected, actionError);+ useEffect(() => {+ if (hasStaleConnectError) setActionError(provider.id, undefined);+ }, [hasStaleConnectError, provider.id, setActionError]);// Compact connect/status control for the left-list (NavItem) row. Mirrors the// ChatInput skills dropdown UX: connected → green check; otherwise a Connect@@ -326,6 +355,7 @@ const LobehubSkillItem = memo<LobehubSkillItemProps>(return (<NavItemactive={isSelected}+ description={description}extra={renderNavExtra()}icon={renderNavIcon}title={provider.label}diff --git a/src/features/Settings/skill/features/connectorRowState.test.ts b/src/features/Settings/skill/features/connectorRowState.test.tsnew file mode 100644index 00000000000..3a6f881be73--- /dev/null+++ b/src/features/Settings/skill/features/connectorRowState.test.ts@@ -0,0 +1,68 @@+import { renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { isSettledByConnection, useConnectorManageGate } from './connectorRowState';++const mocks = vi.hoisted(() => ({+ connectors: [] as Array<{ identifier: string; userId?: string }>,+ policy: undefined as+ { canEditPolicy: boolean; canManage: boolean; memberManage: string } | undefined,+}));++vi.mock('@/store/tool', () => ({+ useToolStore: <T>(selector: (state: { connectors: typeof mocks.connectors }) => T): T =>+ selector({ connectors: mocks.connectors }),+}));++vi.mock('@/libs/swr', () => ({+ mutate: vi.fn(),+ useClientDataSWR: () => ({ data: mocks.policy }),+}));++vi.mock('@/hooks/useResourceManageable', () => ({+ useResourceManageable: (userId?: string | null) => !userId || userId === 'me',+}));++describe('useConnectorManageGate', () => {+ beforeEach(() => {+ mocks.connectors = [];+ mocks.policy = undefined;+ });++ const gate = () => renderHook(() => useConnectorManageGate('gmail')).result.current;++ it('lets a member co-maintain a connection another member created by default', () => {+ mocks.connectors = [{ identifier: 'gmail', userId: 'arvin' }];+ mocks.policy = { canEditPolicy: false, canManage: true, memberManage: 'all_members' };+ expect(gate()).toEqual({ access: 'allowed' });+ });++ it('gates a member out once admins restricted connector management', () => {+ mocks.connectors = [{ identifier: 'gmail', userId: 'me' }];+ mocks.policy = { canEditPolicy: false, canManage: false, memberManage: 'admins_only' };+ expect(gate()).toEqual({ access: 'restricted' });++ // Not connected yet: Connect is gated too, the row itself stays.+ mocks.connectors = [];+ expect(gate()).toEqual({ access: 'restricted' });+ });++ it('keeps Connect disabled, but not restricted, while the policy is loading', () => {+ // Never clickable before the server says it is allowed.+ expect(gate()).toEqual({ access: 'pending' });+ });+});++describe('isSettledByConnection', () => {+ it('clears a connect failure once the connection is active', () => {+ expect(isSettledByConnection(true, { action: 'connect', code: 'AUTH_INCOMPLETE' })).toBe(true);+ });++ it('keeps a failed remove on an active row', () => {+ expect(isSettledByConnection(true, { action: 'remove', code: 'NETWORK' })).toBe(false);+ });++ it('keeps any failure while not connected', () => {+ expect(isSettledByConnection(false, { action: 'connect', code: 'FORBIDDEN' })).toBe(false);+ });+});diff --git a/src/features/Settings/skill/features/connectorRowState.ts b/src/features/Settings/skill/features/connectorRowState.tsnew file mode 100644index 00000000000..9efc059b4f3--- /dev/null+++ b/src/features/Settings/skill/features/connectorRowState.ts@@ -0,0 +1,30 @@+import { useConnectorManageable } from '@/hooks/useConnectorManagePolicy';+import { useToolStore } from '@/store/tool';+import { connectorSelectors } from '@/store/tool/slices/connector';+import { type ConnectorActionError } from '@/utils/connectorActionError';++/**+ * Whether a row's stored failure is settled by the connection being active: an+ * earlier connect failure is (e.g. a slow OAuth that later succeeded), but a+ * failed remove leaves the row active on purpose, so its reason must stay.+ */+export const isSettledByConnection = (+ isConnected: boolean,+ error: ConnectorActionError | undefined,+): boolean => isConnected && error?.action === 'connect';++/**+ * Row-level manage gate of a workspace-shared connection, mirroring the server's+ * `assertComposioRowManageable`: members co-maintain shared connectors unless a+ * workspace owner or admin restricted it, in which case the row stays visible+ * with a disabled Connect and an "Ask an admin" entry instead of a button that+ * fails with a 403. While the policy loads (`pending`) controls stay disabled.+ */+export const useConnectorManageGate = (+ identifier: string,+): { access: 'allowed' | 'pending' | 'restricted' } => {+ const connector = useToolStore(connectorSelectors.connectorByIdentifier(identifier));+ const { canManage, isPending } = useConnectorManageable(connector);++ return { access: isPending ? 'pending' : canManage ? 'allowed' : 'restricted' };+};diff --git a/src/hooks/useConnectorManagePolicy.test.ts b/src/hooks/useConnectorManagePolicy.test.tsnew file mode 100644index 00000000000..26baa88901f--- /dev/null+++ b/src/hooks/useConnectorManagePolicy.test.ts@@ -0,0 +1,80 @@+import { renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useConnectorManageable } from './useConnectorManagePolicy';++const mocks = vi.hoisted(() => ({+ error: undefined as Error | undefined,+ policy: undefined as+ { canEditPolicy: boolean; canManage: boolean; memberManage: string } | undefined,+}));++vi.mock('@/libs/swr', () => ({+ mutate: vi.fn(),+ useClientDataSWR: () => ({ data: mocks.policy, error: mocks.error }),+}));++vi.mock('@/hooks/useResourceManageable', () => ({+ useResourceManageable: (userId?: string | null) => !userId || userId === 'me',+}));++const manageable = (connector?: { agentId?: string | null; userId?: string | null }) =>+ renderHook(() => useConnectorManageable(connector)).result.current;++describe('useConnectorManageable', () => {+ beforeEach(() => {+ mocks.error = undefined;+ mocks.policy = { canEditPolicy: false, canManage: true, memberManage: 'all_members' };+ });++ it('keeps actions disabled, without a permission reason, until the policy loads', () => {+ mocks.policy = undefined;++ expect(manageable({ userId: 'me' })).toEqual({+ canManage: false,+ canManageCredentials: false,+ isPending: true,+ restrictedByPolicy: false,+ });+ });++ it('falls back to the default when the policy cannot be read', () => {+ mocks.policy = undefined;+ mocks.error = new Error('network');++ expect(manageable({ userId: 'me' })).toMatchObject({ canManage: true, isPending: false });+ });++ it("lets members maintain a shared row but keeps another member's credentials out", () => {+ expect(manageable({ userId: 'arvin' })).toEqual({+ canManage: true,+ canManageCredentials: false,+ isPending: false,+ restrictedByPolicy: false,+ });+ expect(manageable({ userId: 'me' })).toEqual({+ canManage: true,+ canManageCredentials: true,+ isPending: false,+ restrictedByPolicy: false,+ });+ });++ it('blocks every write on shared rows when the policy restricts members', () => {+ mocks.policy = { canEditPolicy: false, canManage: false, memberManage: 'admins_only' };++ expect(manageable({ userId: 'me' })).toEqual({+ canManage: false,+ canManageCredentials: false,+ isPending: false,+ restrictedByPolicy: true,+ });+ });++ it('keeps the creator rule for agent-scoped rows regardless of the policy', () => {+ mocks.policy = { canEditPolicy: false, canManage: false, memberManage: 'admins_only' };++ expect(manageable({ agentId: 'a1', userId: 'me' })).toMatchObject({ canManage: true });+ expect(manageable({ agentId: 'a1', userId: 'arvin' })).toMatchObject({ canManage: false });+ });+});diff --git a/src/hooks/useConnectorManagePolicy.ts b/src/hooks/useConnectorManagePolicy.tsnew file mode 100644index 00000000000..d2014eb86f8--- /dev/null+++ b/src/hooks/useConnectorManagePolicy.ts@@ -0,0 +1,72 @@+import { useResourceManageable } from '@/hooks/useResourceManageable';+import { useClientDataSWR } from '@/libs/swr';+import {+ CONNECTOR_MANAGE_POLICY_SWR_KEY,+ type ConnectorManagePolicy,+ getConnectorManagePolicy,+} from '@/services/connectorManagePolicy';++export const useConnectorManagePolicy = () =>+ useClientDataSWR<ConnectorManagePolicy>(+ [CONNECTOR_MANAGE_POLICY_SWR_KEY],+ getConnectorManagePolicy,+ );++export interface ConnectorManageable {+ /** Maintenance writes: connect, re-authorize, sync, reset permissions, remove. */+ canManage: boolean;+ /**+ * Writes that reach the stored credentials (edit form, agent binding). Shared+ * connectors are co-maintained, but another member's secrets stay with their+ * creator and the workspace owner.+ */+ canManageCredentials: boolean;+ /**+ * The policy has not loaded yet: actions stay disabled without a permission+ * hint, so a button is never clickable before we know the server allows it.+ */+ isPending: boolean;+ /** The workspace policy, not the row's creator, is what blocks the viewer. */+ restrictedByPolicy: boolean;+}++/**+ * Client mirror of the server's connector manage gates+ * (`assertConnectorMaintainable` / `assertConnectorCredentialsManageable`).+ * Actions are enabled only once the server-computed policy says they are+ * allowed; a restricted viewer gets disabled controls with the reason on hover.+ */+export const useConnectorManageable = (connector?: {+ agentId?: string | null;+ userId?: string | null;+}): ConnectorManageable => {+ const { data: policy, error } = useConnectorManagePolicy();+ const isCreatorOrOwner = useResourceManageable(connector?.userId);++ // Agent-scoped rows belong to that agent's setup and keep the creator rule.+ if (connector?.agentId)+ return {+ canManage: isCreatorOrOwner,+ canManageCredentials: isCreatorOrOwner,+ isPending: false,+ restrictedByPolicy: false,+ };++ if (!policy && !error)+ return {+ canManage: false,+ canManageCredentials: false,+ isPending: true,+ restrictedByPolicy: false,+ };++ // A failed policy read must not lock every connector: fall back to the+ // default and let the server decide (a 403 refetches the policy).+ const canManage = policy?.canManage ?? true;+ return {+ canManage,+ canManageCredentials: canManage && isCreatorOrOwner,+ isPending: false,+ restrictedByPolicy: !canManage,+ };+};diff --git a/src/services/connectorManagePolicy.ts b/src/services/connectorManagePolicy.tsnew file mode 100644index 00000000000..868cbfc9b06--- /dev/null+++ b/src/services/connectorManagePolicy.ts@@ -0,0 +1,27 @@+import { type WorkspaceConnectorMemberManage } from '@lobechat/types';++import { mutate } from '@/libs/swr';+import { lambdaClient } from '@/libs/trpc/client';++/** Workspace-dimensioned by `useClientDataSWR`, so each workspace keeps its own entry. */+export const CONNECTOR_MANAGE_POLICY_SWR_KEY = 'connector/managePolicy';++export interface ConnectorManagePolicy {+ /** Owners and admins choose whether members may maintain shared connectors. */+ canEditPolicy: boolean;+ /** Whether the viewer may connect, re-authorize, sync or remove shared connectors. */+ canManage: boolean;+ memberManage: WorkspaceConnectorMemberManage;+}++export const getConnectorManagePolicy = (): Promise<ConnectorManagePolicy> =>+ lambdaClient.connector.getManagePolicy.query();++/** Refetch the policy, e.g. after a 403 shows the cached one is stale. */+export const refreshConnectorManagePolicy = () =>+ mutate((key: unknown) => Array.isArray(key) && key[0] === CONNECTOR_MANAGE_POLICY_SWR_KEY);++export const updateConnectorManagePolicy = async (memberManage: WorkspaceConnectorMemberManage) => {+ await lambdaClient.connector.updateManagePolicy.mutate({ memberManage });+ await refreshConnectorManagePolicy();+};diff --git a/src/store/tool/slices/composioStore/action.ts b/src/store/tool/slices/composioStore/action.tsindex 2e7b02babba..a372c7c585b 100644--- a/src/store/tool/slices/composioStore/action.ts+++ b/src/store/tool/slices/composioStore/action.ts@@ -10,7 +10,9 @@ import {type ReplicaSyncResult,} from '@/libs/replica';import { lambdaClient, toolsClient } from '@/libs/trpc/client';+import { refreshConnectorManagePolicy } from '@/services/connectorManagePolicy';import { type StoreSetter } from '@/store/types';+import { type ConnectorActionError, toConnectorActionError } from '@/utils/connectorActionError';import { setNamespace } from '@/utils/storeDebug';import { type ToolStore } from '../../store';@@ -209,6 +211,7 @@ export class ComposioStoreActionImpl {this.#set(produce((draft: ComposioStoreState) => {draft.loadingComposioServerIds.add(identifier);+ delete draft.composioServerErrors[identifier];}),false,n('createComposioConnection/start'),@@ -276,9 +279,16 @@ export class ComposioStoreActionImpl {} catch (error) {console.error('[Composio] Failed to create connection:', error);+ const actionError = toConnectorActionError('connect', error);+ // A permission rejection is not a failure to explain: the row switches to+ // its disabled state once the refetched policy arrives.+ const rejected = this.#settlePermissionRejection(actionError);this.#set(produce((draft: ComposioStoreState) => {draft.loadingComposioServerIds.delete(identifier);+ // Kept on the row, so the failure stays visible after any toast is gone.+ if (cacheScope.get() === scope && !rejected)+ draft.composioServerErrors[identifier] = { ...actionError, scope };}),false,n('createComposioConnection/error'),@@ -368,6 +378,7 @@ export class ComposioStoreActionImpl {this.#markLocalWrite(scope);clearLoading('refreshComposioConnectionStatus/success');+ this.setComposioServerError(identifier, undefined);try {await lambdaClient.composio.updateComposioPlugin.mutate({@@ -426,6 +437,10 @@ export class ComposioStoreActionImpl {});} catch (error) {console.error('[Composio] Failed to clean up stale connection:', error);+ // A permission rejection here means minting a new link is rejected too:+ // stop, and let the refetched policy disable the row.+ if (this.#settlePermissionRejection(toConnectorActionError('connect', error)))+ return undefined;}// Identity switched during the cleanup: minting now would create (and@@ -441,20 +456,29 @@ export class ComposioStoreActionImpl {});};- removeComposioConnection = async (identifier: string): Promise<void> => {- const { composioServers } = this.#get();- const server = composioServers.find((s) => s.identifier === identifier);-- // Drop the row locally first — the server delete stays best-effort, so a- // failure never resurrects the row the user just deleted. Recording the- // removal also cancels a pending add of the same identifier: the row was- // created but never echoed, so leaving it in `added` would re-append it the- // moment a response clears `removed`, resurrecting the deleted row for the- // rest of the session.+ /**+ * Drop a connection from the local list after it was removed on the server+ * by another path (e.g. uninstalling it from the connector detail panel), so+ * its row stops showing as connected. Recording the removal also cancels a+ * pending add of the same identifier: the row was created but never echoed,+ * so leaving it in `added` would re-append it the moment a response clears+ * `removed`, resurrecting the deleted row for the rest of the session.+ */+ forgetComposioConnection = (identifier: string): void => {+ this.setComposioServerError(identifier, undefined);this.#localIntent().added.delete(identifier);this.#localIntent().removed.add(identifier);this.#servers.remove(identifier);this.#markLocalWrite();+ };++ removeComposioConnection = async (identifier: string): Promise<void> => {+ const { composioServers } = this.#get();+ const server = composioServers.find((s) => s.identifier === identifier);+ const scope = cacheScope.get();++ // Drop the row locally first so the delete shows at once.+ this.forgetComposioConnection(identifier);if (server) {try {@@ -464,10 +488,50 @@ export class ComposioStoreActionImpl {});} catch (error) {console.error('[Composio] Failed to delete connection:', error);+ // The server already tolerates a missing remote account, so a rejected+ // call (permission, network) means the connection still exists. Put the+ // row back with the reason, so the user sees it failed and can retry.+ if (cacheScope.get() !== scope) return;+ this.#localIntent().removed.delete(identifier);+ this.#connections.update(COMPOSIO_SERVERS_KEY, (servers) => {+ const list = servers ?? [];+ return list.some((s) => s.identifier === identifier) ? list : [...list, server];+ });+ this.#markLocalWrite();+ const actionError = toConnectorActionError('remove', error);+ if (!this.#settlePermissionRejection(actionError))+ this.setComposioServerError(identifier, actionError);}}};+ /**+ * A 403 means the cached connector policy is stale (an admin restricted+ * connectors after the page loaded). Refetch it so the row turns into the+ * disabled state with its hover reason, instead of a red "only admins can+ * change this" under a button that looked clickable. Returns whether the+ * error was such a rejection.+ */+ #settlePermissionRejection = (error: ConnectorActionError): boolean => {+ if (error.code !== 'FORBIDDEN') return false;+ void refreshConnectorManagePolicy();+ return true;+ };++ /** Record (or clear, with `undefined`) the last failed write of a connection row. */+ setComposioServerError = (identifier: string, error: ConnectorActionError | undefined): void => {+ if (!error && !this.#get().composioServerErrors[identifier]) return;++ this.#set(+ produce((draft: ComposioStoreState) => {+ if (error) draft.composioServerErrors[identifier] = { ...error, scope: cacheScope.get() };+ else delete draft.composioServerErrors[identifier];+ }),+ false,+ n('setComposioServerError'),+ );+ };+/*** Fetch orchestration only; read the tools through `composioAppToolsMap[appSlug]`.* Deliberately does not subscribe to the store here — the composio slice isdiff --git a/src/store/tool/slices/composioStore/actionError.test.ts b/src/store/tool/slices/composioStore/actionError.test.tsnew file mode 100644index 00000000000..14765335987--- /dev/null+++ b/src/store/tool/slices/composioStore/actionError.test.ts@@ -0,0 +1,236 @@+/**+ * @vitest-environment happy-dom+ *+ * A failed connect / re-authorize / remove keeps its reason on the row+ * (`composioServerErrors`), so the settings list can explain it in place+ * instead of a toast that is gone by the time the OAuth popup closes.+ */+import { randomUUID } from 'node:crypto';++import { act, cleanup, renderHook, waitFor } from '@testing-library/react';+import type { PropsWithChildren } from 'react';+import { createElement, useEffect } from 'react';+import { SWRConfig, useSWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { cacheScope } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';++import { useToolStore } from '../../store';+import { initialComposioStoreState } from './initialState';+import { composioServersResource } from './projection';+import { composioStoreSelectors } from './selectors';++const mocks = vi.hoisted(() => ({+ refreshConnectorManagePolicy: vi.fn(),+ createConnection: vi.fn(),+ deleteConnection: vi.fn(),+ getComposioPlugins: vi.fn(),+ getConnection: vi.fn(),+ listActions: vi.fn(),+ updateComposioPlugin: vi.fn(),+}));++vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: {+ composio: {+ createConnection: { mutate: mocks.createConnection },+ deleteConnection: { mutate: mocks.deleteConnection },+ getComposioPlugins: { query: mocks.getComposioPlugins },+ getConnection: { query: mocks.getConnection },+ updateComposioPlugin: { mutate: mocks.updateComposioPlugin },+ },+ },+ toolsClient: { composio: { listActions: { query: mocks.listActions } } },+}));++vi.mock('@/services/connectorManagePolicy', () => ({+ refreshConnectorManagePolicy: mocks.refreshConnectorManagePolicy,+}));++const MutateBridge = () => {+ const { mutate } = useSWRConfig();+ useEffect(() => setScopedMutate(mutate), [mutate]);+ return null;+};++const wrapper = ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ { value: { dedupingInterval: 0, provider: () => new Map() } },+ createElement(MutateBridge),+ children,+ );++const forbidden = () =>+ Object.assign(new Error('Only the creator or a workspace owner can modify this connector'), {+ data: { code: 'FORBIDDEN', httpStatus: 403 },+ });++const gmailPlugin = (status = 'PENDING') => ({+ customParams: {+ composio: {+ appSlug: 'GMAIL',+ authConfigId: 'ac_gmail',+ connectedAccountId: 'ca_gmail',+ status,+ },+ },+ identifier: 'gmail',+ manifest: { api: [] },+});++const SERVERS_STORAGE_KEY = composioServersResource.storageKey({} as Record<string, never>);+const errorOf = (identifier: string) =>+ composioStoreSelectors.getServerError(identifier)(useToolStore.getState());++describe('composio connection errors', () => {+ let scope = '';++ beforeEach(() => {+ scope = `composio-error-${randomUUID()}:ws`;+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ vi.spyOn(console, 'error').mockImplementation(() => {});+ act(() => useToolStore.setState(initialComposioStoreState));+ });++ afterEach(async () => {+ cleanup();+ await composioServersResource.storage!.remove({ queryKey: SERVERS_STORAGE_KEY, scope });+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });++ const loadGmail = async (status?: string) => {+ mocks.getComposioPlugins.mockResolvedValue([gmailPlugin(status)]);+ renderHook(() => useToolStore((s) => s.useFetchUserComposioConnections)(true), { wrapper });+ await waitFor(() => expect(useToolStore.getState().composioServers).toHaveLength(1));+ };++ it('keeps a failed connect on the row instead of swallowing it', async () => {+ mocks.createConnection.mockRejectedValue(new TypeError('Failed to fetch'));++ await act(async () => {+ await useToolStore+ .getState()+ .createComposioConnection({ appSlug: 'GMAIL', identifier: 'gmail', label: 'Gmail' });+ });++ expect(errorOf('gmail')).toMatchObject({ action: 'connect', code: 'NETWORK' });+ expect(mocks.refreshConnectorManagePolicy).not.toHaveBeenCalled();+ });++ it('turns a permission rejection into a policy refetch, not a red reason', async () => {+ // The button only looked usable because the cached policy was stale; the+ // refetched policy disables the row with its hover reason instead.+ mocks.createConnection.mockRejectedValue(forbidden());++ await act(async () => {+ await useToolStore+ .getState()+ .createComposioConnection({ appSlug: 'GMAIL', identifier: 'gmail', label: 'Gmail' });+ });++ expect(errorOf('gmail')).toBeUndefined();+ expect(mocks.refreshConnectorManagePolicy).toHaveBeenCalledTimes(1);+ });++ it('does not show one scope’s failure on the same row of another scope', async () => {+ mocks.createConnection.mockRejectedValue(new TypeError('Failed to fetch'));++ await act(async () => {+ await useToolStore+ .getState()+ .createComposioConnection({ appSlug: 'GMAIL', identifier: 'gmail', label: 'Gmail' });+ });+ expect(errorOf('gmail')).toBeDefined();++ const workspaceScope = scope;+ scope = `composio-error-${randomUUID()}:personal`;+ expect(errorOf('gmail')).toBeUndefined();++ scope = workspaceScope;+ expect(errorOf('gmail')).toMatchObject({ code: 'NETWORK' });+ });++ it('clears the previous failure when a new connect starts and succeeds', async () => {+ act(() => useToolStore.getState().setComposioServerError('gmail', { action: 'connect' }));+ mocks.createConnection.mockResolvedValue({+ authConfigId: 'ac_gmail',+ connectedAccountId: 'ca_gmail',+ identifier: 'gmail',+ redirectUrl: 'https://composio.dev/redirect',+ });++ await act(async () => {+ await useToolStore+ .getState()+ .createComposioConnection({ appSlug: 'GMAIL', identifier: 'gmail', label: 'Gmail' });+ });++ expect(errorOf('gmail')).toBeUndefined();+ });++ it('stops re-authorizing when the cleanup is rejected for permission', async () => {+ await loadGmail();+ mocks.deleteConnection.mockRejectedValue(forbidden());++ await act(async () => {+ await useToolStore.getState().reauthorizeComposioConnection('gmail');+ });++ expect(mocks.createConnection).not.toHaveBeenCalled();+ expect(errorOf('gmail')).toBeUndefined();+ expect(mocks.refreshConnectorManagePolicy).toHaveBeenCalledTimes(1);+ });++ it('puts the row back without a red reason when the delete is rejected for permission', async () => {+ await loadGmail('ACTIVE');+ mocks.deleteConnection.mockRejectedValue(forbidden());++ await act(async () => {+ await useToolStore.getState().removeComposioConnection('gmail');+ });++ expect(useToolStore.getState().composioServers.map((s) => s.identifier)).toEqual(['gmail']);+ expect(errorOf('gmail')).toBeUndefined();+ expect(mocks.refreshConnectorManagePolicy).toHaveBeenCalledTimes(1);+ });++ it('puts the row back with the reason when the delete is rejected', async () => {+ await loadGmail('ACTIVE');+ mocks.deleteConnection.mockRejectedValue(new TypeError('Failed to fetch'));++ await act(async () => {+ await useToolStore.getState().removeComposioConnection('gmail');+ });++ expect(useToolStore.getState().composioServers.map((s) => s.identifier)).toEqual(['gmail']);+ expect(errorOf('gmail')).toMatchObject({ action: 'remove', code: 'NETWORK' });+ });++ it('removes the row without an error when the delete succeeds', async () => {+ await loadGmail('ACTIVE');+ mocks.deleteConnection.mockResolvedValue({ success: true });++ await act(async () => {+ await useToolStore.getState().removeComposioConnection('gmail');+ });++ expect(useToolStore.getState().composioServers).toEqual([]);+ expect(errorOf('gmail')).toBeUndefined();+ });++ it('drops a connection removed elsewhere (detail-panel uninstall) from the list', async () => {+ await loadGmail('ACTIVE');+ act(() => useToolStore.getState().setComposioServerError('gmail', { action: 'connect' }));++ act(() => useToolStore.getState().forgetComposioConnection('gmail'));++ expect(useToolStore.getState().composioServers).toEqual([]);+ expect(errorOf('gmail')).toBeUndefined();+ expect(mocks.deleteConnection).not.toHaveBeenCalled();+ });+});diff --git a/src/store/tool/slices/composioStore/initialState.ts b/src/store/tool/slices/composioStore/initialState.tsindex ab680d826a7..18123b58b7d 100644--- a/src/store/tool/slices/composioStore/initialState.ts+++ b/src/store/tool/slices/composioStore/initialState.ts@@ -1,4 +1,5 @@import { createReplicaState, type ReplicaState } from '@/libs/replica';+import { type ScopedConnectorActionError } from '@/utils/connectorActionError';import { type ComposioServer, type ComposioTool } from './types';@@ -9,6 +10,11 @@ export interface ComposioStoreState {composioAppToolsReplica: ReplicaState<ComposioTool[]>;/** In-flight tool calls, keyed `identifier:toolSlug` (local UI state; never persisted). */composioExecutingToolIds: Set<string>;+ /**+ * Last failed connect / remove per connection `identifier`, so the settings+ * row can show why it failed in place (local UI state; never persisted).+ */+ composioServerErrors: Record<string, ScopedConnectorActionError>;/** The user's Composio connections — the view of the `composioServers` replica. */composioServers: ComposioServer[];/** Replica bookkeeping of `composioServers`. */@@ -26,6 +32,7 @@ export interface ComposioStoreState {export const initialComposioStoreState: ComposioStoreState = {composioExecutingToolIds: new Set(),composioAppToolsMap: {},+ composioServerErrors: {},composioAppToolsReplica: createReplicaState(),composioServers: [],composioServersReplica: createReplicaState(),diff --git a/src/store/tool/slices/composioStore/selectors.ts b/src/store/tool/slices/composioStore/selectors.tsindex 1c0052413ac..d2c94872001 100644--- a/src/store/tool/slices/composioStore/selectors.ts+++ b/src/store/tool/slices/composioStore/selectors.ts@@ -1,3 +1,6 @@+import { cacheScope } from '@/libs/replica';+import { errorInScope } from '@/utils/connectorActionError';+import { type ToolStore } from '../../store';import { type ComposioServer, ComposioServerStatus } from './types';@@ -25,6 +28,9 @@ export const composioStoreSelectors = {(server) => server.status === ComposioServerStatus.PENDING_AUTH,),+ getServerError: (identifier: string) => (s: ToolStore) =>+ errorInScope(s.composioServerErrors?.[identifier], cacheScope.get()),+getServerByIdentifier: (identifier: string) => (s: ToolStore) =>s.composioServers?.find((server) => server.identifier === identifier),diff --git a/src/store/tool/slices/lobehubSkillStore/action.test.ts b/src/store/tool/slices/lobehubSkillStore/action.test.tsindex 3da9dbf3bc9..c462690cbf9 100644--- a/src/store/tool/slices/lobehubSkillStore/action.test.ts+++ b/src/store/tool/slices/lobehubSkillStore/action.test.ts@@ -931,6 +931,11 @@ describe('lobehubSkillStore actions', () => {// Server should still be in state after errorexpect(result.current.lobehubSkillServers).toHaveLength(1);expect(result.current.lobehubSkillLoadingIds.has('linear')).toBe(false);+ // The reason stays on the row, so the settings list can show it in place.+ expect(result.current.lobehubSkillErrors.linear).toMatchObject({+ action: 'remove',+ message: 'Revoke failed',+ });});});diff --git a/src/store/tool/slices/lobehubSkillStore/action.ts b/src/store/tool/slices/lobehubSkillStore/action.tsindex 71229d54403..fcbe7dffbe9 100644--- a/src/store/tool/slices/lobehubSkillStore/action.ts+++ b/src/store/tool/slices/lobehubSkillStore/action.ts@@ -14,6 +14,7 @@ import { type StoreSetter } from '@/store/types';import { useUserStore } from '@/store/user';import { authSelectors } from '@/store/user/selectors';import { isSkillConnectionError } from '@/types/skillConnectionError';+import { type ConnectorActionError, toConnectorActionError } from '@/utils/connectorActionError';import { setNamespace } from '@/utils/storeDebug';import { type ToolStore } from '../../store';@@ -322,9 +323,11 @@ export class LobehubSkillStoreActionImpl {};revokeLobehubSkill = async (provider: string): Promise<void> => {+ const scope = cacheScope.get();this.#set(produce((draft: LobehubSkillStoreState) => {draft.lobehubSkillLoadingIds.add(provider);+ delete draft.lobehubSkillErrors[provider];}),false,n('revokeLobehubSkill/start'),@@ -353,6 +356,12 @@ export class LobehubSkillStoreActionImpl {this.#set(produce((draft: LobehubSkillStoreState) => {draft.lobehubSkillLoadingIds.delete(provider);+ // Kept on the row, so the failure stays visible after any toast is gone.+ if (cacheScope.get() === scope)+ draft.lobehubSkillErrors[provider] = {+ ...toConnectorActionError('remove', error),+ scope,+ };}),false,n('revokeLobehubSkill/error'),@@ -360,6 +369,20 @@ export class LobehubSkillStoreActionImpl {}};+ /** Record (or clear, with `undefined`) the last failed write of a provider row. */+ setLobehubSkillError = (provider: string, error: ConnectorActionError | undefined): void => {+ if (!error && !this.#get().lobehubSkillErrors[provider]) return;++ this.#set(+ produce((draft: LobehubSkillStoreState) => {+ if (error) draft.lobehubSkillErrors[provider] = { ...error, scope: cacheScope.get() };+ else delete draft.lobehubSkillErrors[provider];+ }),+ false,+ n('setLobehubSkillError'),+ );+ };+/*** Fetch orchestration only; read the tools through `lobehubSkillToolsMap`.* One replica entry per provider, so switching providers paints the cacheddiff --git a/src/store/tool/slices/lobehubSkillStore/initialState.ts b/src/store/tool/slices/lobehubSkillStore/initialState.tsindex 8019773c9a8..bf604e9145a 100644--- a/src/store/tool/slices/lobehubSkillStore/initialState.ts+++ b/src/store/tool/slices/lobehubSkillStore/initialState.ts@@ -1,4 +1,5 @@import { createReplicaState, type ReplicaState } from '@/libs/replica';+import { type ScopedConnectorActionError } from '@/utils/connectorActionError';import { type LobehubSkillServer, type LobehubSkillTool } from './types';@@ -9,6 +10,11 @@ import { type LobehubSkillServer, type LobehubSkillTool } from './types';* API — the replica persists them and the network only confirms.*/export interface LobehubSkillStoreState {+ /**+ * Last failed connect / disconnect per provider id, so the settings row can+ * show why it failed in place (local UI state; never persisted).+ */+ lobehubSkillErrors: Record<string, ScopedConnectorActionError>;/** Set of executing tool call IDs */lobehubSkillExecutingToolIds: Set<string>;/** Set of loading Provider IDs */@@ -32,6 +38,7 @@ export interface LobehubSkillStoreState {* LobeHub Skill Store initial state*/export const initialLobehubSkillStoreState: LobehubSkillStoreState = {+ lobehubSkillErrors: {},lobehubSkillExecutingToolIds: new Set(),lobehubSkillLoadingIds: new Set(),// Absent until the persisted row hydrates or the first network response lands.diff --git a/src/store/tool/slices/lobehubSkillStore/selectors.ts b/src/store/tool/slices/lobehubSkillStore/selectors.tsindex 85462d6cd7d..f39ebb09ea4 100644--- a/src/store/tool/slices/lobehubSkillStore/selectors.ts+++ b/src/store/tool/slices/lobehubSkillStore/selectors.ts@@ -1,6 +1,8 @@import urlJoin from 'url-join';import { OFFICIAL_SITE } from '@/const/url';+import { cacheScope } from '@/libs/replica';+import { errorInScope } from '@/utils/connectorActionError';import { type ToolStoreState } from '../../initialState';import { type LobehubSkillServer } from './types';@@ -46,6 +48,9 @@ export const lobehubSkillStoreSelectors = {getServerByIdentifier: (identifier: string) => (s: ToolStoreState) =>s.lobehubSkillServers?.find((server) => server.identifier === identifier),+ getServerError: (identifier: string) => (s: ToolStoreState) =>+ errorInScope(s.lobehubSkillErrors?.[identifier], cacheScope.get()),+/*** Get all LobeHub Skill servers*/diff --git a/src/utils/connectorActionError.test.ts b/src/utils/connectorActionError.test.tsnew file mode 100644index 00000000000..c56ea829536--- /dev/null+++ b/src/utils/connectorActionError.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from 'vitest';++import { toConnectorActionError } from './connectorActionError';++describe('toConnectorActionError', () => {+ it('keeps the tRPC code of a server rejection', () => {+ const error = Object.assign(new Error('Only the creator or a workspace owner can modify'), {+ data: { code: 'FORBIDDEN', httpStatus: 403 },+ });++ expect(toConnectorActionError('connect', error)).toEqual({+ action: 'connect',+ code: 'FORBIDDEN',+ message: 'Only the creator or a workspace owner can modify',+ });+ });++ it('treats a bare 403 as a permission rejection', () => {+ const error = Object.assign(new Error('Forbidden'), { data: { httpStatus: 403 } });++ expect(toConnectorActionError('remove', error).code).toBe('FORBIDDEN');+ });++ it('marks a request that never reached the server as a network failure', () => {+ expect(toConnectorActionError('remove', new TypeError('Failed to fetch')).code).toBe('NETWORK');+ });++ it('keeps the message of any other failure', () => {+ expect(toConnectorActionError('connect', new Error('Unsupported Composio app'))).toEqual({+ action: 'connect',+ code: undefined,+ message: 'Unsupported Composio app',+ });+ });+});diff --git a/src/utils/connectorActionError.ts b/src/utils/connectorActionError.tsnew file mode 100644index 00000000000..3280eb3b4ef--- /dev/null+++ b/src/utils/connectorActionError.ts@@ -0,0 +1,47 @@+/**+ * Why a connector write (connect / re-authorize / remove) failed, kept on the+ * row so the settings list can explain the failure in place instead of relying+ * on a toast that is long gone once the user returns from the OAuth popup.+ */+export interface ConnectorActionError {+ action: 'connect' | 'remove';+ /**+ * tRPC error code (e.g. `FORBIDDEN`) when the server rejected the call,+ * `NETWORK` when the request never reached it, or `AUTH_INCOMPLETE` when the+ * OAuth window closed without granting access.+ */+ code?: string;+ /** Raw server/client message, shown when the code has no friendlier wording. */+ message?: string;+}++/**+ * A stored {@link ConnectorActionError}, stamped with the replica scope (user ×+ * workspace) it happened in. Rows are keyed by identifier, which repeats across+ * scopes, so a reader must not show one scope's failure on another's row.+ */+export interface ScopedConnectorActionError extends ConnectorActionError {+ scope: string;+}++/** The stored error, only when it belongs to the scope being viewed. */+export const errorInScope = (+ error: ScopedConnectorActionError | undefined,+ scope: string,+): ConnectorActionError | undefined => (error?.scope === scope ? error : undefined);++const NETWORK_MESSAGE_PATTERN = /failed to fetch|network|load failed/i;++export const toConnectorActionError = (+ action: ConnectorActionError['action'],+ error: unknown,+): ConnectorActionError => {+ const data = (error as { data?: { code?: string; httpStatus?: number } } | undefined)?.data;+ const message = error instanceof Error ? error.message : error ? String(error) : undefined;++ let code = data?.code;+ if (!code && data?.httpStatus === 403) code = 'FORBIDDEN';+ if (!code && !data && message && NETWORK_MESSAGE_PATTERN.test(message)) code = 'NETWORK';++ return { action, code, message };+};