🤯 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): multiple accounts per OAuth MCP connector (#22988)
Bryane5312145e629
diff --git a/apps/cli/src/commands/connector.test.ts b/apps/cli/src/commands/connector.test.tsindex 1fd82d9900b..3eeef4bcfaa 100644--- a/apps/cli/src/commands/connector.test.ts+++ b/apps/cli/src/commands/connector.test.ts@@ -294,6 +294,7 @@ describe('connector command', () => {name: 'DeepWiki',sourceType: 'custom',status: 'connected',+ links: [{ id: 'a' }, { id: 'b' }],tools: [{}, {}, {}],},]);@@ -302,8 +303,9 @@ describe('connector command', () => {const output = consoleSpy.mock.calls.map((c: unknown[]) => String(c[0])).join('\n');expect(output).toContain('TOOLS');+ expect(output).toContain('ACCOUNTS');expect(output).toContain('deepwiki');- expect(output).toMatch(/custom\s+\S*connected\S*\s+3/);+ expect(output).toMatch(/custom\s+\S*connected\S*\s+3\s+2/);});it('outputs JSON with toolCount and field selection', async () => {diff --git a/apps/cli/src/commands/connector.ts b/apps/cli/src/commands/connector.tsindex edcb0c2f581..7835b5bef54 100644--- a/apps/cli/src/commands/connector.ts+++ b/apps/cli/src/commands/connector.ts@@ -390,9 +390,10 @@ export function registerConnectorCommand(program: Command) {c.sourceType || '',c.status === 'connected' ? pc.green(c.status) : c.status || '',String(c.toolCount),+ String(c.links?.length ?? 0),]);- printTable(rows, ['ID', 'IDENTIFIER', 'NAME', 'SOURCE', 'STATUS', 'TOOLS']);+ printTable(rows, ['ID', 'IDENTIFIER', 'NAME', 'SOURCE', 'STATUS', 'TOOLS', 'ACCOUNTS']);});// ── add ───────────────────────────────────────────────diff --git a/apps/desktop/src/main/controllers/ConnectorOAuthCtr.ts b/apps/desktop/src/main/controllers/ConnectorOAuthCtr.tsindex dddeb1d7039..7b9953adedb 100644--- a/apps/desktop/src/main/controllers/ConnectorOAuthCtr.ts+++ b/apps/desktop/src/main/controllers/ConnectorOAuthCtr.ts@@ -6,7 +6,7 @@ import type {ConnectorOAuthRequest,ConnectorOAuthResult,} from '@lobechat/electron-client-ipc/types';-import { BrowserWindow } from 'electron';+import { BrowserWindow, session } from 'electron';import { preloadDir } from '@/const/dir';import { createLogger } from '@/utils/logger';@@ -68,6 +68,8 @@ export default class ConnectorOAuthCtr extends ControllerModule implements Connereturn 'failed';}+ if (params.freshSession) await session.fromPartition('connector-oauth').clearStorageData();+ if (pending.canceled) return 'dismissed';const parent = this.app.browserManager.getMainWindow().browserWindow;const popup = new BrowserWindow({autoHideMenuBar: true,diff --git a/apps/desktop/src/main/controllers/__tests__/ConnectorOAuthCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/ConnectorOAuthCtr.test.tsindex 255a6a8c5e4..31ffe38d3cb 100644--- a/apps/desktop/src/main/controllers/__tests__/ConnectorOAuthCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/ConnectorOAuthCtr.test.ts@@ -1,6 +1,6 @@import { EventEmitter } from 'node:events';-import { BrowserWindow } from 'electron';+import { BrowserWindow, session } from 'electron';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { App } from '@/core/App';@@ -8,7 +8,12 @@ import { CONNECTOR_OAUTH_RESULT_CHANNEL } from '~common/connectorOAuth';import ConnectorOAuthCtr from '../ConnectorOAuthCtr';-vi.mock('electron', () => ({ BrowserWindow: vi.fn(), ipcMain: { handle: vi.fn() } }));+const clearStorageData = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));+vi.mock('electron', () => ({+ BrowserWindow: vi.fn(),+ ipcMain: { handle: vi.fn() },+ session: { fromPartition: vi.fn(() => ({ clearStorageData })) },+}));vi.mock('@/const/dir', () => ({ preloadDir: '/preload' }));vi.mock('../RemoteServerConfigCtr', () => ({ default: class {} }));@@ -248,4 +253,15 @@ describe('ConnectorOAuthCtr', () => {expect(vi.getTimerCount()).toBe(0);expect(parent.listenerCount('closed')).toBe(0);});+ it('clears only the OAuth partition before opening an additional-account window', async () => {+ const pending = controller.authorize({ ...params, freshSession: true });+ await vi.advanceTimersByTimeAsync(0);+ expect(session.fromPartition).toHaveBeenCalledWith('connector-oauth');+ expect(clearStorageData).toHaveBeenCalledOnce();+ expect(clearStorageData.mock.invocationCallOrder[0]).toBeLessThan(+ vi.mocked(BrowserWindow).mock.invocationCallOrder[0],+ );+ send();+ expect(await pending).toBe('success');+ });});diff --git a/apps/server/src/modules/Redis/keys.ts b/apps/server/src/modules/Redis/keys.tsindex 6d920309cc8..4d56cc53953 100644--- a/apps/server/src/modules/Redis/keys.ts+++ b/apps/server/src/modules/Redis/keys.ts@@ -263,6 +263,11 @@ export const RedisKeys = {* Integrations scope — see {@link RedisKeyNamespace.INTEGRATIONS}.*/integrations: {+ /**+ * How one connector OAuth flow ended, read back by the window that started it.+ * Full key: integrations:connector_oauth_completion:v1:{flowId}+ */+ connectorOAuthCompletion: (flowId: string): string => `connector_oauth_completion:v1:${flowId}`,/*** Single-use state of one "Connect Linear" OAuth hand-off.* Full key: integrations:linear_oauth_state:v1:{state}diff --git a/apps/server/src/routers/lambda/__tests__/connector.links.test.ts b/apps/server/src/routers/lambda/__tests__/connector.links.test.tsnew file mode 100644index 00000000000..d2adae40016--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/connector.links.test.ts@@ -0,0 +1,195 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { ConnectorModel } from '@/database/models/connector';+import { users } from '@/database/schemas';+import { startOAuthMcpServer } from '@/libs/mcp/__tests__/fixtures/oauthMcpServer';+import { ensureFreshLinkToken } from '@/server/services/connector/tokens';++import { connectorRouter } from '../connector';++const vault = vi.hoisted(() => ({+ encrypt: async (s: string) => `enc:${s}`,+ decrypt: async (s: string) => ({ plaintext: s.replace(/^enc:/, '') }),+}));+vi.mock('@/libs/trpc/lambda/middleware', () => ({+ serverDatabase: async (opts: any) => opts.next({ ctx: opts.ctx }),+}));+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({+ KeyVaultsGateKeeper: { initWithEnvKey: async () => vault },+}));+const db = await getTestDB();+const model = new ConnectorModel(db, 'links-router', undefined, vault);+const linkModel = model.getLinkModel();+const caller = connectorRouter.createCaller({ userId: 'links-router', serverDB: db } as never);+const credentials = {+ type: 'oauth2' as const,+ accessToken: 'private-token',+ refreshToken: 'private-refresh',+};+const create = async () => {+ const row = await model.create({+ identifier: crypto.randomUUID(),+ name: 'OAuth',+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://mcp.example',+ sourceType: 'custom',+ status: 'connected',+ oidcConfig: {+ scheme: 'dcr',+ clientId: 'resolved-client',+ clientSecret: 'resolved-secret',+ issuer: 'https://as.example',+ scopes: ['tools'],+ },+ });+ const link = await linkModel.applyAuthorization(row.id, {+ target: { kind: 'new' },+ credentials,+ authorizerId: 'links-router',+ });+ return { row, link };+};+beforeEach(async () => {+ await db.delete(users);+ await db.insert(users).values({ id: 'links-router', fullName: 'Author' });+});+afterEach(async () => {+ await db.delete(users);+ vi.restoreAllMocks();+ vi.unstubAllEnvs();+});+describe('connector account APIs', () => {+ it('preserves a resolved DCR client on ordinary form save and both accounts stay usable', async () => {+ const { row } = await create();+ await linkModel.applyAuthorization(row.id, {+ target: { kind: 'new' },+ credentials,+ authorizerId: 'links-router',+ });+ await caller.update({+ id: row.id,+ patch: {+ name: 'Renamed',+ metadata: { customHeaders: { 'X-Test': 'value' } },+ oidcConfig: { scheme: 'dcr', clientId: undefined },+ },+ });+ expect((await model.findById(row.id))?.oidcConfig).toMatchObject({+ clientId: 'resolved-client',+ clientSecret: 'resolved-secret',+ scopes: ['tools'],+ });+ expect(await linkModel.listByConnectorIds([row.id])).toHaveLength(2);+ await caller.update({ id: row.id, patch: { mcpServerUrl: 'https://different.example' } });+ expect(await linkModel.listByConnectorIds([row.id])).toHaveLength(0);+ expect((await model.findById(row.id))?.oidcConfig).toEqual({ scheme: 'dcr' });+ });+ it('returns safe account summaries and the decrypted auth kind', async () => {+ const { row, link } = await create();+ const result = (await caller.list()).find((c) => c.id === row.id)!;+ expect(result).toMatchObject({+ authKind: 'oauth2',+ links: [{ id: link.linkId, name: 'Default', authorizedByName: 'Author' }],+ });+ expect(JSON.stringify(result)).not.toContain('private-token');+ expect(JSON.stringify(result)).not.toContain('resolved-secret');+ await model.create({+ identifier: 'bearer',+ name: 'Bearer',+ sourceType: 'custom',+ status: 'connected',+ credentials: JSON.stringify({ type: 'bearer', token: 'static' }),+ });+ expect((await caller.list()).find((c) => c.identifier === 'bearer')).toMatchObject({+ authKind: 'bearer',+ links: [],+ });+ });+ it('renames, rejects duplicate names and disconnects only after removing the last account', async () => {+ const { row, link } = await create();+ const second = await linkModel.applyAuthorization(row.id, {+ target: { kind: 'new' },+ credentials,+ authorizerId: 'links-router',+ });+ await expect(+ caller.renameLink({ id: row.id, linkId: second.linkId, name: 'Default' }),+ ).rejects.toMatchObject({ code: 'CONFLICT' });+ await caller.renameLink({ id: row.id, linkId: second.linkId, name: 'Work' });+ await caller.deleteLink({ id: row.id, linkId: link.linkId });+ expect((await model.findById(row.id))?.status).toBe('connected');+ await caller.deleteLink({ id: row.id, linkId: second.linkId });+ expect((await model.findById(row.id))?.status).toBe('disconnected');+ });+ it('reports none after an explicit switch away from OAuth without losing the no-account OAuth distinction', async () => {+ const { row, link } = await create();+ await caller.deleteLink({ id: row.id, linkId: link.linkId });+ expect((await caller.list()).find((c) => c.id === row.id)?.authKind).toBe('oauth2');+ await caller.update({ id: row.id, patch: { credentials: null } });+ expect((await caller.list()).find((c) => c.id === row.id)?.authKind).toBe('none');+ expect((await model.findById(row.id))?.oidcConfig).toBeNull();+ });+ it.each([undefined, 'updated-secret'])(+ 'merges a same-clientId save without losing resolved OAuth config and refreshes its link (secret=%s)',+ async (clientSecret) => {+ vi.stubEnv('SSRF_ALLOW_PRIVATE_IP_ADDRESS', '1');+ const fixture = await startOAuthMcpServer();+ try {+ const oidc = {+ scheme: 'pre_registration' as const,+ clientId: 'fixture-client',+ clientSecret: 'stored-secret',+ issuer: fixture.base,+ authorizationEndpoint: `${fixture.base}/authorize`,+ tokenEndpoint: `${fixture.base}/token`,+ registrationEndpoint: `${fixture.base}/register`,+ redirectUri: 'http://localhost/callback',+ scopes: ['tools'],+ tokenEndpointAuthMethod: 'none' as const,+ };+ const row = await model.create({+ identifier: crypto.randomUUID(),+ name: 'Refresh',+ sourceType: 'custom',+ status: 'connected',+ mcpConnectionType: 'http',+ mcpServerUrl: `${fixture.base}/mcp`,+ oidcConfig: oidc,+ });+ const link = await linkModel.applyAuthorization(row.id, {+ target: { kind: 'new' },+ credentials: {+ type: 'oauth2',+ accessToken: 'expired',+ refreshToken: 'refresh-alice-seed',+ expiresAt: 1,+ },+ authorizerId: 'links-router',+ });+ await caller.update({+ id: row.id,+ patch: {+ oidcConfig: { scheme: 'pre_registration', clientId: oidc.clientId, clientSecret },+ },+ });+ const updated = (await model.findById(row.id))!;+ expect(updated.oidcConfig).toEqual({+ ...oidc,+ clientSecret: clientSecret ?? 'stored-secret',+ });+ const links = await linkModel.listByConnectorIds([row.id]);+ expect(links.map((item) => item.id)).toEqual([link.linkId]);+ const refreshed = await ensureFreshLinkToken(updated, links[0], linkModel, model);+ expect(refreshed.credentials.accessToken).toMatch(/^tok-alice-/);+ expect((await linkModel.findById(row.id, link.linkId))?.credentials.accessToken).toBe(+ refreshed.credentials.accessToken,+ );+ expect(fixture.refreshes).toEqual(['refresh-alice-seed']);+ } finally {+ await fixture.close();+ }+ },+ );+});diff --git a/apps/server/src/routers/lambda/__tests__/connector.startOAuth.test.ts b/apps/server/src/routers/lambda/__tests__/connector.startOAuth.test.tsindex 4a338a0b88c..738babbb674 100644--- a/apps/server/src/routers/lambda/__tests__/connector.startOAuth.test.ts+++ b/apps/server/src/routers/lambda/__tests__/connector.startOAuth.test.ts@@ -2,6 +2,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { ConnectorModel } from '@/database/models/connector';+import { ConnectorLinkModel } from '@/database/models/connectorLink';import { ConnectorToolModel } from '@/database/models/connectorTool';import { connectorRouter } from '../connector';@@ -10,6 +11,11 @@ const mocks = vi.hoisted(() => ({ saveState: vi.fn() }));vi.mock('@/database/models/agent', () => ({ AgentModel: vi.fn() }));vi.mock('@/database/models/connector', () => ({ ConnectorModel: vi.fn() }));+vi.mock('@/database/models/connectorLink', () => ({+ ConnectorLinkModel: vi.fn(function () {+ return { listByConnectorIds: vi.fn().mockResolvedValue([]) };+ }),+}));vi.mock('@/database/models/connectorTool', () => ({ ConnectorToolModel: vi.fn() }));vi.mock('@/database/models/plugin', () => ({ PluginModel: vi.fn() }));vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({@@ -170,7 +176,7 @@ describe('connectorRouter.startOAuth client registration', () => {const url = new URL((await startOAuth()).authorizationUrl);- expect(url.searchParams.get('scope')).toBe('openid offline_access');+ expect(url.searchParams.get('scope')).toBe('openid offline_access profile email');expect(url.searchParams.get('prompt')).toBe('consent');});@@ -182,7 +188,9 @@ describe('connectorRouter.startOAuth client registration', () => {const url = new URL((await startOAuth()).authorizationUrl);- expect(url.searchParams.get('scope')).toBe('tools:read tools:write offline_access');+ expect(url.searchParams.get('scope')).toBe(+ 'tools:read tools:write offline_access openid profile email',+ );});it.each([undefined, {}])(@@ -271,4 +279,87 @@ describe('connectorRouter.startOAuth client registration', () => {expect(registrations).toHaveLength(1);expect(registrations[0]).not.toHaveProperty('scope');});+ it('merges select_account with SDK consent only when the AS advertises it for a new account', async () => {+ stubAuthorizationServer(+ { ...vercelMetadata, prompt_values_supported: ['select_account', 'consent'] },+ { scopes: ['tools'] },+ );+ connectorModelMock.findById.mockResolvedValue({+ id: CONNECTOR_ID,+ userId: 'me',+ sourceType: 'custom',+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://mcp.example.com/mcp',+ oidcConfig: { scheme: 'dcr' },+ });+ const result = await connectorRouter+ .createCaller({ serverDB: {}, userId: 'me' } as any)+ .startOAuth({ id: CONNECTOR_ID, link: { mode: 'add' } });+ expect(new URL(result.authorizationUrl).searchParams.get('prompt')).toBe(+ 'consent select_account',+ );+ expect(mocks.saveState.mock.calls.at(-1)?.[1].linkTarget).toEqual({ kind: 'new' });+ });++ it('keeps only an in-app return path in the OAuth state', async () => {+ stubAuthorizationServer({ registration_endpoint: 'https://mcp.example.com/register' });+ const caller = connectorRouter.createCaller({ serverDB: {}, userId: 'me' } as any);++ await caller.startOAuth({ id: CONNECTOR_ID, returnTo: '/settings/connector' });+ expect(mocks.saveState.mock.calls.at(-1)?.[1].returnTo).toBe('/settings/connector');++ for (const returnTo of ['https://evil.example/x', '//evil.example/x', '/\\evil.example']) {+ await caller.startOAuth({ id: CONNECTOR_ID, returnTo });+ expect(mocks.saveState.mock.calls.at(-1)?.[1].returnTo).toBeUndefined();+ }+ });++ it('rejects add on a non-custom connector and reauthorization of an unknown account', async () => {+ connectorModelMock.findById.mockResolvedValue({+ id: CONNECTOR_ID,+ userId: 'me',+ sourceType: 'marketplace',+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://mcp.example.com/mcp',+ });+ const caller = connectorRouter.createCaller({ serverDB: {}, userId: 'me' } as any);+ await expect(+ caller.startOAuth({ id: CONNECTOR_ID, link: { mode: 'add' } }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ await expect(+ caller.startOAuth({ id: CONNECTOR_ID, link: { mode: 'reauthorize', linkId: 'missing' } }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ });++ it('defaults to the earliest account and honors an explicit reauthorization target', async () => {+ stubAuthorizationServer(vercelMetadata);+ vi.mocked(ConnectorLinkModel).mockImplementationOnce(function () {+ return {+ listByConnectorIds: async () => [+ { id: 'lnk_early', userConnectorId: CONNECTOR_ID },+ { id: 'lnk_late', userConnectorId: CONNECTOR_ID },+ ],+ } as any;+ });+ await startOAuth();+ expect(mocks.saveState.mock.calls.at(-1)?.[1].linkTarget).toEqual({+ kind: 'existing',+ linkId: 'lnk_early',+ });+ vi.mocked(ConnectorLinkModel).mockImplementationOnce(function () {+ return {+ listByConnectorIds: async () => [+ { id: 'lnk_early', userConnectorId: CONNECTOR_ID },+ { id: 'lnk_late', userConnectorId: CONNECTOR_ID },+ ],+ } as any;+ });+ await connectorRouter+ .createCaller({ serverDB: {}, userId: 'me' } as any)+ .startOAuth({ id: CONNECTOR_ID, link: { mode: 'reauthorize', linkId: 'lnk_late' } });+ expect(mocks.saveState.mock.calls.at(-1)?.[1].linkTarget).toEqual({+ kind: 'existing',+ linkId: 'lnk_late',+ });+ });});diff --git a/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts b/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.tsindex 1c05f10145f..269c032aadd 100644--- a/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts+++ b/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts@@ -16,6 +16,12 @@ const mocks = vi.hoisted(() => ({// so the relative import order doesn't matter functionally — the mocks below// are still active when the router module is evaluated. They live below the// imports to satisfy `import-x/first` without disabling the rule.+vi.mock('@/database/models/connectorLink', () => ({+ ConnectorLinkModel: vi.fn(function () {+ return { listByConnectorIds: async () => [] };+ }),+}));+vi.mock('@/database/models/agent', () => ({ AgentModel: vi.fn() }));vi.mock('@/database/models/connector', () => ({ ConnectorModel: vi.fn() }));vi.mock('@/database/models/connectorTool', () => ({ ConnectorToolModel: vi.fn() }));diff --git a/apps/server/src/routers/lambda/connector/accounts.ts b/apps/server/src/routers/lambda/connector/accounts.tsnew file mode 100644index 00000000000..b35e90f9103--- /dev/null+++ b/apps/server/src/routers/lambda/connector/accounts.ts@@ -0,0 +1,218 @@+import type { ConnectorOIDCConfig } from '@lobechat/types';+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import type { ConnectorModel } from '@/database/models/connector';+import {+ type ConnectorLinkModel,+ ConnectorLinkNameTakenError,+ ConnectorLinkNotFoundError,+} from '@/database/models/connectorLink';+import { loadConnectorLinksMap } from '@/server/services/connector/links';+import {+ buildAuthorizationUrl,+ discoverConnectorOAuth,+ getConnectorRedirectUri,+ resolveConnectorClient,+ resolveConnectorOAuthScopes,+ toClientInformation,+} from '@/server/services/connector/oauth';+import {+ generateConnectorOAuthState,+ readConnectorOAuthCompletion,+ saveConnectorOAuthState,+} from '@/server/services/connector/stateStore';+import { sanitizeReturnTo } from '@/server/services/scm/scope';++import { assertConnectorMaintainable } from '../_helpers/connectorManagePolicy';+import { connectorProcedure, connectorWriteProcedure } from './procedures';++/** The connector holding account `linkId`; NOT_FOUND when either is out of reach. */+const findAccountConnector = async (+ ctx: { connectorLinkModel: ConnectorLinkModel; connectorModel: ConnectorModel },+ id: string,+ linkId: string,+) => {+ const connector = await ctx.connectorModel.findById(id);+ if (!connector || !(await ctx.connectorLinkModel.findById(id, linkId)))+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector account not found' });+ return connector;+};++export const connectorAccountProcedures = {+ startOAuth: connectorWriteProcedure+ .input(+ z.object({+ id: z.string().uuid(),+ returnTo: z.string().optional(),+ link: z+ .discriminatedUnion('mode', [+ z.object({ mode: z.literal('add') }),+ z.object({ mode: z.literal('reauthorize'), linkId: z.string() }),+ ])+ .optional(),+ }),+ )+ .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 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' });+ }++ if (+ input.link?.mode === 'add' &&+ (connector.sourceType !== 'custom' || connector.mcpConnectionType !== 'http')+ )+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Multiple accounts require a custom HTTP connector',+ });+ const links = (await loadConnectorLinksMap([connector], ctx)).get(connector.id) ?? [];+ const linkTarget =+ input.link?.mode === 'add'+ ? { kind: 'new' as const }+ : input.link?.mode === 'reauthorize'+ ? { kind: 'existing' as const, linkId: input.link.linkId }+ : links.length+ ? { kind: 'existing' as const, linkId: links[0].id }+ : { kind: 'new' as const };+ if (linkTarget.kind === 'existing' && !links.some((link) => link.id === linkTarget.linkId))+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector account not found' });+ const existing: ConnectorOIDCConfig = connector.oidcConfig ?? { scheme: 'dcr' };+ const redirectUri = getConnectorRedirectUri();++ // 1. Discover the authorization server backing the MCP resource.+ // Discovery and registration failures below are server-compatibility+ // problems the user must fix in their OAuth setup, not internal errors —+ // surface them as BAD_REQUEST with the reason so the form can show it.+ const discovery = await discoverConnectorOAuth(connector.mcpServerUrl).catch(+ (error: unknown) => {+ throw new TRPCError({+ cause: error,+ code: 'BAD_REQUEST',+ message: (error as Error)?.message ?? String(error),+ });+ },+ );++ const { authorizationServerUrl, metadata } = discovery;+ const scopes = resolveConnectorOAuthScopes({+ discovery,+ existingScopes: existing.scopes,+ preRegistered: existing.scheme === 'pre_registration',+ });++ // 2. Resolve the OAuth client: pre-registration, CIMD, then DCR.+ const { clientId, clientSecret, scheme, tokenEndpointAuthMethod } =+ await resolveConnectorClient({+ authorizationServerUrl,+ existing,+ metadata,+ redirectUri,+ scopes,+ }).catch((error: unknown) => {+ throw new TRPCError({+ cause: error,+ code: 'BAD_REQUEST',+ message: (error as Error)?.message ?? String(error),+ });+ });++ // 3. Persist the resolved config so the callback + refresh can reuse it.+ const resolvedOidc: ConnectorOIDCConfig = {+ ...existing,+ authorizationEndpoint: metadata.authorization_endpoint,+ clientId,+ clientSecret,+ issuer: authorizationServerUrl,+ redirectUri,+ registrationEndpoint: metadata.registration_endpoint,+ scheme,+ scopes,+ tokenEndpoint: metadata.token_endpoint,+ tokenEndpointAuthMethod,+ };+ await ctx.connectorModel.update(input.id, { oidcConfig: resolvedOidc });++ // 4. Build the authorize URL (with PKCE) and stash the verifier under `state`.+ const state = generateConnectorOAuthState();+ const { authorizationUrl, codeVerifier } = await buildAuthorizationUrl({+ authorizationServerUrl,+ clientInformation: toClientInformation(resolvedOidc),+ prompt:+ linkTarget.kind === 'new' &&+ Array.isArray(+ (metadata as { prompt_values_supported?: string[] }).prompt_values_supported,+ ) &&+ (metadata as { prompt_values_supported?: string[] }).prompt_values_supported!.includes(+ 'select_account',+ )+ ? 'select_account'+ : undefined,+ metadata,+ redirectUri,+ resource: connector.mcpServerUrl,+ scopes,+ state,+ });++ await saveConnectorOAuthState(state, {+ authorizationServerUrl,+ codeVerifier,+ connectorId: input.id,+ lobeUserId: ctx.userId,+ linkTarget,+ // Only an in-app path may ever be followed after the callback.+ returnTo: sanitizeReturnTo(input.returnTo),+ workspaceId: ctx.workspaceId ?? undefined,+ });++ return { authorizationUrl, flowId: state };+ }),++ oauthResult: connectorProcedure+ .input(z.object({ flowId: z.string() }))+ .query(async ({ input, ctx }) => {+ const result = await readConnectorOAuthCompletion(input.flowId);+ if (+ !result ||+ result.lobeUserId !== ctx.userId ||+ (result.workspaceId ?? null) !== (ctx.workspaceId ?? null)+ )+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Authorization result not found' });+ return { linkId: result.linkId, outcome: result.outcome };+ }),++ renameLink: connectorWriteProcedure+ .input(+ z.object({+ id: z.string().uuid(),+ linkId: z.string(),+ name: z.string().trim().min(1).max(64),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ const connector = await findAccountConnector(ctx, input.id, input.linkId);+ await assertConnectorMaintainable(ctx, connector);+ try {+ await ctx.connectorLinkModel.rename(input.id, input.linkId, input.name);+ } catch (error) {+ if (error instanceof ConnectorLinkNameTakenError)+ throw new TRPCError({ code: 'CONFLICT', message: error.message });+ if (error instanceof ConnectorLinkNotFoundError)+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector account not found' });+ throw error;+ }+ }),++ deleteLink: connectorWriteProcedure+ .input(z.object({ id: z.string().uuid(), linkId: z.string() }))+ .mutation(async ({ input, ctx }) => {+ const connector = await findAccountConnector(ctx, input.id, input.linkId);+ await assertConnectorMaintainable(ctx, connector);+ await ctx.connectorLinkModel.remove(input.id, input.linkId);+ }),+};diff --git a/apps/server/src/routers/lambda/connector/index.ts b/apps/server/src/routers/lambda/connector/index.tsindex e9a62377475..479cac9985f 100644--- a/apps/server/src/routers/lambda/connector/index.ts+++ b/apps/server/src/routers/lambda/connector/index.ts@@ -17,7 +17,6 @@ import {} from '@/database/models/connectorEval';import { WorkspaceModel } from '@/database/models/workspace';import { WorkspaceAuditLogModel } from '@/database/models/workspaceAuditLog';-import type { OIDCConfig } from '@/database/schemas';import {ConnectorMcpConnectionType,ConnectorSourceType,@@ -34,18 +33,8 @@ import {readConnectorUiResourceById,} from '@/server/services/connector/exec';import { getConnectorLocalCallToken } from '@/server/services/connector/localCallToken';-import {- buildAuthorizationUrl,- discoverConnectorOAuth,- getConnectorRedirectUri,- resolveConnectorClient,- resolveConnectorOAuthScopes,- toClientInformation,-} from '@/server/services/connector/oauth';-import {- generateConnectorOAuthState,- saveConnectorOAuthState,-} from '@/server/services/connector/stateStore';+import { getConnectorRedirectUri } from '@/server/services/connector/oauth';+import { loadConnectorPresentation } from '@/server/services/connector/presentation';import {pruneMissingAutoConnectorTools,syncConnectorToolsById,@@ -80,6 +69,7 @@ import {} from '../_helpers/connectorManagePolicy';import { resolveDefaultPermission } from '../_helpers/connectorToolPermission';import { upsertConnectorEntry } from '../_helpers/upsertConnectorEntry';+import { connectorAccountProcedures } from './accounts';import { connectorAgentScopeRouter } from './agentScope';import { connectorProcedure, connectorWriteProcedure } from './procedures';@@ -147,10 +137,12 @@ const createConnectorSchema = z.object({});const connectorCoreRouter = router({+ ...connectorAccountProcedures,// ── Queries ──────────────────────────────────────────────────────────────list: connectorProcedure.query(async ({ ctx }) => {const connectors = await ctx.connectorModel.query();+ const presentation = await loadConnectorPresentation(connectors, ctx);// Attribution — resolve the member who authorized each connector (workspace// dimension), so the profile can tag "authorized by X". The ids come from@@ -170,6 +162,7 @@ const connectorCoreRouter = router({const author = authorMap.get(resolveConnectorAuthorizerId(c) ?? '');return {...rest,+ ...presentation.get(c.id),authorizedByAvatar: author?.avatar ?? null,authorizedByName: author?.name ?? null,oidcConfig: safeOidcConfig,@@ -191,6 +184,7 @@ const connectorCoreRouter = router({.input(z.object({ agentId: z.string() })).query(async ({ input, ctx }) => {const connectors = await ctx.connectorModel.queryByAgent(input.agentId);+ const presentation = await loadConnectorPresentation(connectors, ctx);// Attribution — the member who authorized each agent-scoped connector, so// a teammate viewing the agent sees "authorized by X" on each chip.@@ -210,6 +204,7 @@ const connectorCoreRouter = router({const author = authorMap.get(resolveConnectorAuthorizerId(c) ?? '');return {...rest,+ ...presentation.get(c.id),authorizedByAvatar: author?.avatar ?? null,authorizedByName: author?.name ?? null,oidcConfig: safeOidcConfig,@@ -247,9 +242,11 @@ const connectorCoreRouter = router({// connector inventory never leaks across members.const agentMetas = agentIds.length > 0 ? await agentModel.getAgentAvatarsByIds(agentIds) : [];const agentMetaById = new Map(agentMetas.map((m) => [m.id, m]));+ const visibleConnectors = connectors.filter((c) => !!c.agentId && agentMetaById.has(c.agentId));+ const presentation = await loadConnectorPresentation(visibleConnectors, ctx);return pMap(- connectors.filter((c) => !!c.agentId && agentMetaById.has(c.agentId)),+ visibleConnectors,async (c) => {const tools = await ctx.connectorToolModel.queryByConnector(c.id);const { credentials: _credentials, oidcConfig, ...rest } = c;@@ -257,6 +254,7 @@ const connectorCoreRouter = router({const meta = agentMetaById.get(c.agentId!);return {...rest,+ ...presentation.get(c.id),agentAvatar: meta?.avatar ?? null,agentName: meta?.name ?? null,agentTitle: meta?.title ?? null,@@ -303,8 +301,8 @@ const connectorCoreRouter = router({/** The OAuth access token a device-routed connector's local desktop call sends. */getLocalCallToken: connectorWriteProcedure- .input(z.object({ id: z.string().uuid() }))- .mutation(({ ctx, input }) => getConnectorLocalCallToken(ctx, input.id)),+ .input(z.object({ id: z.string().uuid(), linkId: z.string().optional() }))+ .mutation(({ ctx, input }) => getConnectorLocalCallToken(ctx, input.id, input.linkId)),/*** Test an MCP server that runs on the user's device (an HTTP server set to@@ -467,102 +465,7 @@ const connectorCoreRouter = router({return { id: created.id, isNew: true };}),- /**- * Begin the OAuth authorization-code flow for a custom MCP connector.- *- * Discovers the authorization server (RFC 9728 → RFC 8414), resolves the- * client (pre-registration when a client_id was provided, otherwise a Client- * ID Metadata Document or RFC 7591 dynamic registration), persists the- * resolved OIDC config, and returns the authorize URL for the client to open. The PKCE verifier is stashed in Redis- * keyed by `state`; the callback route completes the exchange.- */- startOAuth: connectorWriteProcedure- .input(z.object({ id: z.string().uuid(), returnTo: z.string().optional() }))- .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 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' });- }-- const existing: OIDCConfig = connector.oidcConfig ?? { scheme: 'dcr' };- const redirectUri = getConnectorRedirectUri();-- // 1. Discover the authorization server backing the MCP resource.- // Discovery and registration failures below are server-compatibility- // problems the user must fix in their OAuth setup, not internal errors —- // surface them as BAD_REQUEST with the reason so the form can show it.- const discovery = await discoverConnectorOAuth(connector.mcpServerUrl).catch(- (error: unknown) => {- throw new TRPCError({- cause: error,- code: 'BAD_REQUEST',- message: (error as Error)?.message ?? String(error),- });- },- );-- const { authorizationServerUrl, metadata } = discovery;- const scopes = resolveConnectorOAuthScopes({ discovery, existingScopes: existing.scopes });-- // 2. Resolve the OAuth client: pre-registration, CIMD, then DCR.- const { clientId, clientSecret, scheme, tokenEndpointAuthMethod } =- await resolveConnectorClient({- authorizationServerUrl,- existing,- metadata,- redirectUri,- scopes,- }).catch((error: unknown) => {- throw new TRPCError({- cause: error,- code: 'BAD_REQUEST',- message: (error as Error)?.message ?? String(error),- });- });-- // 3. Persist the resolved config so the callback + refresh can reuse it.- const resolvedOidc: OIDCConfig = {- ...existing,- authorizationEndpoint: metadata.authorization_endpoint,- clientId,- clientSecret,- issuer: authorizationServerUrl,- redirectUri,- registrationEndpoint: metadata.registration_endpoint,- scheme,- scopes,- tokenEndpoint: metadata.token_endpoint,- tokenEndpointAuthMethod,- };- await ctx.connectorModel.update(input.id, { oidcConfig: resolvedOidc });-- // 4. Build the authorize URL (with PKCE) and stash the verifier under `state`.- const state = generateConnectorOAuthState();- const { authorizationUrl, codeVerifier } = await buildAuthorizationUrl({- authorizationServerUrl,- clientInformation: toClientInformation(resolvedOidc),- metadata,- redirectUri,- resource: connector.mcpServerUrl,- scopes,- state,- });-- await saveConnectorOAuthState(state, {- authorizationServerUrl,- codeVerifier,- connectorId: input.id,- lobeUserId: ctx.userId,- returnTo: input.returnTo,- workspaceId: ctx.workspaceId ?? undefined,- });-- return { authorizationUrl };- }),-+ /** Update connector configuration while preserving server-resolved OAuth state. */update: connectorWriteProcedure.input(z.object({@@ -601,6 +504,39 @@ const connectorCoreRouter = router({await assertConnectorDeviceBindingAllowed(ctx, input.patch.metadata, target.metadata);const { credentials, ...patch } = input.patch;+ const changesUrl =+ patch.mcpServerUrl !== undefined && patch.mcpServerUrl !== target.mcpServerUrl;+ if (+ changesUrl &&+ target.oidcConfig &&+ target.oidcConfig.scheme !== 'pre_registration' &&+ !patch.oidcConfig?.clientId+ ) {+ // An automatic client is registered with the old authorization server.+ // A new endpoint must resolve its own client and initial scopes.+ patch.oidcConfig = { scheme: 'dcr' };+ } else if (+ patch.oidcConfig &&+ !patch.oidcConfig.clientId &&+ target.oidcConfig &&+ target.oidcConfig.scheme !== 'pre_registration' &&+ patch.oidcConfig.scheme === target.oidcConfig.scheme+ )+ // The edit form resends the automatic client it shows without the+ // fields the server resolved: keep the stored client and its accounts.+ // A connector switching to OAuth, or to another scheme, stores the new+ // one and waits for its authorization.+ delete patch.oidcConfig;+ if (patch.oidcConfig?.clientId && patch.oidcConfig.clientId === target.oidcConfig?.clientId) {+ // A form/CLI may resend the client without its resolved server fields.+ // Undefined fields mean omitted, including an unfilled client secret.+ patch.oidcConfig = {+ ...target.oidcConfig,+ ...Object.fromEntries(+ Object.entries(patch.oidcConfig).filter(([, value]) => value !== undefined),+ ),+ };+ }// Preserve the server-owned `composio.linkedByUserId` from the stored row// and ignore whatever the client sent, so an edit can never spoof (or// silently clear) the connector's authorizer. Untouched when the patch@@ -735,6 +671,8 @@ const connectorCoreRouter = router({fromApp: z.boolean().optional(),fromEntrypoint: z.boolean().optional(),identifier: z.string().min(1),+ /** The account to call as, for a connector holding several. */+ linkId: z.string().optional(),/** With `fromApp`: the server the view came from (`getMcpServerFingerprint`). */server: z.string().optional(),toolName: z.string().min(1),@@ -769,6 +707,8 @@ const connectorCoreRouter = router({/** The server the result came from (`getMcpServerFingerprint`). */server: z.string().min(1),uri: z.string().startsWith('ui://'),+ /** The account the tool ran as, for a connector holding several. */+ linkId: z.string().optional(),}),).query(async ({ input, ctx }) => {diff --git a/apps/server/src/routers/lambda/connector/oauthResult.test.ts b/apps/server/src/routers/lambda/connector/oauthResult.test.tsnew file mode 100644index 00000000000..41286b7fa39--- /dev/null+++ b/apps/server/src/routers/lambda/connector/oauthResult.test.ts@@ -0,0 +1,48 @@+// @vitest-environment node+import { afterEach, describe, expect, it, vi } from 'vitest';++import { connectorRouter } from './index';++const result = vi.hoisted(() => vi.fn());+vi.mock('@/server/services/connector/stateStore', async (original) => ({+ ...(await original<object>()),+ readConnectorOAuthCompletion: result,+}));+vi.mock('@/libs/trpc/lambda/middleware', () => ({+ serverDatabase: async (opts: any) => opts.next({ ctx: opts.ctx }),+}));+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({+ KeyVaultsGateKeeper: { initWithEnvKey: async () => ({}) },+}));+const caller = (userId = 'me', workspaceId?: string) =>+ connectorRouter.createCaller({ userId, workspaceId, serverDB: {} } as never);+afterEach(() => {+ vi.clearAllMocks();+});+describe('OAuth completion receipts', () => {+ it('returns only the exact outcome to the initiating user and scope', async () => {+ result.mockResolvedValue({+ lobeUserId: 'me',+ workspaceId: 'ws',+ connectorId: 'c',+ linkId: 'lnk_b',+ outcome: 'matchedExisting',+ });+ expect(await caller('me', 'ws').oauthResult({ flowId: 'state' })).toEqual({+ linkId: 'lnk_b',+ outcome: 'matchedExisting',+ });+ await expect(caller('other', 'ws').oauthResult({ flowId: 'state' })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ await expect(caller('me').oauthResult({ flowId: 'state' })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ });+ it('does not reveal expired or missing receipts', async () => {+ result.mockResolvedValue(null);+ await expect(caller().oauthResult({ flowId: 'expired' })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ });+});diff --git a/apps/server/src/routers/lambda/connector/procedures.ts b/apps/server/src/routers/lambda/connector/procedures.tsindex 7682a7619b3..f1e94e97def 100644--- a/apps/server/src/routers/lambda/connector/procedures.ts+++ b/apps/server/src/routers/lambda/connector/procedures.ts@@ -4,6 +4,7 @@ import {} from '@/business/server/trpc-middlewares/workspaceAuth';import { AgentModel } from '@/database/models/agent';import { ConnectorModel } from '@/database/models/connector';+import { ConnectorLinkModel } from '@/database/models/connectorLink';import { ConnectorToolModel } from '@/database/models/connectorTool';import { PluginModel } from '@/database/models/plugin';import { serverDatabase } from '@/libs/trpc/lambda/middleware';@@ -17,6 +18,7 @@ export const connectorProcedure = wsCompatProcedure.use(serverDatabase).use(asynreturn opts.next({ctx: {agentModel: new AgentModel(ctx.serverDB, ctx.userId, wsId),+ connectorLinkModel: new ConnectorLinkModel(ctx.serverDB, ctx.userId, wsId, gateKeeper),connectorModel: new ConnectorModel(ctx.serverDB, ctx.userId, wsId, gateKeeper),connectorToolModel: new ConnectorToolModel(ctx.serverDB, ctx.userId, wsId),pluginModel: new PluginModel(ctx.serverDB, ctx.userId, wsId),diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.connectorTokenRefresh.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.connectorTokenRefresh.test.tsindex a7792b1f10b..dc73da91ba9 100644--- a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.connectorTokenRefresh.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.connectorTokenRefresh.test.ts@@ -1,6 +1,6 @@import { describe, expect, it, vi } from 'vitest';-import { refreshExpiredConnectorTokens } from '@/server/services/connector/tokens';+import { refreshExpiredLinkTokens } from '@/server/services/connector/tokens';import { discoverTools } from '../toolDiscovery';@@ -29,8 +29,32 @@ vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({KeyVaultsGateKeeper: { initWithEnvKey: vi.fn().mockResolvedValue({}) },}));vi.mock('@/server/services/connector/tokens', () => ({- refreshExpiredConnectorTokens: vi.fn(async (connectors: any[]) =>- connectors.map((c) => ({ ...c, credentials: { accessToken: 'fresh', type: 'oauth2' } })),+ refreshExpiredConnectorTokens: vi.fn(async (connectors: any[]) => connectors),+ refreshExpiredLinkTokens: vi.fn(async (_connector: unknown, links: any[]) =>+ links.map((link) => ({ ...link, credentials: { accessToken: 'fresh', type: 'oauth2' } })),+ ),+}));+// The OAuth token lives on the connector's account, read through the link+// storage; stand that in so the bare runtime needs no database.+vi.mock('@/server/services/connector/links', async (original) => ({+ ...(await original<object>()),+ getConnectorLinkModel: vi.fn().mockReturnValue({}),+ loadConnectorLinksMap: vi.fn(+ async (connectors: { id: string }[]) =>+ new Map(+ connectors.map((connector) => [+ connector.id,+ [+ {+ credentials: { accessToken: 'expired', type: 'oauth2' },+ id: 'lnk_xmind',+ name: 'Default',+ status: 'connected',+ userConnectorId: connector.id,+ },+ ],+ ]),+ ),),}));vi.mock('@/server/services/deviceGateway', () => ({@@ -40,7 +64,7 @@ vi.mock('@/server/services/deviceGateway', () => ({const XMIND = 'xmind-mcp';const oauthConnector = {- credentials: { accessToken: 'expired', type: 'oauth2' },+ credentials: null,id: 'conn-xmind',identifier: XMIND,isEnabled: true,@@ -48,6 +72,7 @@ const oauthConnector = {mcpServerUrl: 'https://app.xmind.com/api/mcp',metadata: {},name: 'XMind',+ oidcConfig: { clientId: 'client', scheme: 'dcr' },};const connectorTools = [@@ -109,13 +134,13 @@ const run = (plugins: string[]) =>const manifestToken = (manifest: unknown) =>(manifest as { mcpParams?: { auth?: { accessToken?: string } } })?.mcpParams?.auth?.accessToken;-// Manifests carry the connector token for the whole run, so an-// expired-but-refreshable token used to 401 on the first call after expiry.+// A single-account manifest carries that account's token for the whole run, so+// an expired-but-refreshable token used to 401 on the first call after expiry.describe('discoverTools — connector OAuth token refresh', () => {it('builds a pinned connector manifest from refreshed credentials', async () => {const result = await run([XMIND]);- expect(refreshExpiredConnectorTokens).toHaveBeenCalled();+ expect(refreshExpiredLinkTokens).toHaveBeenCalled();expect(manifestToken(result.toolManifestMap[XMIND])).toBe('fresh');});diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/connectors.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/connectors.tsindex 97abbddba22..78cb25c16f6 100644--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/connectors.ts+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/connectors.ts@@ -37,9 +37,23 @@ const log = debug('lobe-server:ai-agent-service');export const buildOwnershipNote = async (deps: ToolDiscoveryDeps,connectors: DecryptedConnector[],+ anonymous = false,): Promise<string | undefined> => {try {- const borrowed = collectBorrowedConnectors(connectors, deps.userId!);+ const borrowed = collectBorrowedConnectors(+ connectors.filter((c) => !c.links?.length),+ deps.userId!,+ );+ for (const connector of connectors) {+ for (const [index, link] of (connector.links ?? []).entries()) {+ if (!link.userId || link.userId === deps.userId) continue;+ borrowed.push({+ authorizerId: link.userId,+ identifier: connector.identifier,+ name: `${connector.name} (${anonymous ? `Account ${index + 1}` : link.name})`,+ });+ }+ }if (borrowed.length > 0) {const displayMap = await resolveUserDisplayMap(deps.db,diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.tsindex 4cc6ecb18d4..21230a0d765 100644--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts@@ -295,7 +295,11 @@ export const discoverTools = async (// 5a-1b. Model awareness: tell the model whose connected account each// borrowed tool runs on (see `buildOwnershipNote`).- connectorOwnershipNote = await buildOwnershipNote(deps, connectors);+ connectorOwnershipNote = await buildOwnershipNote(+ deps,+ connectors.map((c) => connectorsMcp.find((mcp) => mcp.id === c.id) ?? c),+ !!shareGate,+ );connectorManifests = [...buildConnectorManifests(diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.connectorLinks.test.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.connectorLinks.test.tsnew file mode 100644index 00000000000..4c8c79d4a7c--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.connectorLinks.test.ts@@ -0,0 +1,96 @@+// @vitest-environment node+import { afterEach, describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { ConnectorModel } from '@/database/models/connector';+import { ConnectorToolModel } from '@/database/models/connectorTool';+import { users } from '@/database/schemas';+import { startOAuthMcpServer } from '@/libs/mcp/__tests__/fixtures/oauthMcpServer';+import { buildConnectorManifests } from '@/libs/mcp/buildConnectorManifests';++import { startToolReads } from './reads';++const vault = vi.hoisted(() => ({+ encrypt: async (s: string) => `enc:${s}`,+ decrypt: async (s: string) => ({ plaintext: s.replace(/^enc:/, '') }),+}));+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({+ KeyVaultsGateKeeper: { initWithEnvKey: async () => vault },+}));+vi.mock('@/server/services/deviceGateway', () => ({ deviceGateway: { isConfigured: false } }));+const db = await getTestDB();+const model = new ConnectorModel(db, 'read-links', undefined, vault);+const toolModel = new ConnectorToolModel(db, 'read-links');+afterEach(async () => {+ await db.delete(users);+ vi.unstubAllEnvs();+});++describe('server discovery account credentials and visitor privacy', () => {+ it.each([false, true])(+ 'keeps multiple tokens out of the run and does not pre-refresh (visitor=%s)',+ async (visitor) => {+ vi.stubEnv('SSRF_ALLOW_PRIVATE_IP_ADDRESS', '1');+ const fixture = await startOAuthMcpServer();+ try {+ await db.insert(users).values({ id: 'read-links' });+ const row = await model.create({+ identifier: 'multi',+ name: 'Multi',+ sourceType: 'custom',+ isEnabled: true,+ status: 'connected',+ mcpConnectionType: 'http',+ mcpServerUrl: `${fixture.base}/mcp`,+ oidcConfig: { clientId: 'fixture-client', scheme: 'dcr', issuer: fixture.base },+ });+ for (const account of ['alice', 'bob'])+ await model.getLinkModel().applyAuthorization(row.id, {+ target: { kind: 'new' },+ authorizerId: 'read-links',+ credentials: {+ type: 'oauth2',+ accessToken: `tok-${account}-expired`,+ refreshToken: `refresh-${account}-test`,+ expiresAt: 1,+ },+ identity: { profile: { email: `${account}@private.example` } },+ });+ await toolModel.upsertMany(row.id, [+ { toolName: 'echo', crudType: 'read', inputSchema: { type: 'object' } },+ ]);+ const reads = startToolReads(+ {+ db,+ userId: 'read-links',+ connectorModel: model,+ connectorToolModel: toolModel,+ pluginModel: { query: async () => [] },+ agentDocumentsService: { hasDocuments: async () => false },+ composioService: { getComposioManifests: async () => [] },+ getMarketService: async () => ({ getLobehubSkillManifests: async () => [] }),+ } as any,+ {+ candidateIds: ['multi'],+ resolvedAgentId: 'agent',+ agentConfig: {},+ isGoalTurn: true,+ topicId: '',+ shareGate: visitor ? {} : undefined,+ } as any,+ );+ const result = await reads.connectors;+ expect(result.connectorsMcp[0].credentials).toBeNull();+ expect(JSON.stringify(result.connectorsMcp)).not.toContain('tok-alice');+ expect(fixture.refreshes).toEqual([]);+ const manifest = buildConnectorManifests(result.connectorsMcp, result.connectorTools)[0];+ expect(manifest.api[0].parameters.required).toContain('link_id');+ expect((manifest as any).mcpParams.auth).toBeUndefined();+ expect(JSON.stringify(manifest)).toContain(visitor ? 'Account 1' : '[email protected]');+ if (visitor) expect(JSON.stringify(manifest)).not.toContain('@private.example');+ } finally {+ await fixture.close();+ }+ },+ );+});diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.tsindex a38601150ea..9cd5079e954 100644--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts@@ -5,6 +5,7 @@ import { FILE_PREVIEW_CHARS, isOversizedFileContent } from '@lobechat/prompts';import type { FrozenCredentialFacts } from '@lobechat/types';import { agentShareFileAccessScope, ordinaryFileAccessScope } from '@lobechat/types';import debug from 'debug';+import pMap from 'p-map';import { AgentAccountModel } from '@/database/models/agentAccount';import { ConnectorModel, type DecryptedConnector } from '@/database/models/connector';@@ -13,7 +14,16 @@ import { FileModel } from '@/database/models/file';import type { UserConnectorToolItem } from '@/database/schemas';import { buildConnectorManifests } from '@/libs/mcp/buildConnectorManifests';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';-import { refreshExpiredConnectorTokens } from '@/server/services/connector/tokens';+import {+ getConnectorLinkModel,+ loadConnectorLinksMap,+ pickPrimaryLink,+ withLinkCredentials,+} from '@/server/services/connector/links';+import {+ refreshExpiredConnectorTokens,+ refreshExpiredLinkTokens,+} from '@/server/services/connector/tokens';import { deviceGateway } from '@/server/services/deviceGateway';import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';import { isMcpAppsEnabled } from '@/server/services/mcp/featureGate';@@ -99,6 +109,9 @@ export const readCredentialFacts = async (}};+/** Connectors refreshed at once; each refresh may call its authorization server. */+const CONNECTOR_REFRESH_CONCURRENCY = 5;+/*** Manifests carry each connector's access token for the whole run, so refresh* expired OAuth tokens first. Rotated credentials are persisted encrypted,@@ -109,12 +122,36 @@ const refreshConnectorTokens = async (gateKeeper: KeyVaultsGateKeeper | undefined,connectors: DecryptedConnector[],onTimeout: () => void,+ anonymous = false,): Promise<DecryptedConnector[]> => {if (!gateKeeper || connectors.length === 0) return connectors;- return refreshExpiredConnectorTokens(+ const model = new ConnectorModel(deps.db, deps.userId, deps.workspaceId, gateKeeper);+ const linksContext = { connectorModel: model };+ const map = await loadConnectorLinksMap(connectors, linksContext);+ return pMap(connectors,- new ConnectorModel(deps.db, deps.userId, deps.workspaceId, gateKeeper),- { onTimeout },+ async (connector) => {+ const links = map.get(connector.id) ?? [];+ const choices = links.map(({ id, name, userId }, index) => ({+ id,+ name: anonymous ? `Account ${index + 1}` : name,+ userId,+ }));+ if (links.length > 1) return { ...connector, credentials: null, links: choices };+ const primary = pickPrimaryLink(links);+ if (primary) {+ const [fresh] = await refreshExpiredLinkTokens(+ connector,+ [primary],+ getConnectorLinkModel(linksContext),+ model,+ { onTimeout },+ );+ return { ...withLinkCredentials(connector, fresh), links: choices };+ }+ return (await refreshExpiredConnectorTokens([connector], model, { onTimeout }))[0];+ },+ { concurrency: CONNECTOR_REFRESH_CONCURRENCY },);};@@ -168,6 +205,7 @@ const readConnectors = async (connectorGateKeeper,connectors.filter(hasCallableMcpEndpoint),onRefreshTimeout,+ !!ctx.shareGate,);// Fetch ALL tools for all real-MCP connectors (including disabled tools) so that@@ -253,6 +291,7 @@ const readDiscoverableConnectors = async (gateKeeper,connectorsMcp,onRefreshTimeout,+ !!ctx.shareGate,);return {connectorsMcp: refreshed,diff --git a/apps/server/src/services/connector/__tests__/multiAccount.integration.test.ts b/apps/server/src/services/connector/__tests__/multiAccount.integration.test.tsnew file mode 100644index 00000000000..bb480f2a918--- /dev/null+++ b/apps/server/src/services/connector/__tests__/multiAccount.integration.test.ts@@ -0,0 +1,214 @@+// @vitest-environment node+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { ConnectorModel } from '@/database/models/connector';+import { ConnectorToolModel } from '@/database/models/connectorTool';+import { users } from '@/database/schemas';+import { startOAuthMcpServer } from '@/libs/mcp/__tests__/fixtures/oauthMcpServer';+import { buildConnectorManifests } from '@/libs/mcp/buildConnectorManifests';++import { callConnectorToolById } from '../exec';+import { resolveLinkIdentity } from '../identity';+import { loadConnectorLinksMap } from '../links';+import {+ buildAuthorizationUrl,+ discoverConnectorOAuth,+ exchangeConnectorCode,+ resolveConnectorClient,+ resolveConnectorOAuthScopes,+ toClientInformation,+} from '../oauth';+import { syncConnectorToolsById } from '../sync';+import { tokensToCredentials } from '../tokens';++vi.mock('@/server/services/mcp/featureGate', () => ({ isMcpAppsEnabled: async () => false }));+vi.mock('../refresh', () => ({+ scheduleStaleConnectorToolsRefresh: () => {},+ buildLastSyncedAtMap: () => new Map(),+}));+const db = await getTestDB();+const vault = {+ encrypt: async (s: string) => `enc:${s}`,+ decrypt: async (s: string) => ({ plaintext: s.replace(/^enc:/, '') }),+};+const model = new ConnectorModel(db, 'account-e2e', undefined, vault);+const linkModel = model.getLinkModel();+const toolModel = new ConnectorToolModel(db, 'account-e2e');+const ctx = {+ connectorModel: model,+ connectorLinkModel: linkModel,+ connectorToolModel: toolModel,+ agentModel: { existsById: async () => true },+ serverDB: undefined,+ userId: 'account-e2e',+};+beforeAll(() => {+ vi.stubEnv('SSRF_ALLOW_PRIVATE_IP_ADDRESS', '1');+});+afterAll(() => {+ vi.unstubAllEnvs();+});+afterEach(async () => {+ await db.delete(users);+});++describe('OAuth account routing over real HTTP and database', () => {+ it.each(['idtoken', 'userinfo', 'none'] as const)(+ 'authorizes and routes two accounts (%s)',+ async (variant) => {+ const fixture = await startOAuthMcpServer(variant);+ try {+ await db.insert(users).values({ id: 'account-e2e' });+ const row = await model.create({+ identifier: 'account-fixture',+ name: 'Accounts',+ sourceType: 'custom',+ mcpConnectionType: 'http',+ mcpServerUrl: `${fixture.base}/mcp`,+ status: 'disconnected',+ });+ const discovery = await discoverConnectorOAuth(`${fixture.base}/mcp`);+ const scopes = resolveConnectorOAuthScopes({ discovery });+ const redirectUri = 'http://localhost/callback';+ const client = await resolveConnectorClient({+ authorizationServerUrl: discovery.authorizationServerUrl,+ existing: { scheme: 'dcr' },+ metadata: discovery.metadata,+ redirectUri,+ scopes,+ });+ const oidc = { ...client, issuer: discovery.authorizationServerUrl, redirectUri, scopes };+ await model.update(row.id, { oidcConfig: oidc });+ const authorize = async (account: string) => {+ const { authorizationUrl, codeVerifier } = await buildAuthorizationUrl({+ authorizationServerUrl: fixture.base,+ clientInformation: toClientInformation(oidc),+ metadata: discovery.metadata,+ redirectUri,+ scopes,+ state: 'fixture-state',+ prompt: 'select_account',+ });+ const url = new URL(authorizationUrl);+ url.searchParams.set('account', account);+ const response = await fetch(url, { redirect: 'manual' });+ const callback = new URL(response.headers.get('location')!);+ const { tokens } = await exchangeConnectorCode({+ authorizationCode: callback.searchParams.get('code')!,+ authorizationServerUrl: fixture.base,+ clientInformation: toClientInformation(oidc),+ codeVerifier,+ metadata: discovery.metadata,+ redirectUri,+ iss: fixture.base,+ });+ const { credentials } = tokensToCredentials(tokens);+ if (credentials.type !== 'oauth2') throw new Error('Expected OAuth credentials');+ return linkModel.applyAuthorization(row.id, {+ authorizerId: 'account-e2e',+ target: { kind: 'new' },+ credentials,+ identity: await resolveLinkIdentity({ tokens, metadata: discovery.metadata }),+ });+ };+ const alice = await authorize('alice');+ await syncConnectorToolsById(row.id, ctx, { linkId: alice.linkId });+ let connector = (await model.findById(row.id))!;+ let links = (await loadConnectorLinksMap([connector], ctx)).get(row.id)!;+ const tools = await toolModel.queryByConnector(row.id);+ expect(+ buildConnectorManifests([{ ...connector, links }], tools)[0].api[0].parameters.required,+ ).toBeUndefined();+ const bob = await authorize('bob');+ connector = (await model.findById(row.id))!;+ links = (await loadConnectorLinksMap([connector], ctx)).get(row.id)!;+ expect(links.map((link) => link.name)).toEqual(+ variant === 'none' ? ['Default', 'Account 2'] : ['[email protected]', '[email protected]'],+ );+ const manifest = buildConnectorManifests([{ ...connector, links }], tools)[0];+ expect(manifest.api.every((tool) => tool.parameters.required?.includes('link_id'))).toBe(+ true,+ );+ expect(+ (manifest as unknown as { mcpParams: { auth?: unknown } }).mcpParams.auth,+ ).toBeUndefined();+ if (variant !== 'none') {+ expect((await authorize('bob')).outcome).toBe('matchedExisting');+ expect(await linkModel.listByConnectorIds([row.id])).toHaveLength(2);+ }+ await callConnectorToolById(+ {+ identifier: row.identifier,+ toolName: 'echo_args',+ args: JSON.stringify({ link_id: bob.linkId, x: 1 }),+ },+ ctx,+ );+ expect(fixture.requests.at(-1)).toMatchObject({+ authorization: expect.stringMatching(/^Bearer tok-bob-/),+ arguments: { x: 1 },+ });+ expect(fixture.requests.at(-1)!.arguments).not.toHaveProperty('link_id');+ expect(+ await callConnectorToolById({ identifier: row.identifier, toolName: 'whoami' }, ctx),+ ).toMatchObject({+ success: false,+ content: expect.stringContaining('link_id is required'),+ // The chat shows a failed tool card only when `error` is set.+ error: {+ type: 'CONNECTOR_ACCOUNT_SELECTION',+ message: expect.stringContaining('link_id is required'),+ },+ state: { isError: true },+ });+ expect(+ await callConnectorToolById(+ { identifier: row.identifier, toolName: 'whoami', args: '{"link_id":"invalid"}' },+ ctx,+ ),+ ).toMatchObject({+ success: false,+ content: expect.stringContaining('no longer exists'),+ error: { type: 'CONNECTOR_ACCOUNT_SELECTION' },+ state: { isError: true },+ });+ await linkModel.updateCredentials(row.id, bob.linkId, {+ ...(await linkModel.findById(row.id, bob.linkId))!.credentials,+ expiresAt: 1,+ });+ await callConnectorToolById(+ {+ identifier: row.identifier,+ toolName: 'whoami',+ args: JSON.stringify({ link_id: bob.linkId }),+ },+ ctx,+ );+ expect(fixture.refreshes).toHaveLength(1);+ expect(fixture.refreshes[0]).toMatch(/^refresh-bob-/);+ const legacy = await model.create({+ identifier: 'legacy',+ name: 'Legacy',+ sourceType: 'custom',+ status: 'connected',+ credentials: JSON.stringify({ type: 'oauth2', accessToken: 'tok-alice-legacy' }),+ });+ // A token written before accounts existed reads as one account, unchanged+ const [legacyLink] =+ (await loadConnectorLinksMap([(await model.findById(legacy.id))!], ctx)).get(legacy.id) ??+ [];+ expect(legacyLink).toMatchObject({+ credentials: { accessToken: 'tok-alice-legacy' },+ name: 'Default',+ });+ expect((await model.findById(legacy.id))!.credentials).toMatchObject({+ accessToken: 'tok-alice-legacy',+ });+ } finally {+ await fixture.close();+ }+ },+ 120_000,+ );+});diff --git a/apps/server/src/services/connector/exec.boundDevice.test.ts b/apps/server/src/services/connector/exec.boundDevice.test.tsindex ea8497e9496..4a2b50052c2 100644--- a/apps/server/src/services/connector/exec.boundDevice.test.ts+++ b/apps/server/src/services/connector/exec.boundDevice.test.ts@@ -21,7 +21,10 @@ vi.mock('@/server/services/mcp/deviceTunnel', async (importOriginal) => ({vi.mock('@/server/services/mcp/featureGate', () => ({isMcpAppsEnabled: vi.fn().mockResolvedValue(false),}));-vi.mock('./tokens', () => ({ ensureFreshConnectorToken: vi.fn(async (c) => c) }));+vi.mock('./tokens', () => ({+ ensureFreshConnectorToken: vi.fn(async (c) => c),+ ensureFreshLinkToken: vi.fn(async (_c, link) => link),+}));vi.mock('./refresh', () => ({buildLastSyncedAtMap: vi.fn(() => new Map()),scheduleStaleConnectorToolsRefresh: vi.fn(),@@ -43,10 +46,13 @@ const stdioConnector = (metadata: Record<string, unknown> | null, workspaceId?:workspaceId: workspaceId ?? null,}) as any;-const makeCtx = (connector: any) =>+const makeCtx = (connector: any, links: any[] = []) =>({agentModel: { existsById: vi.fn().mockResolvedValue(true) },- connectorModel: { queryByIdentifiers: vi.fn().mockResolvedValue([connector]) },+ connectorModel: {+ getLinkModel: () => ({ listByConnectorIds: vi.fn().mockResolvedValue(links) }),+ queryByIdentifiers: vi.fn().mockResolvedValue([connector]),+ },connectorToolModel: {queryByConnector: vi.fn()@@ -62,6 +68,22 @@ const call = (connector: any, over: Record<string, unknown> = {}) =>makeCtx(connector),);+const oauthAccount = (id: string, accessToken: string) => ({+ credentials: { accessToken, type: 'oauth2' },+ id,+ name: id,+ status: 'connected',+ userConnectorId: 'c1',+ userId: 'u1',+});+const lanOAuthConnector = {+ ...stdioConnector({ boundDeviceId: 'ws-nas' }, 'ws1'),+ mcpConnectionType: 'http',+ mcpServerUrl: 'http://192.168.1.5/mcp',+ mcpStdioConfig: null,+ oidcConfig: { clientId: 'client', scheme: 'dcr' },+};+describe('callConnectorToolById — connector bound to a device', () => {beforeEach(() => {vi.clearAllMocks();@@ -109,6 +131,38 @@ describe('callConnectorToolById — connector bound to a device', () => {expect(mcpService.callTool).not.toHaveBeenCalled();});+ it("sends the selected account's token and the arguments without the selector", async () => {+ const links = [oauthAccount('lnk_a', 'alice-token'), oauthAccount('lnk_b', 'bob-token')];+ await callConnectorToolById(+ { args: '{"link_id":"lnk_b","q":1}', identifier: 'local-tool', toolName: 'do_thing' },+ makeCtx(lanOAuthConnector, links),+ );++ expect(deviceGateway.executeMcpCall).toHaveBeenCalledWith(+ expect.objectContaining({+ arguments: '{"q":1}',+ params: expect.objectContaining({+ auth: { accessToken: 'bob-token', type: 'oauth2' },+ type: 'http',+ }),+ }),+ );+ });++ it('fails a call that names no account of a connector holding several', async () => {+ const links = [oauthAccount('lnk_a', 'alice-token'), oauthAccount('lnk_b', 'bob-token')];+ await expect(+ callConnectorToolById(+ { args: '{"q":1}', identifier: 'local-tool', toolName: 'do_thing' },+ makeCtx(lanOAuthConnector, links),+ ),+ ).resolves.toMatchObject({+ error: { type: 'CONNECTOR_ACCOUNT_SELECTION' },+ success: false,+ });+ expect(deviceGateway.executeMcpCall).not.toHaveBeenCalled();+ });+it("keeps a failure's error marker and details from the device", async () => {vi.mocked(deviceGateway.executeMcpCall).mockResolvedValue({content: 'Device call timed out',diff --git a/apps/server/src/services/connector/exec.test.ts b/apps/server/src/services/connector/exec.test.tsindex 037ce53fd05..65cb5aabaf1 100644--- a/apps/server/src/services/connector/exec.test.ts+++ b/apps/server/src/services/connector/exec.test.ts@@ -57,6 +57,7 @@ const makeCtx = (connectors: any[], tools: any[], { agentVisible = true } = {})({agentModel: { existsById: vi.fn().mockResolvedValue(agentVisible) },connectorModel: {+ getLinkModel: () => ({ listByConnectorIds: async () => [] }),queryByIdentifiers: vi.fn().mockResolvedValue(connectors),resolveByIdentifiers: vi.fn().mockResolvedValue(connectors),},diff --git a/apps/server/src/services/connector/exec.ts b/apps/server/src/services/connector/exec.tsindex 93ad77863ef..3f85b4de900 100644--- a/apps/server/src/services/connector/exec.ts+++ b/apps/server/src/services/connector/exec.ts@@ -24,7 +24,12 @@ import {toGatewayMcpParams,} from '@/server/services/mcp/deviceTunnel';import { isMcpAppsEnabled } from '@/server/services/mcp/featureGate';+import {+ buildMcpAuthorizationErrorContent,+ isMcpAuthorizationError,+} from '@/server/services/toolExecution/mcpAuthError';+import { ConnectorLinkSelectionError, resolveLinkedCall } from './links';import { buildLastSyncedAtMap, scheduleStaleConnectorToolsRefresh } from './refresh';import { buildConnectorMcpParams, type ConnectorToolSyncContext } from './sync';import { ensureFreshConnectorToken } from './tokens';@@ -163,6 +168,18 @@ const reachesServer = async ();};+/**+ * A failed call in the shape the chat stores as a tool error. The model reads+ * `content`; the tool card shows a failure only when `error` is set, so a bare+ * `success: false` would render as a successful call.+ */+const failedToolResult = (message: string, type: string) => ({+ content: message,+ error: { message, type },+ state: { content: [{ text: message, type: 'text' as const }], isError: true },+ success: false,+});+export const callConnectorToolById = async (params: {agentId?: string;@@ -170,6 +187,7 @@ export const callConnectorToolById = async (/** An MCP App view's `tools/call`: only tools visible to the app run. */fromApp?: boolean;fromEntrypoint?: boolean;+ linkId?: string;identifier: string;/** With `fromApp`: the server the view came from; its calls reach no other. */server?: string;@@ -271,7 +289,12 @@ export const callConnectorToolById = async (// call is refused: a device's result offers no view to call back into.const binding = connectorDeviceBinding(connector);if (binding && deviceGateway.isConfigured && !params.fromApp && !params.fromEntrypoint) {- return runConnectorToolOnBoundDevice(connector, binding, { ...params, mcpApps }, ctx);+ return runConnectorToolOnBoundDevice(+ connector,+ binding,+ { ...params, mcpApps, schemas: tools.map((t) => t.inputSchema) },+ ctx,+ );}throw new ConnectorToolCallError('BAD_REQUEST',@@ -281,7 +304,7 @@ export const callConnectorToolById = async (}const report = await resolveReporter(connector, ctx);- const run = { ...params, mcpApps };+ const run = { ...params, mcpApps, schemas: tools.map((t) => t.inputSchema) };if (!report) return runConnectorTool(connector, run, ctx);const startTime = Date.now();@@ -330,11 +353,52 @@ const installedVersion = (metadata: unknown): string | undefined => {return typeof version === 'string' ? version : undefined;};+interface ConnectorCallAccount {+ args?: string;+ fromApp?: boolean;+ linkId?: string;+ /** Input schemas of the connector's synced tools: they decide the selector's name. */+ schemas: readonly unknown[];+}++/**+ * The credentials and arguments a call runs with: the selected account's, the+ * selector stripped from the arguments, or the connector's own credentials. A+ * selection the model got wrong comes back as a failed tool result it can fix.+ */+const resolveCallAccount = async (+ connector: DecryptedConnector,+ params: ConnectorCallAccount,+ ctx: ConnectorExecContext,+): Promise<+ | { argsStr: string; failure?: undefined; fresh: DecryptedConnector; linkName?: string }+ | { failure: ReturnType<typeof failedToolResult> }+> => {+ try {+ const resolved = await resolveLinkedCall(+ {+ connector,+ argsStr: params.args,+ linkId: params.linkId,+ fromApp: params.fromApp,+ schemas: params.schemas,+ },+ ctx,+ );+ const fresh = resolved.linkId+ ? resolved.connector+ : await ensureFreshConnectorToken(connector, ctx.connectorModel);+ return { argsStr: resolved.argsStr, fresh, linkName: resolved.linkName };+ } catch (error) {+ if (error instanceof ConnectorLinkSelectionError)+ return { failure: failedToolResult(error.message, 'CONNECTOR_ACCOUNT_SELECTION') };+ throw error;+ }+};+const runConnectorTool = async (connector: DecryptedConnector,- params: {- args?: string;- fromApp?: boolean;+ params: ConnectorCallAccount & {fromEntrypoint?: boolean;/** The caller's `mcp_apps` flag, as the call's checks read it. */mcpApps: boolean;@@ -358,21 +422,34 @@ const runConnectorTool = async ();}- const fresh = await ensureFreshConnectorToken(connector, ctx.connectorModel);+ const account = await resolveCallAccount(connector, params, ctx);+ if (account.failure) return account.failure;// A view's call gets its blocks back as they are (`mcpService.callTool`)const fileService = params.fromApp ? undefined : ctx.resolveFileService?.();- return mcpService.callTool({- argsStr: params.args ?? '{}',- clientParams: buildConnectorMcpParams(fresh),- fromApp: params.fromApp,- fromEntrypoint: params.fromEntrypoint,- mcpApps: params.mcpApps,- processContentBlocks: fileService- ? (blocks) => processContentBlocks(blocks, fileService)- : undefined,- toolName: params.toolName,- });+ try {+ return await mcpService.callTool({+ argsStr: account.argsStr,+ clientParams: buildConnectorMcpParams(account.fresh),+ fromApp: params.fromApp,+ fromEntrypoint: params.fromEntrypoint,+ mcpApps: params.mcpApps,+ processContentBlocks: fileService+ ? (blocks) => processContentBlocks(blocks, fileService)+ : undefined,+ toolName: params.toolName,+ });+ } catch (error) {+ if (isMcpAuthorizationError(error))+ return failedToolResult(+ buildMcpAuthorizationErrorContent(connector.identifier, {+ isShareVisitor: false,+ linkName: account.linkName,+ }),+ 'AUTHORIZATION_ERROR',+ );+ throw error;+ }};/**@@ -384,7 +461,7 @@ const runConnectorTool = async (const runConnectorToolOnBoundDevice = async (connector: DecryptedConnector,binding: McpDeviceBinding,- params: { args?: string; mcpApps: boolean; toolName: string },+ params: ConnectorCallAccount & { mcpApps: boolean; toolName: string },ctx: ConnectorExecContext,): Promise<unknown> => {if (!ctx.serverDB || !ctx.userId) {@@ -409,14 +486,15 @@ const runConnectorToolOnBoundDevice = async (throw error;}- const fresh = await ensureFreshConnectorToken(connector, ctx.connectorModel);+ const account = await resolveCallAccount(connector, params, ctx);+ if (account.failure) return account.failure;const result = await deviceGateway.executeMcpCall({apiName: params.toolName,- arguments: params.args ?? '{}',+ arguments: account.argsStr,clientKinds: target.clientKinds,deviceId: target.deviceId,identifier: connector.identifier,- params: toGatewayMcpParams(buildConnectorMcpParams(fresh)),+ params: toGatewayMcpParams(buildConnectorMcpParams(account.fresh)),userId: ctx.userId,workspaceId: target.workspaceId,});@@ -446,7 +524,7 @@ const runConnectorToolOnBoundDevice = async (*/export const readConnectorUiResourceById = async (/** `server`: the server the result came from; the view is read from no other. */- params: { agentId?: string; identifier: string; server: string; uri: string },+ params: { agentId?: string; identifier: string; server: string; uri: string; linkId?: string },ctx: ConnectorExecContext,) => {if (!(await isMcpAppsEnabled(ctx.userId))) {@@ -493,7 +571,13 @@ export const readConnectorUiResourceById = async ();}- const fresh = await ensureFreshConnectorToken(connector, ctx.connectorModel);+ const resolved = await resolveLinkedCall(+ { connector, linkId: params.linkId, fromApp: true },+ ctx,+ );+ const fresh = resolved.linkId+ ? resolved.connector+ : await ensureFreshConnectorToken(connector, ctx.connectorModel);return mcpService.readUiResource(buildConnectorMcpParams(fresh), params.uri);};diff --git a/apps/server/src/services/connector/identity.test.ts b/apps/server/src/services/connector/identity.test.tsnew file mode 100644index 00000000000..0c74258b134--- /dev/null+++ b/apps/server/src/services/connector/identity.test.ts@@ -0,0 +1,48 @@+import type { AuthorizationServerMetadata, OAuthTokens } from '@modelcontextprotocol/client';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { resolveLinkIdentity } from './identity';++const mocks = vi.hoisted(() => ({ fetch: vi.fn() }));+vi.mock('@lobechat/ssrf-safe-fetch', () => ({ ssrfSafeFetch: mocks.fetch }));+const metadata = {+ issuer: 'https://as.example',+ userinfo_endpoint: 'https://as.example/me',+} as AuthorizationServerMetadata;+const tokens = (extra: Record<string, unknown> = {}) =>+ ({ access_token: 'access', token_type: 'Bearer', ...extra }) as OAuthTokens;+afterEach(() => {+ vi.clearAllMocks();+});+describe('resolveLinkIdentity', () => {+ it('uses id token profile before userinfo, with issuer-scoped identity', async () => {+ const payload = Buffer.from(+ JSON.stringify({ sub: 'alice', email: '[email protected]', picture: 'https://avatar' }),+ ).toString('base64url');+ expect(+ await resolveLinkIdentity({+ metadata,+ tokens: tokens({ id_token: `header.${payload}.sig` }),+ }),+ ).toEqual({+ externalAccountId: '["https://as.example","alice"]',+ profile: { email: '[email protected]', avatar: 'https://avatar' },+ });+ expect(mocks.fetch).not.toHaveBeenCalled();+ });+ it('falls back to SSRF-safe userinfo and tolerates no identity', async () => {+ mocks.fetch.mockResolvedValueOnce(Response.json({ sub: 'bob', preferred_username: 'Bob' }));+ expect(+ await resolveLinkIdentity({ metadata, tokens: tokens({ id_token: 'malformed' }) }),+ ).toMatchObject({ profile: { username: 'Bob' } });+ expect(mocks.fetch.mock.calls[0][1].headers.Authorization).toBe('Bearer access');+ mocks.fetch.mockRejectedValueOnce(new Error('blocked'));+ expect(await resolveLinkIdentity({ metadata, tokens: tokens() })).toBeUndefined();+ expect(+ await resolveLinkIdentity({+ metadata: { issuer: 'https://as' } as AuthorizationServerMetadata,+ tokens: tokens(),+ }),+ ).toBeUndefined();+ });+});diff --git a/apps/server/src/services/connector/identity.ts b/apps/server/src/services/connector/identity.tsnew file mode 100644index 00000000000..72c0933637c--- /dev/null+++ b/apps/server/src/services/connector/identity.ts@@ -0,0 +1,58 @@+import { ssrfSafeFetch } from '@lobechat/ssrf-safe-fetch';+import { isRecord } from '@lobechat/utils/object';+import type { AuthorizationServerMetadata, OAuthTokens } from '@modelcontextprotocol/client';++import type { ConnectorLinkIdentity } from '@/database/models/connectorLink';++const identityFromClaims = (+ claims: unknown,+ issuer?: string,+): ConnectorLinkIdentity | undefined => {+ if (!isRecord(claims)) return;+ const string = (key: string) =>+ typeof claims[key] === 'string' ? (claims[key] as string) : undefined;+ const subject = string('sub');+ if (!subject) return;+ return {+ externalAccountId: JSON.stringify([issuer ?? string('iss') ?? '', subject]),+ profile: {+ avatar: string('picture'),+ email: string('email'),+ name: string('name'),+ username: string('preferred_username'),+ },+ };+};++/** Identity is best-effort display/deduplication data, never an authorization claim. */+export const resolveLinkIdentity = async ({+ tokens,+ metadata,+}: {+ tokens: OAuthTokens;+ metadata: AuthorizationServerMetadata;+}): Promise<ConnectorLinkIdentity | undefined> => {+ if (typeof tokens.id_token === 'string') {+ try {+ const identity = identityFromClaims(+ JSON.parse(Buffer.from(tokens.id_token.split('.')[1], 'base64url').toString()),+ metadata.issuer,+ );+ if (identity) return identity;+ } catch {+ /* A malformed ID token must not break successful OAuth. */+ }+ }+ const endpoint = metadata.userinfo_endpoint;+ if (typeof endpoint !== 'string') return;+ try {+ const response = await ssrfSafeFetch(endpoint, {+ headers: { Authorization: `Bearer ${tokens.access_token}` },+ signal: AbortSignal.timeout(5000),+ });+ if (!response.ok) return;+ return identityFromClaims(await response.json(), metadata.issuer);+ } catch {+ /* Identity discovery is optional and must never fail authorization. */+ }+};diff --git a/apps/server/src/services/connector/links.test.ts b/apps/server/src/services/connector/links.test.tsnew file mode 100644index 00000000000..bbcd3b7a8db--- /dev/null+++ b/apps/server/src/services/connector/links.test.ts@@ -0,0 +1,134 @@+import { describe, expect, it, vi } from 'vitest';++import type { DecryptedConnector } from '@/database/models/connector';+import type { ConnectorLinkModel, DecryptedConnectorLink } from '@/database/models/connectorLink';++import { loadConnectorLinksMap, pickPrimaryLink, resolveLinkedCall } from './links';+import { ensureFreshLinkToken } from './tokens';++vi.mock('./tokens', () => ({ ensureFreshLinkToken: vi.fn(async (_c, link) => link) }));+const connector = {+ id: 'c',+ credentials: null,+ oidcConfig: { clientId: 'client' },+} as DecryptedConnector;+const links = [+ {+ id: 'lnk_a',+ userConnectorId: 'c',+ name: '[email protected]',+ status: 'connected',+ credentials: { type: 'oauth2', accessToken: 'alice-token' },+ },+ {+ id: 'lnk_b',+ userConnectorId: 'c',+ name: 'Bob',+ status: 'error',+ credentials: { type: 'oauth2', accessToken: 'bob-token' },+ },+] as DecryptedConnectorLink[];+const context = (rows = links) => ({+ connectorModel: {} as never,+ connectorLinkModel: {+ listByConnectorIds: vi.fn().mockResolvedValue(rows),+ } as unknown as ConnectorLinkModel,+});++describe('resolveLinkedCall', () => {+ it('selects even an unhealthy account explicitly and strips the selector', async () => {+ const result = await resolveLinkedCall(+ { connector, argsStr: '{"link_id":"lnk_b","x":1}' },+ context(),+ );+ expect(result).toMatchObject({+ argsStr: '{"x":1}',+ linkId: 'lnk_b',+ connector: { credentials: { accessToken: 'bob-token' } },+ });+ expect(ensureFreshLinkToken).toHaveBeenLastCalledWith(+ connector,+ links[1],+ expect.anything(),+ expect.anything(),+ );+ });+ it('requires a selector by total count, lists current choices and hides names for visitors', async () => {+ await expect(resolveLinkedCall({ connector }, context())).rejects.toThrow(+ 'link_id is required',+ );+ await expect(resolveLinkedCall({ connector, linkId: 'gone' }, context())).rejects.toThrow(+ 'no longer exists',+ );+ await expect(resolveLinkedCall({ connector, isShareVisitor: true }, context())).rejects.toThrow(+ 'Account 1',+ );+ await expect(+ resolveLinkedCall({ connector, isShareVisitor: true }, context()),+ ).rejects.not.toThrow('[email protected]');+ });+ it('accepts the sole link without a selector, but validates any supplied one', async () => {+ expect((await resolveLinkedCall({ connector }, context(links.slice(0, 1)))).linkId).toBe(+ 'lnk_a',+ );+ await expect(+ resolveLinkedCall({ connector, linkId: 'lnk_b' }, context(links.slice(0, 1))),+ ).rejects.toThrow();+ await expect(resolveLinkedCall({ connector }, context([]))).rejects.toThrow(+ 'connect an account',+ );+ });+ it('preserves a business link_id with the collision-safe selector', async () => {+ const result = await resolveLinkedCall(+ {+ connector,+ schemas: [{ properties: { link_id: {} } }],+ argsStr: '{"connector_link_id":"lnk_b","link_id":"business"}',+ },+ context(),+ );+ expect(result.argsStr).toBe('{"link_id":"business"}');+ });+ it('does no storage IO for an empty inventory and picks the earliest healthy primary', async () => {+ expect(await loadConnectorLinksMap([], context())).toEqual(new Map());+ expect(pickPrimaryLink([links[1], links[0]])).toBe(links[0]);+ });+ it('reads accounts only for OAuth connectors, including a legacy OAuth token, never for evaluation mocks', async () => {+ const bearer = {+ id: 'static',+ credentials: { type: 'bearer', token: 't' },+ oidcConfig: null,+ } as DecryptedConnector;+ const none = { id: 'open', credentials: null, oidcConfig: null } as DecryptedConnector;+ const ctx = context();+ expect(await loadConnectorLinksMap([bearer, none], ctx)).toEqual(new Map());+ expect(ctx.connectorLinkModel.listByConnectorIds).not.toHaveBeenCalled();++ const legacy = {+ id: 'legacy',+ credentials: { type: 'oauth2', accessToken: 'old' },+ oidcConfig: null,+ } as DecryptedConnector;+ const evalMock = {+ id: 'eval',+ credentials: { type: 'oauth2', accessToken: 'mock' },+ metadata: { agentEval: {} },+ oidcConfig: { clientId: 'client' },+ } as unknown as DecryptedConnector;+ await loadConnectorLinksMap([bearer, connector, legacy, evalMock], ctx);+ expect(ctx.connectorLinkModel.listByConnectorIds).toHaveBeenCalledWith(['c', 'legacy']);+ });+ it('binds interactive views to an explicit host-provided account', async () => {+ await expect(+ resolveLinkedCall({ connector, fromApp: true, argsStr: '{"link_id":"lnk_b"}' }, context()),+ ).rejects.toThrow('initiating tool call');+ expect(+ (+ await resolveLinkedCall(+ { connector, fromApp: true, linkId: 'lnk_b', argsStr: '{"x":1}' },+ context(),+ )+ ).linkId,+ ).toBe('lnk_b');+ });+});diff --git a/apps/server/src/services/connector/links.ts b/apps/server/src/services/connector/links.tsnew file mode 100644index 00000000000..3955a6aaa69--- /dev/null+++ b/apps/server/src/services/connector/links.ts@@ -0,0 +1,135 @@+import {+ resolveConnectorLinkParam,+ sanitizeConnectorPromptText,+ splitConnectorLinkArg,+} from '@lobechat/mecha';++import type { ConnectorModel, DecryptedConnector } from '@/database/models/connector';+import type { ConnectorLinkModel, DecryptedConnectorLink } from '@/database/models/connectorLink';++import { ensureFreshLinkToken } from './tokens';++export interface ConnectorLinksContext {+ connectorLinkModel?: ConnectorLinkModel;+ connectorModel: ConnectorModel;+}+export const getConnectorLinkModel = (ctx: ConnectorLinksContext) =>+ ctx.connectorLinkModel ?? ctx.connectorModel.getLinkModel();++/**+ * Accounts exist only for OAuth connectors: an authorization needs the+ * connector's OAuth client, and replacing OAuth with static credentials+ * removes both the client and the accounts. A single OAuth token written+ * before accounts existed reads as one account. Evaluation mocks keep their+ * single token.+ */+const mayHaveLinks = (connector: DecryptedConnector) =>+ !connector.metadata?.agentEval &&+ (!!connector.oidcConfig || connector.credentials?.type === 'oauth2');++export const loadConnectorLinksMap = async (+ connectors: DecryptedConnector[],+ ctx: ConnectorLinksContext,+): Promise<Map<string, DecryptedConnectorLink[]>> => {+ const map = new Map<string, DecryptedConnectorLink[]>();+ const candidates = connectors.filter(mayHaveLinks);+ if (!candidates.length) return map;+ const model = getConnectorLinkModel(ctx);+ for (const link of await model.listByConnectorIds(candidates.map((c) => c.id))) {+ const links = map.get(link.userConnectorId) ?? [];+ links.push(link);+ map.set(link.userConnectorId, links);+ }+ return map;+};+export const withLinkCredentials = (+ connector: DecryptedConnector,+ link: DecryptedConnectorLink,+): DecryptedConnector => ({+ ...connector,+ credentials: link.credentials,+ tokenExpiresAt: link.tokenExpiresAt,+});++export const pickPrimaryLink = <T extends { status: string }>(links: readonly T[]): T | undefined =>+ links.find((link) => link.status === 'connected') ?? links[0];++export class ConnectorLinkSelectionError extends Error {}++export const resolveLinkedCall = async (+ params: {+ connector: DecryptedConnector;+ argsStr?: string;+ linkId?: string;+ param?: string;+ schemas?: readonly unknown[];+ fromApp?: boolean;+ isShareVisitor?: boolean;+ },+ ctx: ConnectorLinksContext,+): Promise<{+ connector: DecryptedConnector;+ argsStr: string;+ linkId?: string;+ linkName?: string;+}> => {+ const { connector } = params;+ const links = (await loadConnectorLinksMap([connector], ctx)).get(connector.id) ?? [];+ if (!links.length) {+ if (+ params.linkId ||+ connector.links?.length ||+ (connector.oidcConfig && !connector.credentials)+ ) {+ throw new ConnectorLinkSelectionError(+ 'No connected accounts. Ask the user to connect an account in Settings > Connectors.',+ );+ }+ return { connector, argsStr: params.argsStr ?? '{}' };+ }+ const param = params.param ?? resolveConnectorLinkParam(params.schemas ?? []);+ if (params.fromApp && links.length > 1 && !params.linkId)+ throw new ConnectorLinkSelectionError(+ `${param} from the initiating tool call is required for this interactive view`,+ );+ let split;+ try {+ split = splitConnectorLinkArg(params.argsStr ?? '{}', param);+ } catch (error) {+ throw new ConnectorLinkSelectionError(+ error instanceof Error ? error.message : 'Invalid account selection',+ );+ }+ const linkId = params.linkId ?? split.linkId;+ if (params.linkId && split.linkId && params.linkId !== split.linkId)+ throw new ConnectorLinkSelectionError('Conflicting account selections');+ const choices = JSON.stringify(+ links.map((link, i) => ({+ link_id: link.id,+ link_name: params.isShareVisitor+ ? `Account ${i + 1}`+ : sanitizeConnectorPromptText(link.name),+ })),+ );+ if (!linkId && links.length > 1)+ throw new ConnectorLinkSelectionError(`${param} is required. Select an account: ${choices}`);+ const link = linkId ? links.find((l) => l.id === linkId) : links[0];+ if (!link)+ throw new ConnectorLinkSelectionError(+ `The selected account no longer exists. Current accounts: ${choices}`,+ );+ const fresh = await ensureFreshLinkToken(+ connector,+ link,+ getConnectorLinkModel(ctx),+ ctx.connectorModel,+ );+ return {+ connector: withLinkCredentials(connector, fresh),+ argsStr: split.argsStr,+ linkId: fresh.id,+ linkName: params.isShareVisitor+ ? `Account ${links.indexOf(link) + 1}`+ : sanitizeConnectorPromptText(fresh.name),+ };+};diff --git a/apps/server/src/services/connector/localCallToken.test.ts b/apps/server/src/services/connector/localCallToken.test.tsindex 4967246a17a..71fb7c3c9ad 100644--- a/apps/server/src/services/connector/localCallToken.test.ts+++ b/apps/server/src/services/connector/localCallToken.test.ts@@ -1,43 +1,64 @@import { beforeEach, describe, expect, it, vi } from 'vitest';import { getConnectorLocalCallToken } from './localCallToken';-import { ensureFreshConnectorToken } from './tokens';+import { ensureFreshLinkToken } from './tokens';-vi.mock('./tokens', () => ({ ensureFreshConnectorToken: vi.fn(async (connector) => connector) }));+vi.mock('./tokens', () => ({ ensureFreshLinkToken: vi.fn(async (_connector, link) => link) }));-const oauthConnector = {+const account = (id: string, accessToken: string, userId = 'u1') => ({credentials: {- accessToken: 'access',+ accessToken,clientSecret: 'never-leaves',refreshToken: 'never-leaves',type: 'oauth2',},+ id,+ name: id,+ status: 'connected',+ userConnectorId: 'c1',+ userId,+});++const oauthConnector = {+ credentials: null,id: 'c1',mcpConnectionType: 'http',mcpServerUrl: 'https://nas.tail1234.ts.net/mcp',metadata: { connectVia: 'device' },+ oidcConfig: { clientId: 'client', scheme: 'dcr' },userId: 'u1',};-const call = (connector: Record<string, unknown> | undefined, userId = 'u1') => {- const connectorModel = { findById: vi.fn().mockResolvedValue(connector) };- return getConnectorLocalCallToken({ connectorModel: connectorModel as never, userId }, 'c1');+const call = (+ connector: Record<string, unknown> | undefined,+ {+ links = [account('lnk_a', 'access')],+ linkId,+ userId = 'u1',+ }: { links?: ReturnType<typeof account>[]; linkId?: string; userId?: string } = {},+) => {+ const connectorModel = {+ findById: vi.fn().mockResolvedValue(connector),+ getLinkModel: () => ({ listByConnectorIds: vi.fn().mockResolvedValue(links) }),+ };+ return getConnectorLocalCallToken(+ { connectorModel: connectorModel as never, userId },+ 'c1',+ linkId,+ );};describe('getConnectorLocalCallToken', () => {beforeEach(() => vi.clearAllMocks());it("returns only a device-routed connector's access token, refreshed first when due", async () => {- vi.mocked(ensureFreshConnectorToken).mockResolvedValueOnce({- ...oauthConnector,- credentials: { ...oauthConnector.credentials, accessToken: 'refreshed' },- } as never);+ vi.mocked(ensureFreshLinkToken).mockResolvedValueOnce(account('lnk_a', 'refreshed') as never);await expect(call(oauthConnector)).resolves.toEqual({accessToken: 'refreshed',type: 'oauth2',});- expect(ensureFreshConnectorToken).toHaveBeenCalledOnce();+ expect(ensureFreshLinkToken).toHaveBeenCalledOnce();});it('returns the token for a localhost / LAN endpoint on automatic routing', async () => {@@ -46,24 +67,49 @@ describe('getConnectorLocalCallToken', () => {).resolves.toEqual({ accessToken: 'access', type: 'oauth2' });});+ it('returns the selected account of a connector holding several, its primary one otherwise', async () => {+ const links = [account('lnk_a', 'alice'), account('lnk_b', 'bob')];+ await expect(call(oauthConnector, { links, linkId: 'lnk_b' })).resolves.toEqual({+ accessToken: 'bob',+ type: 'oauth2',+ });+ await expect(call(oauthConnector, { links })).resolves.toEqual({+ accessToken: 'alice',+ type: 'oauth2',+ });+ await expect(call(oauthConnector, { links, linkId: 'lnk_gone' })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ });+// The server calls it itself: the token never needs to leave itit('returns nothing for a connector the server reaches itself', async () => {await expect(call({ ...oauthConnector, metadata: {} })).resolves.toBeNull();- expect(ensureFreshConnectorToken).not.toHaveBeenCalled();+ expect(ensureFreshLinkToken).not.toHaveBeenCalled();});- it('returns nothing for a connector without an OAuth token', async () => {+ it('returns nothing for a connector without an OAuth account', async () => {await expect(- call({ ...oauthConnector, credentials: { token: 't', type: 'bearer' } }),+ call(+ { ...oauthConnector, credentials: { token: 't', type: 'bearer' }, oidcConfig: null },+ { links: [] },+ ),).resolves.toBeNull();});// A workspace owner may manage the row, but not take another member's tokenit('refuses anyone but the member who connected it', async () => {- await expect(call(oauthConnector, 'workspace-owner')).rejects.toMatchObject({+ await expect(call(oauthConnector, { userId: 'workspace-owner' })).rejects.toMatchObject({code: 'FORBIDDEN',});- expect(ensureFreshConnectorToken).not.toHaveBeenCalled();+ expect(ensureFreshLinkToken).not.toHaveBeenCalled();+ });++ it('refuses an account another member authorized', async () => {+ await expect(+ call(oauthConnector, { links: [account('lnk_a', 'theirs', 'teammate')] }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(ensureFreshLinkToken).not.toHaveBeenCalled();});it('fails when the connector is gone', async () => {diff --git a/apps/server/src/services/connector/localCallToken.ts b/apps/server/src/services/connector/localCallToken.tsindex fc1d946e318..82775162b8d 100644--- a/apps/server/src/services/connector/localCallToken.ts+++ b/apps/server/src/services/connector/localCallToken.ts@@ -3,7 +3,8 @@ import { TRPCError } from '@trpc/server';import type { ConnectorModel } from '@/database/models/connector';-import { ensureFreshConnectorToken } from './tokens';+import { getConnectorLinkModel, loadConnectorLinksMap, pickPrimaryLink } from './links';+import { ensureFreshLinkToken } from './tokens';/*** The current OAuth access token of an HTTP connector the creator's desktop app@@ -11,15 +12,18 @@ import { ensureFreshConnectorToken } from './tokens';* connect through the device). The edit read (`getForEdit`) never returns OAuth* tokens, so without this such a call would reach the server unauthenticated.*- * Narrow on purpose: the creator only (a workspace owner can manage the row- * but must not take a token another member authorized), the access token only- * (never the refresh token or client secret), refreshed first when due. This- * is what the device gateway already forwards to the user's device for the- * same call. `null` when the connector has no OAuth token or runs elsewhere.+ * Narrow on purpose: the creator only, and only an account they authorized (a+ * workspace owner can manage the row but must not take a token another member+ * authorized); the access token only (never the refresh token or client+ * secret), refreshed first when due. This is what the device gateway already+ * forwards to the user's device for the same call. `linkId` picks the account+ * of a connector holding several, its primary account otherwise. `null` when+ * the connector has no OAuth account or runs elsewhere.*/export const getConnectorLocalCallToken = async (ctx: { connectorModel: ConnectorModel; userId: string },id: string,+ linkId?: string,): Promise<{ accessToken: string; type: 'oauth2' } | null> => {const connector = await ctx.connectorModel.findById(id);if (!connector) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });@@ -33,11 +37,27 @@ export const getConnectorLocalCallToken = async (const endpoint = connectorMcpEndpoint(connector);if (endpoint.type === 'stdio' || !connector.mcpServerUrl || !isDeviceOnlyMcpEndpoint(endpoint))return null;- if (connector.credentials?.type !== 'oauth2') return null;- const fresh = await ensureFreshConnectorToken(connector, ctx.connectorModel);- const credentials = fresh.credentials;- return credentials?.type === 'oauth2' && credentials.accessToken- ? { accessToken: credentials.accessToken, type: 'oauth2' }+ const links = (await loadConnectorLinksMap([connector], ctx)).get(connector.id) ?? [];+ const link = linkId ? links.find((item) => item.id === linkId) : pickPrimaryLink(links);+ if (!link) {+ if (linkId) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector account not found' });+ return null;+ }+ if (link.userId !== ctx.userId) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'Only the member who connected this account can run it from their device.',+ });+ }++ const fresh = await ensureFreshLinkToken(+ connector,+ link,+ getConnectorLinkModel(ctx),+ ctx.connectorModel,+ );+ return fresh.credentials.accessToken+ ? { accessToken: fresh.credentials.accessToken, type: 'oauth2' }: null;};diff --git a/apps/server/src/services/connector/oauth.test.ts b/apps/server/src/services/connector/oauth.test.tsindex 5a680ed3501..d0c4411cbb1 100644--- a/apps/server/src/services/connector/oauth.test.ts+++ b/apps/server/src/services/connector/oauth.test.ts@@ -11,6 +11,7 @@ import {registerDynamicClient,registeredAuthMethod,resolveConnectorClient,+ resolveConnectorOAuthScopes,selectRegistrationAuthMethod,toClientInformation,} from './oauth';@@ -416,3 +417,51 @@ describe('OAuth metadata issuer validation', () => {);});});++describe('identity scopes are opt-in on initial automatic client registration', () => {+ const discovery = {+ authorizationServerUrl: 'https://as',+ metadata: { ...metadataWith(), scopes_supported: ['tools', 'openid', 'profile', 'email'] },+ scopes: ['tools'],+ };+ it('adds only advertised identity scopes to nonempty initial scopes', () => {+ expect(resolveConnectorOAuthScopes({ discovery })).toEqual([+ 'tools',+ 'openid',+ 'profile',+ 'email',+ ]);+ expect(+ resolveConnectorOAuthScopes({+ discovery: {+ ...discovery,+ metadata: { ...discovery.metadata, scopes_supported: ['tools', 'openid'] },+ },+ }),+ ).toEqual(['tools', 'openid']);+ });+ it('preserves nonempty frozen scopes, pre-registered clients and empty resources', () => {+ expect(resolveConnectorOAuthScopes({ discovery, existingScopes: ['tools'] })).toEqual([+ 'tools',+ ]);++ expect(resolveConnectorOAuthScopes({ discovery, preRegistered: true })).toEqual(['tools']);+ expect(+ resolveConnectorOAuthScopes({ discovery: { ...discovery, scopes: [] } }),+ ).toBeUndefined();+ });+ it('falls back to discovery when Marketplace supplies an empty stored scope array', () => {+ expect(resolveConnectorOAuthScopes({ discovery, existingScopes: [] })).toEqual([+ 'tools',+ 'openid',+ 'profile',+ 'email',+ ]);+ expect(resolveConnectorOAuthScopes({ discovery, existingScopes: undefined })).toEqual([+ 'tools',+ 'openid',+ 'profile',+ 'email',+ ]);+ });+});diff --git a/apps/server/src/services/connector/oauth.ts b/apps/server/src/services/connector/oauth.tsindex 2cec5bc678a..712d59a04ec 100644--- a/apps/server/src/services/connector/oauth.ts+++ b/apps/server/src/services/connector/oauth.ts@@ -177,6 +177,7 @@ export const discoverConnectorOAuth = async (mcpServerUrl: string): Promise<Discexport const resolveConnectorOAuthScopes = (params: {discovery: DiscoveredOAuth;existingScopes?: string[];+ preRegistered?: boolean;}): string[] | undefined => {if (params.existingScopes?.length) return params.existingScopes;const { metadata, scopes: resourceScopes } = params.discovery;@@ -190,6 +191,12 @@ export const resolveConnectorOAuthScopes = (params: {) {scopes.push('offline_access');}+ if (scopes?.length && !params.preRegistered) {+ for (const identityScope of ['openid', 'profile', 'email']) {+ if (metadata.scopes_supported?.includes(identityScope) && !scopes.includes(identityScope))+ scopes.push(identityScope);+ }+ }return scopes;};@@ -334,6 +341,7 @@ export const buildAuthorizationUrl = async (params: {clientInformation: OAuthClientInformationMixed;metadata: AuthorizationServerMetadata;redirectUri: string;+ prompt?: string;resource?: string;scopes?: string[];state: string;@@ -349,6 +357,17 @@ export const buildAuthorizationUrl = async (params: {state: params.state,},);+ if (params.prompt) {+ const prompts = authorizationUrl.searchParams+ .getAll('prompt')+ .join(' ')+ .split(/\s+/)+ .filter(Boolean);+ authorizationUrl.searchParams.set(+ 'prompt',+ [...new Set([...prompts, ...params.prompt.split(/\s+/)])].join(' '),+ );+ }return { authorizationUrl: authorizationUrl.toString(), codeVerifier };};diff --git a/apps/server/src/services/connector/presentation.ts b/apps/server/src/services/connector/presentation.tsnew file mode 100644index 00000000000..e74f665dc24--- /dev/null+++ b/apps/server/src/services/connector/presentation.ts@@ -0,0 +1,36 @@+import type { ConnectorAuthKind } from '@lobechat/types';++import type { DecryptedConnector } from '@/database/models/connector';++import { type ConnectorLinksContext, loadConnectorLinksMap } from './links';++/** Only this allowlist crosses the API boundary; credentials stay server-side. */+export const loadConnectorPresentation = async (+ connectors: DecryptedConnector[],+ ctx: ConnectorLinksContext,+) => {+ const linksMap = await loadConnectorLinksMap(connectors, ctx);+ return new Map(+ connectors.map((connector) => {+ const links = linksMap.get(connector.id) ?? [];+ const authKind: ConnectorAuthKind = links.length+ ? 'oauth2'+ : (connector.credentials?.type ?? (connector.oidcConfig ? 'oauth2' : 'none'));+ return [+ connector.id,+ {+ authKind,+ links: links.map((link) => ({+ id: link.id,+ name: link.name,+ status: link.status,+ profile: link.profile,+ authorizedByName: link.authorizedByName ?? null,+ authorizedByAvatar: link.authorizedByAvatar ?? null,+ createdAt: link.createdAt.toISOString(),+ })),+ },+ ];+ }),+ );+};diff --git a/apps/server/src/services/connector/stateStore.ts b/apps/server/src/services/connector/stateStore.tsindex a190272c6ed..bf6eda80abd 100644--- a/apps/server/src/services/connector/stateStore.ts+++ b/apps/server/src/services/connector/stateStore.ts@@ -3,6 +3,8 @@ import { randomUUID } from 'node:crypto';import debug from 'debug';import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';+import { redisService } from '@/server/services/redis';+import type { ConnectorOAuthCompletion } from '@/server/services/redis/connectorOAuth';const log = debug('lobe-server:connector:oauth-state');@@ -19,6 +21,7 @@ export interface ConnectorOAuthStatePayload {codeVerifier: string;/** The connector being connected. */connectorId: string;+ linkTarget?: { kind: 'new' } | { kind: 'existing'; linkId: string };/** LobeHub user who initiated the connect. */lobeUserId: string;/** Where to send the user after the callback finishes (relative path). */@@ -80,3 +83,17 @@ export const consumeConnectorOAuthState = async (return null;}};++export type { ConnectorOAuthCompletion } from '@/server/services/redis/connectorOAuth';++/** How a flow ended, for its window to read when the callback's message is lost. */+export const saveConnectorOAuthCompletion = async (+ state: string,+ result: ConnectorOAuthCompletion,+): Promise<void> => {+ await redisService.connectorOAuth.saveCompletion(state, result);+};++export const readConnectorOAuthCompletion = (+ state: string,+): Promise<ConnectorOAuthCompletion | null> => redisService.connectorOAuth.readCompletion(state);diff --git a/apps/server/src/services/connector/sync.test.ts b/apps/server/src/services/connector/sync.test.tsindex 5386cf4dc60..d0c3f8d86a0 100644--- a/apps/server/src/services/connector/sync.test.ts+++ b/apps/server/src/services/connector/sync.test.ts@@ -307,7 +307,11 @@ describe('syncConnectorToolsById', () => {const updateStatus = vi.fn();const result = await syncConnectorToolsById('c1', {- connectorModel: { findById: async () => httpConnector(null), updateStatus } as any,+ connectorModel: {+ getLinkModel: () => ({ listByConnectorIds: async () => [] }),+ findById: async () => httpConnector(null),+ updateStatus,+ } as any,connectorToolModel: { upsertMany } as any,});@@ -351,7 +355,11 @@ describe('syncConnectorToolsById', () => {vi.mocked(mcpService.listRawTools).mockResolvedValue([]);await syncConnectorToolsById('c1', {- connectorModel: { findById: async () => httpConnector(null), updateStatus: vi.fn() } as any,+ connectorModel: {+ getLinkModel: () => ({ listByConnectorIds: async () => [] }),+ findById: async () => httpConnector(null),+ updateStatus: vi.fn(),+ } as any,connectorToolModel: { upsertMany: vi.fn() } as any,userId: 'user-1',});diff --git a/apps/server/src/services/connector/sync.ts b/apps/server/src/services/connector/sync.tsindex d622afe4296..d7de77168d2 100644--- a/apps/server/src/services/connector/sync.ts+++ b/apps/server/src/services/connector/sync.ts@@ -12,6 +12,7 @@ import {} from '@lobechat/utils/mcpEndpoint';import type { ConnectorModel, DecryptedConnector } from '@/database/models/connector';+import type { ConnectorLinkModel } from '@/database/models/connectorLink';import type { ConnectorToolModel } from '@/database/models/connectorTool';import type { ConnectorCredentials } from '@/database/schemas';import {@@ -26,9 +27,16 @@ import { mcpService } from '@/server/services/mcp';import { listMcpToolsOnDevice } from '@/server/services/mcp/deviceTunnel';import { isMcpAppsEnabled } from '@/server/services/mcp/featureGate';-import { ensureFreshConnectorToken } from './tokens';+import {+ getConnectorLinkModel,+ loadConnectorLinksMap,+ pickPrimaryLink,+ withLinkCredentials,+} from './links';+import { ensureFreshConnectorToken, ensureFreshLinkToken } from './tokens';export interface ConnectorToolSyncContext {+ connectorLinkModel?: ConnectorLinkModel;connectorModel: ConnectorModel;connectorToolModel: ConnectorToolModel;}@@ -114,6 +122,8 @@ export const buildHttpAuthFromCredentials = (};export interface ConnectorToolSyncOptions {+ /** List with this account's credentials instead of the connector's primary one. */+ linkId?: string;/*** Drop the `auto` tools the server no longer lists, so they stop being* advertised: eval contracts, and an MCP install or reinstall, whose tool@@ -207,7 +217,15 @@ export const syncConnectorToolsById = async (}// Refresh the OAuth access token if it has expired before connecting.- connector = await ensureFreshConnectorToken(connector, ctx.connectorModel);+ const links = (await loadConnectorLinksMap([connector], ctx)).get(connector.id) ?? [];+ const link = options.linkId ? links.find((l) => l.id === options.linkId) : pickPrimaryLink(links);+ if (options.linkId && !link) throw new Error('Connector account no longer exists');+ connector = link+ ? withLinkCredentials(+ connector,+ await ensureFreshLinkToken(connector, link, getConnectorLinkModel(ctx), ctx.connectorModel),+ )+ : await ensureFreshConnectorToken(connector, ctx.connectorModel);const mcpParams = buildConnectorMcpParams(connector);@@ -222,7 +240,8 @@ export const syncConnectorToolsById = async (mcpApps,}));} catch (err) {- await ctx.connectorModel.updateStatus(connectorId, ConnectorStatus.error);+ if (link) await getConnectorLinkModel(ctx).updateStatus(connectorId, link.id, 'error');+ if (links.length < 2) await ctx.connectorModel.updateStatus(connectorId, ConnectorStatus.error);throw err;}@@ -253,6 +272,7 @@ export const syncConnectorToolsById = async (syncInputs.map((tool) => tool.toolName),);}+ if (link) await getConnectorLinkModel(ctx).updateStatus(connectorId, link.id, 'connected');await ctx.connectorModel.updateStatus(connectorId, ConnectorStatus.connected);return { toolCount: syncInputs.length };diff --git a/apps/server/src/services/connector/tokens.test.ts b/apps/server/src/services/connector/tokens.test.tsindex 9e20edd98f0..f83d379dee4 100644--- a/apps/server/src/services/connector/tokens.test.ts+++ b/apps/server/src/services/connector/tokens.test.ts@@ -6,7 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type * as OauthModule from './oauth';import { refreshConnectorToken } from './oauth';-import { refreshExpiredConnectorTokens } from './tokens';+import { ensureFreshLinkToken, refreshExpiredConnectorTokens } from './tokens';vi.mock('@modelcontextprotocol/client', async (importOriginal) => ({...(await importOriginal<object>()),@@ -209,3 +209,103 @@ describe('refreshExpiredConnectorTokens', () => {expect(connector.credentials).toMatchObject({ accessToken: 'winner' });});});++describe('per-account token refresh', () => {+ beforeEach(() => {+ vi.useFakeTimers({ now: NOW });+ vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({} as any);+ });+ afterEach(() => {+ vi.useRealTimers();+ vi.clearAllMocks();+ });+ const makeLink = (id: string) =>+ ({+ id,+ userConnectorId: 'parent',+ name: id,+ status: 'connected',+ credentials: {+ accessToken: `old-${id}`,+ refreshToken: `refresh-${id}`,+ expiresAt: NOW - 1,+ type: 'oauth2',+ },+ }) as any;+ it('coalesces concurrent refreshes by link id and never writes tokens onto the parent', async () => {+ vi.mocked(refreshConnectorToken).mockResolvedValue({+ tokens: { access_token: 'fresh', expires_in: 3600, token_type: 'Bearer' },+ } as any);+ const link = makeLink('coalesce');+ const linkModel = { updateCredentials: vi.fn() } as any;+ const parentModel = { update: vi.fn() } as any;+ const connector = oauthConnector('parent', NOW - 1);+ const results = await Promise.all([+ ensureFreshLinkToken(connector, link, linkModel, parentModel),+ ensureFreshLinkToken(connector, link, linkModel, parentModel),+ ]);+ expect(refreshConnectorToken).toHaveBeenCalledOnce();+ expect(linkModel.updateCredentials).toHaveBeenCalledWith(+ 'parent',+ 'coalesce',+ expect.objectContaining({ accessToken: 'fresh', refreshToken: 'refresh-coalesce' }),+ );+ expect(parentModel.update).not.toHaveBeenCalled();+ expect(results[0].credentials.accessToken).toBe('fresh');+ });+ // Account ids are unique within their connector only: every connector read+ // from a token written before accounts existed has the same one.+ it('refreshes accounts with the same id on different connectors separately', async () => {+ vi.mocked(refreshConnectorToken).mockImplementation(async ({ refreshToken }) => ({+ tokens: { access_token: `fresh-${refreshToken}`, expires_in: 3600, token_type: 'Bearer' },+ }));+ const linkModel = { updateCredentials: vi.fn() } as any;+ const linkOf = (connectorId: string) => ({+ ...makeLink('lnk_default'),+ userConnectorId: connectorId,+ credentials: {+ ...makeLink('lnk_default').credentials,+ refreshToken: `refresh-${connectorId}`,+ },+ });+ const results = await Promise.all(+ ['first', 'second'].map((id) =>+ ensureFreshLinkToken(oauthConnector(id, NOW - 1), linkOf(id), linkModel, {} as any),+ ),+ );+ expect(refreshConnectorToken).toHaveBeenCalledTimes(2);+ expect(results.map((link) => link.credentials.accessToken)).toEqual([+ 'fresh-refresh-first',+ 'fresh-refresh-second',+ ]);+ expect(linkModel.updateCredentials).toHaveBeenCalledWith(+ 'second',+ 'lnk_default',+ expect.objectContaining({ accessToken: 'fresh-refresh-second' }),+ );+ });+ it('recovers a rotation from another process before marking invalid_grant as unhealthy', async () => {+ vi.mocked(refreshConnectorToken).mockRejectedValue({ code: 'invalid_grant' });+ const stale = makeLink('rotated');+ const fresh = {+ ...stale,+ credentials: { ...stale.credentials, accessToken: 'winner', expiresAt: NOW + 3600000 },+ };+ const linkModel = { findById: vi.fn().mockResolvedValue(fresh), updateStatus: vi.fn() } as any;+ expect(+ (await ensureFreshLinkToken(oauthConnector('parent', NOW - 1), stale, linkModel, {} as any))+ .credentials.accessToken,+ ).toBe('winner');+ expect(linkModel.updateStatus).not.toHaveBeenCalled();+ linkModel.findById.mockResolvedValue(stale);+ const pending = ensureFreshLinkToken(+ oauthConnector('parent', NOW - 1),+ stale,+ linkModel,+ {} as any,+ );+ await vi.advanceTimersByTimeAsync(1000);+ expect((await pending).status).toBe('error');+ expect(linkModel.updateStatus).toHaveBeenCalledWith('parent', 'rotated', 'error');+ });+});diff --git a/apps/server/src/services/connector/tokens.ts b/apps/server/src/services/connector/tokens.tsindex 1a88cbde35f..6d134b17b7f 100644--- a/apps/server/src/services/connector/tokens.ts+++ b/apps/server/src/services/connector/tokens.ts@@ -3,6 +3,7 @@ import debug from 'debug';import pMap from 'p-map';import type { ConnectorModel, DecryptedConnector } from '@/database/models/connector';+import type { ConnectorLinkModel, DecryptedConnectorLink } from '@/database/models/connectorLink';import type { ConnectorCredentials } from '@/database/schemas';import {@@ -226,3 +227,117 @@ export const refreshExpiredConnectorTokens = (},{ concurrency: RUN_TOKEN_REFRESH_CONCURRENCY },);++/**+ * Account refreshes in flight on this instance. Keyed by connector and account:+ * account ids are unique within their connector only.+ */+const inFlightLinkRefreshes = new Map<string, Promise<DecryptedConnectorLink>>();+const linkRefreshKey = (connector: DecryptedConnector, link: DecryptedConnectorLink) =>+ `${connector.id}:${link.id}`;+export const ensureFreshLinkToken = (+ connector: DecryptedConnector,+ link: DecryptedConnectorLink,+ linkModel: ConnectorLinkModel,+ connectorModel: ConnectorModel,+): Promise<DecryptedConnectorLink> => {+ const creds = link.credentials;+ const oidc = connector.oidcConfig;+ if (+ !creds.refreshToken ||+ (creds.expiresAt && creds.expiresAt - EXPIRY_SKEW_MS > Date.now()) ||+ !oidc?.issuer ||+ !oidc.clientId+ )+ return Promise.resolve(link);+ const key = linkRefreshKey(connector, link);+ const pending = inFlightLinkRefreshes.get(key);+ if (pending) return pending;+ const refresh = (async () => {+ try {+ const metadata = await discoverConnectorAuthorizationServerMetadata(oidc.issuer!);+ if (!metadata) return link;+ const { authMethod, tokens } = await refreshConnectorToken({+ authorizationServerUrl: oidc.issuer!,+ clientInformation: toClientInformation(oidc),+ metadata,+ refreshToken: creds.refreshToken!,+ resource: connector.mcpServerUrl ?? undefined,+ });+ const { credentials, tokenExpiresAt } = tokensToCredentials(tokens, {+ clientSecret: oidc.clientSecret,+ fallbackRefreshToken: creds.refreshToken,+ });+ if (credentials.type !== 'oauth2') return link;+ await linkModel.updateCredentials(connector.id, link.id, credentials);+ if (authMethod && authMethod !== oidc.tokenEndpointAuthMethod)+ await connectorModel.update(connector.id, {+ oidcConfig: { ...oidc, tokenEndpointAuthMethod: authMethod },+ });+ return { ...link, credentials, tokenExpiresAt, status: 'connected' as const };+ } catch (error) {+ // Another process may have rotated this refresh token. Re-read before+ // marking the account unhealthy, including a short persistence grace.+ for (let attempt = 0; attempt < 2; attempt++) {+ if (attempt) await new Promise((resolve) => setTimeout(resolve, ROTATION_PERSIST_GRACE_MS));+ const latest = await linkModel.findById(connector.id, link.id);+ if (+ latest &&+ latest.credentials.accessToken !== creds.accessToken &&+ (!latest.credentials.expiresAt ||+ latest.credentials.expiresAt - EXPIRY_SKEW_MS > Date.now())+ )+ return latest;+ }+ const code =+ (error as { error?: string; code?: string }).error ?? (error as { code?: string }).code;+ if (+ code === 'invalid_grant' ||+ (error instanceof Error && /invalid_grant/i.test(error.message))+ ) {+ await linkModel.updateStatus(connector.id, link.id, 'error');+ return { ...link, status: 'error' as const };+ }+ log(+ 'token refresh failed for link=%s errorType=%s',+ link.id,+ error instanceof Error ? error.name : typeof error,+ );+ return link;+ }+ })().finally(() => {+ if (inFlightLinkRefreshes.get(key) === refresh) inFlightLinkRefreshes.delete(key);+ });+ inFlightLinkRefreshes.set(key, refresh);+ return refresh;+};++export const refreshExpiredLinkTokens = async (+ connector: DecryptedConnector,+ links: DecryptedConnectorLink[],+ linkModel: ConnectorLinkModel,+ connectorModel: ConnectorModel,+ options: { onTimeout?: () => void } = {},+) =>+ pMap(+ links,+ async (link) => {+ if (!connector.isEnabled || !link.credentials.expiresAt) return link;+ const refresh = ensureFreshLinkToken(connector, link, linkModel, connectorModel);+ let timer: ReturnType<typeof setTimeout> | undefined;+ const timeout = new Promise<DecryptedConnectorLink>((resolve) => {+ timer = setTimeout(() => {+ const key = linkRefreshKey(connector, link);+ if (inFlightLinkRefreshes.get(key) === refresh) inFlightLinkRefreshes.delete(key);+ options.onTimeout?.();+ resolve(link);+ }, RUN_TOKEN_REFRESH_TIMEOUT_MS);+ });+ try {+ return await Promise.race([refresh, timeout]);+ } finally {+ clearTimeout(timer);+ }+ },+ { concurrency: RUN_TOKEN_REFRESH_CONCURRENCY },+ );diff --git a/apps/server/src/services/redis/README.md b/apps/server/src/services/redis/README.mdindex 5df984195c8..249d79913ff 100644--- a/apps/server/src/services/redis/README.md+++ b/apps/server/src/services/redis/README.md@@ -11,6 +11,8 @@ callers do not choose a provider, prefix, key, SET options or claim lifetime.a day. Atomic append (bounded), drain and restore; the runtime drains it into the next turn.Writes return `undefined` without Redis, and the caller tells the client to send directly.- `linear`: single-use OAuth state for "Connect Linear" (ten minutes, deleted on first read).+- `connectorOAuth`: how each connector OAuth flow ended (account and outcome), for ten minutes,+ read back by the window that started the flow. `null` without Redis.- `agentDocumentIndex`: the agent-document index snapshot and change notes one conversation(topic/thread/agent) renders from, for a day. `undefined` without Redis; the runtime thentakes a fresh snapshot every run.diff --git a/apps/server/src/services/redis/connectorOAuth.test.ts b/apps/server/src/services/redis/connectorOAuth.test.tsnew file mode 100644index 00000000000..9c742df4e94--- /dev/null+++ b/apps/server/src/services/redis/connectorOAuth.test.ts@@ -0,0 +1,48 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { connectorOAuth } from './connectorOAuth';++const store = new Map<string, string>();+const redis = vi.hoisted(() => ({ client: null as any }));+vi.mock('./client', () => ({ getRedisServiceClient: async () => redis.client }));++const memoryClient = {+ get: vi.fn(async (key: string) => store.get(key) ?? null),+ set: vi.fn(async (key: string, value: string) => {+ store.set(key, value);+ return 'OK';+ }),+};++const completion = {+ connectorId: 'c1',+ linkId: 'lnk_a',+ lobeUserId: 'u1',+ outcome: 'created' as const,+};++beforeEach(() => {+ store.clear();+ vi.clearAllMocks();+ redis.client = memoryClient;+});++describe('redisService.connectorOAuth', () => {+ it('records how a flow ended for ten minutes and reads it back', async () => {+ expect(await connectorOAuth.saveCompletion('flow-1', completion)).toBe(true);++ expect(memoryClient.set).toHaveBeenCalledWith(+ 'connector_oauth_completion:v1:flow-1',+ expect.any(String),+ { ex: 600 },+ );+ expect(await connectorOAuth.readCompletion('flow-1')).toEqual(completion);+ expect(await connectorOAuth.readCompletion('flow-2')).toBeNull();+ });++ it('records and finds nothing without Redis', async () => {+ redis.client = null;+ expect(await connectorOAuth.saveCompletion('flow-1', completion)).toBe(false);+ expect(await connectorOAuth.readCompletion('flow-1')).toBeNull();+ });+});diff --git a/apps/server/src/services/redis/connectorOAuth.ts b/apps/server/src/services/redis/connectorOAuth.tsnew file mode 100644index 00000000000..8def96caed3--- /dev/null+++ b/apps/server/src/services/redis/connectorOAuth.ts@@ -0,0 +1,50 @@+import { RedisKeys } from '@/server/modules/Redis';++import { getRedisServiceClient } from './client';++const getClient = () => getRedisServiceClient('integrations');++/** As long as the flow's own state lives: the window asks right after the callback. */+const COMPLETION_TTL_SECONDS = 600;++export interface ConnectorOAuthCompletion {+ connectorId: string;+ linkId: string;+ lobeUserId: string;+ outcome: 'created' | 'reauthorized' | 'matchedExisting';+ workspaceId?: string;+}++export const connectorOAuth = {+ /**+ * Record how a connector OAuth flow ended, so the window that started it can+ * read the outcome when the callback's message never reaches it (the native+ * IPC only reports success; a severed `window.opener` reports nothing).+ * `false` without Redis.+ */+ async saveCompletion(flowId: string, completion: ConnectorOAuthCompletion): Promise<boolean> {+ const redis = await getClient();+ if (!redis) return false;++ await redis.set(+ RedisKeys.integrations.connectorOAuthCompletion(flowId),+ JSON.stringify(completion),+ { ex: COMPLETION_TTL_SECONDS },+ );+ return true;+ },++ /** The recorded end of a flow; `null` when none was recorded, it expired, or without Redis. */+ async readCompletion(flowId: string): Promise<ConnectorOAuthCompletion | null> {+ const redis = await getClient();+ if (!redis) return null;++ const raw = await redis.get(RedisKeys.integrations.connectorOAuthCompletion(flowId));+ if (!raw) return null;+ try {+ return JSON.parse(raw) as ConnectorOAuthCompletion;+ } catch {+ return null;+ }+ },+};diff --git a/apps/server/src/services/redis/index.ts b/apps/server/src/services/redis/index.tsindex 7e1774638e2..87befdf8ddb 100644--- a/apps/server/src/services/redis/index.ts+++ b/apps/server/src/services/redis/index.ts@@ -4,6 +4,7 @@ import { agentRunSlots } from './agentRunSlots';import { agentSignal } from './agentSignal';import { botReply } from './botReply';import { botWake } from './botWake';+import { connectorOAuth } from './connectorOAuth';import { deviceSystemInfo } from './deviceSystemInfo';import { linear } from './linear';import { pageCollab } from './pageCollab';@@ -22,6 +23,7 @@ export const redisService = {agentSignal,botReply,botWake,+ connectorOAuth,deviceSystemInfo,linear,pageCollab,diff --git a/apps/server/src/services/toolExecution/index.connectorLinks.test.ts b/apps/server/src/services/toolExecution/index.connectorLinks.test.tsnew file mode 100644index 00000000000..2111490b604--- /dev/null+++ b/apps/server/src/services/toolExecution/index.connectorLinks.test.ts@@ -0,0 +1,229 @@+// @vitest-environment node+import { SdkErrorCode, SdkHttpError } from '@modelcontextprotocol/client';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { deviceGateway } from '@/server/services/deviceGateway';++import { ToolExecutionService } from './index';++const mocks = vi.hoisted(() => ({ find: vi.fn(), links: vi.fn(), call: vi.fn(), tools: vi.fn() }));+vi.mock('@/database/models/connector', () => ({+ ConnectorModel: vi.fn(function () {+ return {+ context: { db: {}, userId: 'me' },+ // Any row by id: the marker alone must never pick the connector+ findById: mocks.find,+ // The connector the call's identifier resolves to for the run+ resolveByIdentifiers: async () => {+ const row = await mocks.find();+ return row ? [row] : [];+ },+ getLinkModel: () => ({ listByConnectorIds: mocks.links }),+ };+ }),+}));+vi.mock('@/database/models/connectorTool', () => ({+ ConnectorToolModel: vi.fn(function () {+ return { queryByConnector: mocks.tools };+ }),+}));+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({+ KeyVaultsGateKeeper: { initWithEnvKey: async () => ({}) },+}));+vi.mock('@/server/services/mcp/featureGate', () => ({ isMcpAppsEnabled: async () => false }));+vi.mock('@/server/services/deviceGateway', () => ({+ deviceGateway: { isConfigured: true, executeMcpCall: vi.fn() },+}));+vi.mock('@/server/services/deviceGateway/deviceChannels', () => ({+ resolveDeviceClientKind: async () => 'desktop',+ resolveMcpClientKinds: async () => ['desktop'],+}));+vi.mock('@/server/services/deviceGateway/dispatchAuthorization', () => ({+ resolveDeviceDispatchAuthorizationFailure: async () => undefined,+}));+vi.mock('./serverRuntimes/resolveWorkspaceScope', () => ({+ resolveRunWorkspaceId: async () => undefined,+}));+const service = new ToolExecutionService({+ builtinToolsExecutor: {} as never,+ mcpService: { callTool: mocks.call } as never,+});+const payload = {+ apiName: 'echo',+ arguments: '{"link_id":"lnk_b","x":1}',+ identifier: 'multi',+ id: 'call',+ type: 'mcp' as const,+};+const context = (url: string, extra = {}) =>+ ({+ userId: 'me',+ serverDB: {},+ toolManifestMap: {+ multi: {+ mcpParams: { type: 'http', url },+ connectorLinks: { connectorId: 'c', param: 'link_id' },+ },+ },+ ...extra,+ }) as any;+beforeEach(() => {+ vi.clearAllMocks();+ mocks.find.mockResolvedValue({+ id: 'c',+ identifier: 'multi',+ isEnabled: true,+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://mcp.example',+ credentials: null,+ // Accounts belong to OAuth connectors, which always carry their client.+ oidcConfig: { clientId: 'client', scheme: 'dcr' },+ });+ mocks.links.mockResolvedValue(+ ['a', 'b'].map((id) => ({+ id: `lnk_${id}`,+ userConnectorId: 'c',+ name: id,+ status: 'connected',+ credentials: { type: 'oauth2', accessToken: `token-${id}` },+ })),+ );+ mocks.call.mockResolvedValue({ content: 'ok', success: true });+ mocks.tools.mockResolvedValue([{ permission: 'auto', toolName: 'echo', userConnectorId: 'c' }]);+ vi.mocked(deviceGateway.executeMcpCall).mockResolvedValue({+ success: true,+ content: 'device ok',+ });+});+describe('live connector account resolution at dispatch', () => {+ it('resolves the selected token and strips the selector before HTTP execution', async () => {+ const result = await service.executeTool(payload, context('https://mcp.example'));+ expect(result.success).toBe(true);+ expect(mocks.call.mock.calls[0][0]).toMatchObject({+ argsStr: '{"x":1}',+ clientParams: { auth: { accessToken: 'token-b' } },+ });+ });+ it('resolves the selected token and strips the selector before device execution', async () => {+ mocks.find.mockResolvedValue({+ id: 'c',+ identifier: 'multi',+ isEnabled: true,+ mcpConnectionType: 'http',+ mcpServerUrl: 'http://localhost:1234/mcp',+ credentials: null,+ oidcConfig: { clientId: 'client', scheme: 'dcr' },+ });+ const result = await service.executeTool(+ payload,+ context('http://localhost:1234/mcp', {+ activeDeviceId: 'device',+ }),+ );+ expect(result.success).toBe(true);+ expect(vi.mocked(deviceGateway.executeMcpCall).mock.calls[0][0]).toMatchObject({+ arguments: '{"x":1}',+ params: { auth: { accessToken: 'token-b' } },+ });+ });+ it('does not silently pick another account and uses neutral names for visitor errors', async () => {+ const result = await service.executeTool(+ { ...payload, arguments: '{}' },+ context('https://mcp.example', { agentShareVisitor: {} }),+ );+ expect(result).toMatchObject({ success: false, content: expect.stringContaining('Account 1') });+ expect(mocks.call).not.toHaveBeenCalled();+ });+ it('includes selected account on authorization failure and disallows switching without consent', async () => {+ mocks.call.mockRejectedValueOnce(+ new SdkHttpError(SdkErrorCode.ClientHttpNotImplemented, 'expired', { status: 401 }),+ );+ const result = await service.executeTool(payload, context('https://mcp.example'));+ expect(result).toMatchObject({+ success: false,+ content: expect.stringContaining("Account 'b'"),+ });+ expect(result.content).toContain("without the user's consent");+ });+ it('rechecks the live endpoint before a shared visitor resolves any account credentials', async () => {+ mocks.find.mockResolvedValue({+ id: 'c',+ identifier: 'multi',+ isEnabled: true,+ mcpConnectionType: 'http',+ mcpServerUrl: 'http://localhost:1234/mcp',+ credentials: null,+ oidcConfig: { clientId: 'client', scheme: 'dcr' },+ });+ const result = await service.executeTool(+ payload,+ context('https://old-public.example', { agentShareVisitor: {} }),+ );+ expect(result).toMatchObject({ success: false, error: { code: 'SHARE_GATE_BLOCKED' } });+ expect(mocks.links).not.toHaveBeenCalled();+ expect(deviceGateway.executeMcpCall).not.toHaveBeenCalled();+ expect(mocks.call).not.toHaveBeenCalled();+ });+ it('retains the selected account on serialized device failures', async () => {+ mocks.find.mockResolvedValue({+ id: 'c',+ identifier: 'multi',+ isEnabled: true,+ mcpConnectionType: 'http',+ mcpServerUrl: 'http://localhost:1234/mcp',+ credentials: null,+ oidcConfig: { clientId: 'client', scheme: 'dcr' },+ });+ vi.mocked(deviceGateway.executeMcpCall).mockResolvedValueOnce({+ success: false,+ content: 'Provider rejected authorization',+ error: '401',+ });+ const result = await service.executeTool(+ payload,+ context('http://localhost:1234/mcp', { activeDeviceId: 'device' }),+ );+ expect(result).toMatchObject({+ success: false,+ content: expect.stringContaining("account 'b'"),+ });+ expect(result.content).toContain("without the user's consent");+ expect(result.content).toContain('Provider rejected authorization');+ });++ // A plugin row can carry any manifest, marker included+ describe('a marker the connector does not back', () => {+ it('lends no account to a manifest whose marker names another connector', async () => {+ const result = await service.executeTool(payload, {+ ...context('https://mcp.example'),+ toolManifestMap: {+ multi: {+ mcpParams: { type: 'http', url: 'https://mcp.example' },+ connectorLinks: { connectorId: 'someone-elses', param: 'link_id' },+ },+ },+ });+ expect(result).toMatchObject({ success: false });+ expect(mocks.links).not.toHaveBeenCalled();+ expect(mocks.call).not.toHaveBeenCalled();+ });+ it('blocks a tool the connector has disabled', async () => {+ mocks.tools.mockResolvedValue([+ { permission: 'disabled', toolName: 'echo', userConnectorId: 'c' },+ ]);+ const result = await service.executeTool(payload, context('https://mcp.example'));+ expect(result.content).toContain('has been disabled by the user');+ expect(mocks.links).not.toHaveBeenCalled();+ expect(mocks.call).not.toHaveBeenCalled();+ });+ it('refuses a tool the connector does not serve', async () => {+ const result = await service.executeTool(+ { ...payload, apiName: 'not_synced' },+ context('https://mcp.example'),+ );+ expect(result).toMatchObject({ success: false });+ expect(mocks.links).not.toHaveBeenCalled();+ expect(mocks.call).not.toHaveBeenCalled();+ });+ });+});diff --git a/apps/server/src/services/toolExecution/index.ts b/apps/server/src/services/toolExecution/index.tsindex 82afddcc4dd..45c71f05d9b 100644--- a/apps/server/src/services/toolExecution/index.ts+++ b/apps/server/src/services/toolExecution/index.ts@@ -4,6 +4,8 @@ import { type ChatToolPayload, type DeviceClient } from '@lobechat/types';import { isDeviceOnlyMcpEndpoint, shouldConnectViaDevice } from '@lobechat/utils/mcpEndpoint';import debug from 'debug';+import { ConnectorModel } from '@/database/models/connector';+import { ConnectorToolModel } from '@/database/models/connectorTool';import { ConnectorToolPermission } from '@/database/schemas';import { type CloudMCPParams, type HttpMCPClientParams, type StdioMCPParams } from '@/libs/mcp';import {@@ -11,6 +13,9 @@ import {getConnectorToolPermission,} from '@/libs/mcp/connectorPermissionCheck';import { isMCPSSRFBlockedError } from '@/libs/mcp/ssrf';+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';+import { resolveLinkedCall } from '@/server/services/connector/links';+import { buildConnectorMcpParams } from '@/server/services/connector/sync';import { deviceGateway } from '@/server/services/deviceGateway';import { resolveMcpClientKinds } from '@/server/services/deviceGateway/deviceChannels';import { resolveDeviceDispatchAuthorizationFailure } from '@/server/services/deviceGateway/dispatchAuthorization';@@ -274,7 +279,8 @@ export class ToolExecutionService {payload: ChatToolPayload,context: ToolExecutionContext,): Promise<ToolExecutionResult> {- const { identifier, apiName, arguments: args } = payload;+ const { identifier, apiName } = payload;+ let args = payload.arguments;log('Executing MCP tool: %s:%s', identifier, apiName);@@ -293,7 +299,8 @@ export class ToolExecutionService {}// Extract MCP params from manifest (stored in customParams.mcp in LobeTool)- const mcpParams = (manifest as any).mcpParams;+ let mcpParams = (manifest as any).mcpParams;+ let linkName: string | undefined;if (!mcpParams) {log('MCP configuration not found in manifest for: %s ', identifier);return {@@ -331,6 +338,66 @@ export class ToolExecutionService {}try {+ const marker = (manifest as { connectorLinks?: { connectorId: string; param: string } })+ .connectorLinks;+ if (marker) {+ if (!context.serverDB || !context.userId)+ throw new Error(+ 'Connector account resolution requires an authenticated execution context',+ );+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();+ const workspaceId = await resolveRunWorkspaceId(context);+ const connectorModel = new ConnectorModel(+ context.serverDB,+ context.userId,+ workspaceId,+ gateKeeper,+ );+ // The marker rides in a manifest, and a plugin row can carry any+ // manifest. Only the connector this call's identifier resolves to for+ // the run (the one the permission gate checked) may lend its accounts,+ // and only to a tool it serves and has not disabled.+ const [connector] = await connectorModel.resolveByIdentifiers(+ [identifier],+ context.agentId,+ );+ if (!connector || connector.id !== marker.connectorId || !connector.isEnabled)+ throw new Error(+ 'Connector is no longer available. Ask the user to connect an account in Settings > Connectors.',+ );+ const tool = (+ await new ConnectorToolModel(+ context.serverDB,+ context.userId,+ workspaceId,+ ).queryByConnector(connector.id)+ ).find((item) => item.toolName === apiName);+ if (!tool) throw new Error(`Connector '${identifier}' has no tool named '${apiName}'.`);+ if (tool.permission === ConnectorToolPermission.disabled)+ return buildBlockedToolResponse(apiName);+ const currentEndpoint = buildConnectorMcpParams({ ...connector, credentials: null });+ if (context.agentShareVisitor && isDeviceOnlyMcpEndpoint(currentEndpoint)) {+ const message = `MCP server '${identifier}' runs on the agent owner's own machine and is not available in shared conversations.`;+ return {+ content: message,+ error: { code: 'SHARE_GATE_BLOCKED', message },+ success: false,+ };+ }+ const resolved = await resolveLinkedCall(+ {+ connector,+ argsStr: args,+ param: marker.param,+ isShareVisitor: !!context.agentShareVisitor,+ },+ { connectorModel },+ );+ args = resolved.argsStr;+ payload = { ...payload, arguments: args };+ linkName = resolved.linkName;+ mcpParams = buildConnectorMcpParams(resolved.connector);+ }// Check if this is a cloud MCP endpointif (mcpParams.type === 'cloud') {return await this.executeCloudMCPTool(payload, context, mcpParams);@@ -381,7 +448,16 @@ export class ToolExecutionService {success: false,};}- return await this.executeMcpViaDevice(payload, context, mcpParams, tunnelTarget);+ const result = await this.executeMcpViaDevice(payload, context, mcpParams, tunnelTarget);+ if (!result.success && linkName) {+ // Device transports may serialize a provider error to plain text.+ // Preserve its meaning while retaining the selected account boundary.+ return {+ ...result,+ content: `The call using account '${linkName}' failed. Do not switch to another account without the user's consent. ${result.content}`,+ };+ }+ return result;}// HTTP MCP endpoints can execute through the server-side MCP service.@@ -407,6 +483,7 @@ export class ToolExecutionService {if (isMcpAuthorizationError(error)) {const content = buildMcpAuthorizationErrorContent(identifier, {isShareVisitor: !!context.agentShareVisitor,+ linkName,});return {content,diff --git a/apps/server/src/services/toolExecution/mcpAuthError.ts b/apps/server/src/services/toolExecution/mcpAuthError.tsindex cde4c615769..04bc9ae759c 100644--- a/apps/server/src/services/toolExecution/mcpAuthError.ts+++ b/apps/server/src/services/toolExecution/mcpAuthError.ts@@ -43,8 +43,11 @@ export const isMcpAuthorizationError = (error: unknown): boolean => {*/export const buildMcpAuthorizationErrorContent = (identifier: string,- options: { isShareVisitor: boolean },+ options: { isShareVisitor: boolean; linkName?: string },): string =>- options.isShareVisitor+ (options.linkName+ ? `Account '${options.linkName}' could not authorize this call. Do not switch to another account without the user's consent. `+ : '') ++ (options.isShareVisitor? `The '${identifier}' connection was set up on this agent creator's side (by the creator or a member of their workspace), and its authorization has expired or been revoked. The person in this shared conversation cannot reconnect it and has no sign-in or authorization option here. Tell them this tool is unavailable until the agent's creator (or whoever manages this connection for them) reconnects it. They cannot do it themselves, so do not ask them to sign in, authorize, or reconnect anything, and continue with what you can do without this tool.`- : `The '${identifier}' connection's authorization has expired, been revoked, or lacks the required permissions. Ask the user to reconnect '${identifier}' in their tool or connector settings, then retry.`;+ : `The '${identifier}' connection's authorization has expired, been revoked, or lacks the required permissions. Ask the user to reconnect '${identifier}' in their tool or connector settings, then retry.`);diff --git a/apps/server/src/services/widget/__tests__/credentials.test.ts b/apps/server/src/services/widget/__tests__/credentials.test.tsindex 6a6c133fd2b..a66ff5883d1 100644--- a/apps/server/src/services/widget/__tests__/credentials.test.ts+++ b/apps/server/src/services/widget/__tests__/credentials.test.ts@@ -1,7 +1,10 @@import { describe, expect, it, vi } from 'vitest';import type { DecryptedConnector } from '@/database/models/connector';-import { ensureFreshConnectorToken } from '@/server/services/connector/tokens';+import {+ ensureFreshConnectorToken,+ ensureFreshLinkToken,+} from '@/server/services/connector/tokens';import {ForbiddenWidgetCredentialsError,@@ -13,6 +16,7 @@ import {vi.mock('@/server/services/connector/tokens', () => ({ensureFreshConnectorToken: vi.fn(async (connector) => connector),+ ensureFreshLinkToken: vi.fn(async (_connector, link) => link),}));const connector = (overrides: Partial<DecryptedConnector>): DecryptedConnector =>@@ -27,7 +31,8 @@ const connector = (overrides: Partial<DecryptedConnector>): DecryptedConnector =...overrides,}) as DecryptedConnector;-const modelReturning = (rows: DecryptedConnector[]) => ({+const modelReturning = (rows: DecryptedConnector[], accounts: object[] = []) => ({+ getLinkModel: () => ({ listByConnectorIds: async () => accounts }),resolveByIdentifiers: vi.fn().mockResolvedValue(rows),update: vi.fn(),});@@ -264,6 +269,57 @@ describe('resolveWidgetEnv', () => {expect(isWorkspaceOwner).not.toHaveBeenCalled();});+ // A script can read and send its environment anywhere+ describe("an OAuth connector's accounts", () => {+ const oauth = connector({+ credentials: null,+ id: 'c1',+ oidcConfig: { clientId: 'client', scheme: 'dcr' },+ workspaceId: 'ws1',+ } as Partial<DecryptedConnector>);+ const account = (id: string, userId: string, createdAt: number) => ({+ createdAt: new Date(createdAt),+ credentials: { accessToken: `token-${id}`, type: 'oauth2' },+ id,+ name: id,+ status: 'connected',+ tokenExpiresAt: null,+ userConnectorId: 'c1',+ userId,+ });+ const teammateFirst = [account('lnk_teammate', 'u2', 1), account('lnk_mine', 'u1', 2)];++ it("never hands the creator a teammate's token, even the primary one", async () => {+ const { env } = await resolveWidgetEnv({} as any, workspace, requirement, {+ connectorModel: modelReturning([oauth], teammateFirst) as any,+ isWorkspaceOwner: vi.fn().mockResolvedValue(false),+ });++ expect(env).toEqual({ GITHUB_TOKEN: 'token-lnk_mine' });+ });++ it('refuses when only teammates connected accounts, before refreshing any', async () => {+ vi.mocked(ensureFreshLinkToken).mockClear();+ const error = await resolveWidgetEnv({} as any, workspace, requirement, {+ connectorModel: modelReturning([oauth], [account('lnk_teammate', 'u2', 1)]) as any,+ isWorkspaceOwner: vi.fn().mockResolvedValue(false),+ }).catch((e) => e);++ expect(error).toBeInstanceOf(ForbiddenWidgetCredentialsError);+ expect(error.connectors).toEqual(['github']);+ expect(ensureFreshLinkToken).not.toHaveBeenCalled();+ });++ it("lets the workspace owner use a member's account when they have none", async () => {+ const { env } = await resolveWidgetEnv({} as any, workspace, requirement, {+ connectorModel: modelReturning([oauth], [account('lnk_teammate', 'u2', 1)]) as any,+ isWorkspaceOwner: vi.fn().mockResolvedValue(true),+ });++ expect(env).toEqual({ GITHUB_TOKEN: 'token-lnk_teammate' });+ });+ });+it('injects nothing once the author no longer exists', async () => {await expect(resolveWidgetEnv({} as any, { ...workspace, authorUserId: null }, requirement, {diff --git a/apps/server/src/services/widget/credentials.ts b/apps/server/src/services/widget/credentials.tsindex e40ddf2ef4d..f283677f9b4 100644--- a/apps/server/src/services/widget/credentials.ts+++ b/apps/server/src/services/widget/credentials.ts@@ -1,10 +1,19 @@import type { WidgetEnvRequirement } from '@lobechat/types';import { ConnectorModel, type DecryptedConnector } from '@/database/models/connector';+import type { DecryptedConnectorLink } from '@/database/models/connectorLink';import type { ConnectorCredentials } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';-import { ensureFreshConnectorToken } from '@/server/services/connector/tokens';+import {+ loadConnectorLinksMap,+ pickPrimaryLink,+ withLinkCredentials,+} from '@/server/services/connector/links';+import {+ ensureFreshConnectorToken,+ ensureFreshLinkToken,+} from '@/server/services/connector/tokens';import { isWorkspacePrimaryOwner } from '@/server/services/workspacePermission';import {@@ -196,6 +205,23 @@ const mayInject = async (return !!connector.workspaceId && isOwner();};+/**+ * The OAuth account whose token a script may receive. A script can read and+ * send its environment anywhere, so an account's token goes only to the member+ * who authorized it, or to the workspace owner, who may use any workspace+ * credential. Creating the connector does not make a teammate's account yours.+ */+const pickInjectableAccount = async (+ connector: DecryptedConnector,+ accounts: DecryptedConnectorLink[],+ scope: WidgetCredentialScope,+ isOwner: () => Promise<boolean>,+): Promise<DecryptedConnectorLink | undefined> => {+ const own = accounts.filter((account) => account.userId === scope.authorUserId);+ if (own.length) return pickPrimaryLink(own);+ return connector.workspaceId && (await isOwner()) ? pickPrimaryLink(accounts) : undefined;+};+/*** Resolve the environment a widget script declares in `manifest.env`.*@@ -270,9 +296,22 @@ export const resolveWidgetEnv = async (: isWorkspacePrimaryOwner({ db, userId: scope.authorUserId, workspaceId: scope.workspaceId });return ownerCheck;};+ const model = connectorModel as ConnectorModel;+ const accountsByConnector = await loadConnectorLinksMap([...byIdentifier.values()], {+ connectorModel: model,+ });const forbidden: string[] = [];+ const accountOf = new Map<string, DecryptedConnectorLink>();for (const connector of byIdentifier.values()) {- if (!(await mayInject(connector, scope, isOwner))) forbidden.push(connector.identifier);+ if (!(await mayInject(connector, scope, isOwner))) {+ forbidden.push(connector.identifier);+ continue;+ }+ const accounts = accountsByConnector.get(connector.id) ?? [];+ if (!accounts.length) continue;+ const account = await pickInjectableAccount(connector, accounts, scope, isOwner);+ if (account) accountOf.set(connector.id, account);+ else forbidden.push(connector.identifier);}if (forbidden.length > 0) throw new ForbiddenWidgetCredentialsError(forbidden);@@ -286,7 +325,13 @@ export const resolveWidgetEnv = async (let connector = byIdentifier.get(requirement.connector);if (connector) {- connector = await ensureFreshConnectorToken(connector, connectorModel as ConnectorModel);+ const link = accountOf.get(connector.id);+ connector = link+ ? withLinkCredentials(+ connector,+ await ensureFreshLinkToken(connector, link, model.getLinkModel(), model),+ )+ : await ensureFreshConnectorToken(connector, model);}const selection = selectConnectorSecret(connector?.credentials ?? null, requirement.field);if ('error' in selection) {diff --git a/apps/server/src/utils/connectorAttribution.ts b/apps/server/src/utils/connectorAttribution.tsindex d743886d085..ecba4197a1d 100644--- a/apps/server/src/utils/connectorAttribution.ts+++ b/apps/server/src/utils/connectorAttribution.ts@@ -1,3 +1,5 @@+import { sanitizeConnectorPromptText } from '@lobechat/mecha';+import { UserModel } from '@/database/models/user';import type { LobeChatDatabase } from '@/database/type';@@ -123,8 +125,7 @@ export const collectBorrowedConnectors = (* brackets so a crafted name can't forge a closing `</tool_credential_ownership>`* tag or inject its own system-level instructions, then cap the length.*/-const sanitizeForPrompt = (value: string): string =>- value.replaceAll(/\s+/g, ' ').replaceAll(/[<>]/g, '').trim().slice(0, 120);+const sanitizeForPrompt = sanitizeConnectorPromptText;/*** Build the system-prompt block that tells the model which of its tools rundiff --git a/locales/en-US/tool.json b/locales/en-US/tool.jsonindex c9770841817..5805d16c5eb 100644--- a/locales/en-US/tool.json+++ b/locales/en-US/tool.json@@ -77,6 +77,44 @@"codeInterpreter.files": "Files:","codeInterpreter.output": "Output:","codeInterpreter.returnValue": "Return Value:",+ "connector.account.alreadyConnected": "“{{name}}” is already connected",+ "connector.account.alreadyConnectedDesc": "No account was added. To connect a different one, sign in to the provider with that account and try again.",+ "connector.account.alreadyConnectedUnnamed": "This account is already connected",+ "connector.account.authorizedBy": "Authorized by {{name}}",+ "connector.account.connect": "Connect account",+ "connector.account.connectAnother": "Connect another account",+ "connector.account.connectFailed": "Couldn't connect the account. {{reason}}",+ "connector.account.connected": "Connected “{{name}}”",+ "connector.account.editDropsAccount": "Changing the server URL or OAuth client removes the connected account. Saving will authorize again.",+ "connector.account.editDropsAccounts": "Changing the server URL or OAuth client removes all {{count}} connected accounts. Saving authorizes one of them again; reconnect the others under Accounts afterwards.",+ "connector.account.editKeepsAccounts": "Saving keeps the connected accounts. To re-authorize one or connect another, go to Accounts on the connector's page.",+ "connector.account.empty": "No account connected yet. Connect one so the AI can use this connector's tools.",+ "connector.account.error.authFailed": "Authorization didn't complete. Try again, or check this connector's OAuth settings.",+ "connector.account.error.retry": "Try again.",+ "connector.account.error.timeout": "Authorization timed out. Try again.",+ "connector.account.more": "More actions",+ "connector.account.namingHint": "The AI picks an account by its name, so give each one a name that tells them apart.",+ "connector.account.needsReauth_one": "{{count}} account needs re-authorization",+ "connector.account.needsReauth_other": "{{count}} accounts need re-authorization",+ "connector.account.reauthorize": "Re-authorize",+ "connector.account.reauthorizeFailed": "Couldn't re-authorize “{{name}}”. {{reason}}",+ "connector.account.reauthorizeMismatch": "“{{name}}” wasn't updated",+ "connector.account.reauthorizeMismatchDesc": "You signed in as “{{matched}}”, which is connected separately, so its authorization was refreshed instead. To re-authorize “{{name}}”, sign in with that account.",+ "connector.account.reauthorized": "Re-authorized “{{name}}”",+ "connector.account.remove": "Remove",+ "connector.account.removeConfirmContent": "The AI will no longer use this account. You can connect it again later.",+ "connector.account.removeConfirmOk": "Remove account",+ "connector.account.removeConfirmTitle": "Remove “{{name}}”?",+ "connector.account.removeFailed": "Couldn't remove “{{name}}”; it's still connected. {{reason}}",+ "connector.account.removeLastConfirmContent": "This is the only connected account. Once it's removed, this connector's tools stop working until you connect an account again.",+ "connector.account.rename": "Rename",+ "connector.account.renameConflict": "This connector already has an account named “{{name}}”. Choose another name.",+ "connector.account.renameDesc": "The AI sees this name when choosing an account. Up to 64 characters, unique within this connector.",+ "connector.account.renameFailed": "Couldn't rename the account. {{reason}}",+ "connector.account.renameTitle": "Rename account",+ "connector.account.switchHint": "Connecting uses the account you're signed in to on the provider's site in this browser. To connect a different one, switch accounts there first.",+ "connector.account.title": "Accounts",+ "connector.account.usingAccount": "Account: {{name}}","connector.actionFailed": "Operation failed, please try again","connector.add.advanced": "Advanced settings","connector.add.authError": "Authorization failed: {{reason}}",diff --git a/locales/zh-CN/tool.json b/locales/zh-CN/tool.jsonindex 3652dff61d7..00a8d56a15e 100644--- a/locales/zh-CN/tool.json+++ b/locales/zh-CN/tool.json@@ -77,6 +77,44 @@"codeInterpreter.files": "文件:","codeInterpreter.output": "输出:","codeInterpreter.returnValue": "返回值:",+ "connector.account.alreadyConnected": "「{{name}}」已经连接过",+ "connector.account.alreadyConnectedDesc": "没有新增账号。要连接其他账号,请在对方网站换成那个账号登录后再试。",+ "connector.account.alreadyConnectedUnnamed": "这个账号已经连接过",+ "connector.account.authorizedBy": "由 {{name}} 授权",+ "connector.account.connect": "连接账号",+ "connector.account.connectAnother": "再连接一个账号",+ "connector.account.connectFailed": "没能连接账号。{{reason}}",+ "connector.account.connected": "已连接「{{name}}」",+ "connector.account.editDropsAccount": "更改服务器地址或 OAuth 客户端会移除已连接的账号,保存时需要重新授权。",+ "connector.account.editDropsAccounts": "更改服务器地址或 OAuth 客户端会移除已连接的 {{count}} 个账号。保存时会重新授权其中一个,其余账号之后请在「账号」中重新连接。",+ "connector.account.editKeepsAccounts": "保存后继续使用已连接的账号。重新授权或再连接一个账号,请在连接器详情的「账号」中操作。",+ "connector.account.empty": "还没有连接账号。连接后,AI 才能使用这个连接器的工具。",+ "connector.account.error.authFailed": "授权没有完成。请重试,或检查这个连接器的 OAuth 设置。",+ "connector.account.error.retry": "请重试。",+ "connector.account.error.timeout": "授权超时了,请重试。",+ "connector.account.more": "更多操作",+ "connector.account.namingHint": "AI 会按账号名选择要用的账号,请给每个账号起一个能区分的名字。",+ "connector.account.needsReauth_one": "{{count}} 个账号需要重新授权",+ "connector.account.needsReauth_other": "{{count}} 个账号需要重新授权",+ "connector.account.reauthorize": "重新授权",+ "connector.account.reauthorizeFailed": "没能重新授权「{{name}}」。{{reason}}",+ "connector.account.reauthorizeMismatch": "「{{name}}」没有更新",+ "connector.account.reauthorizeMismatchDesc": "你登录的是另一个已连接的账号「{{matched}}」,因此刷新的是它的授权。要重新授权「{{name}}」,请用对应的账号登录。",+ "connector.account.reauthorized": "已重新授权「{{name}}」",+ "connector.account.remove": "移除",+ "connector.account.removeConfirmContent": "移除后,AI 将不再通过这个账号调用工具。之后可以重新连接。",+ "connector.account.removeConfirmOk": "移除账号",+ "connector.account.removeConfirmTitle": "移除账号「{{name}}」?",+ "connector.account.removeFailed": "没能移除「{{name}}」,账号仍保持连接。{{reason}}",+ "connector.account.removeLastConfirmContent": "这是唯一已连接的账号。移除后,这个连接器的工具将无法使用,直到你重新连接账号。",+ "connector.account.rename": "重命名",+ "connector.account.renameConflict": "这个连接器已有名为「{{name}}」的账号,请换一个名字。",+ "connector.account.renameDesc": "AI 会根据这个名字选择账号。最多 64 个字符,同一连接器内不能重名。",+ "connector.account.renameFailed": "没能重命名账号。{{reason}}",+ "connector.account.renameTitle": "重命名账号",+ "connector.account.switchHint": "连接时会直接使用你在此浏览器中登录对方网站的账号。要连接其他账号,请先在对方网站切换账号。",+ "connector.account.title": "账号",+ "connector.account.usingAccount": "账号:{{name}}","connector.actionFailed": "操作失败,请重试","connector.add.advanced": "高级设置","connector.add.authError": "授权失败:{{reason}}",diff --git a/packages/context-engine/src/engine/tools/types.ts b/packages/context-engine/src/engine/tools/types.tsindex e10ecf3aa7a..1e66da6a8a2 100644--- a/packages/context-engine/src/engine/tools/types.ts+++ b/packages/context-engine/src/engine/tools/types.ts@@ -28,6 +28,7 @@ export interface LobeChatPluginApi {export interface LobeToolManifest {api: LobeChatPluginApi[];+ connectorLinks?: { connectorId: string; param: string };identifier: string;meta: any;systemRole?: string;diff --git a/packages/database/src/models/__tests__/connectorLink.test.ts b/packages/database/src/models/__tests__/connectorLink.test.tsnew file mode 100644index 00000000000..7166687c88d--- /dev/null+++ b/packages/database/src/models/__tests__/connectorLink.test.ts@@ -0,0 +1,411 @@+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { agents, userConnectors, users, workspaces } from '../../schemas';+import { rehomeAgentConnectorsForRecipient } from '../../utils/agentConnectors';+import { ConnectorModel } from '../connector';+import {+ allocateLinkName,+ ConnectorLinkModel,+ ConnectorLinkNameTakenError,+ ConnectorLinkNotFoundError,+ LEGACY_LINK_ID,+} from '../connectorLink';++const db = await getTestDB();+const vault = {+ encrypt: async (s: string) => `enc:${s}`,+ decrypt: async (s: string) => ({ plaintext: s.replace(/^enc:/, '') }),+};+const model = new ConnectorModel(db, 'alice', undefined, vault);+const links = new ConnectorLinkModel(db, 'alice', undefined, vault);+const credentials = { type: 'oauth2' as const, accessToken: 'alice-token', idToken: 'transient' };++const create = (extra = {}) =>+ model.create({+ identifier: crypto.randomUUID(),+ name: 'test',+ sourceType: 'custom',+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://mcp.example',+ oidcConfig: { clientId: 'client', scheme: 'dcr' },+ status: 'connected',+ ...extra,+ });+const save = (id: string, externalAccountId?: string, accessToken = 'alice-token') =>+ links.applyAuthorization(id, {+ authorizerId: 'alice',+ credentials: { ...credentials, accessToken },+ target: { kind: 'new' },+ identity: { externalAccountId },+ });+const storedPlaintext = async (id: string) => {+ const [row] = await db+ .select({ credentials: userConnectors.credentials })+ .from(userConnectors)+ .where(eq(userConnectors.id, id));+ return row.credentials;+};++beforeEach(async () => {+ await db.delete(users);+ await db.insert(users).values([+ { id: 'alice', fullName: 'Alice' },+ { id: 'bob', fullName: 'Bob' },+ ]);+});+afterEach(async () => {+ await db.delete(users);+});++describe('ConnectorLinkModel', () => {+ it('stores every account encrypted on the connector row, never the id token', async () => {+ const row = await create();+ await save(row.id, 'issuer/alice');+ await save(row.id, 'issuer/bob', 'bob-token');++ const stored = await storedPlaintext(row.id);+ expect(stored).toMatch(/^enc:/);+ expect(stored).not.toContain('transient');+ const result = await links.listByConnectorIds([row.id]);+ expect(result.map((l) => [l.name, l.credentials.accessToken])).toEqual([+ ['Default', 'alice-token'],+ ['Account 2', 'bob-token'],+ ]);+ expect(result[0]).toMatchObject({ authorizedByName: 'Alice', userConnectorId: row.id });+ expect((await model.queryPublic())[0].hasCredentials).toBe(true);+ });++ // Callers that spread a connector (the edit read, list projections) must+ // never carry the tokens of its accounts.+ it('keeps accounts out of the connector read', async () => {+ const row = await create();+ await save(row.id);+ expect((await model.findById(row.id))?.credentials).toBeNull();+ expect((await model.query()).find((c) => c.id === row.id)?.credentials).toBeNull();+ });++ it('reads a token written before accounts existed as one account, and keeps its id', async () => {+ const expiresAt = new Date('2030-01-01').getTime();+ const row = await create({+ credentials: JSON.stringify({ ...credentials, expiresAt }),+ status: 'error',+ });++ const [legacy] = await links.listByConnectorIds([row.id]);+ expect(legacy).toMatchObject({+ credentials: { accessToken: 'alice-token' },+ id: LEGACY_LINK_ID,+ name: 'Default',+ status: 'error',+ tokenExpiresAt: new Date(expiresAt),+ userId: 'alice',+ });+ expect(legacy.credentials).not.toHaveProperty('idToken');+ // Reading changes nothing: an instance of the previous release keeps using it+ expect(await storedPlaintext(row.id)).toBe(+ `enc:${JSON.stringify({ ...credentials, expiresAt })}`,+ );+ expect((await model.findById(row.id))?.credentials).toMatchObject({ type: 'oauth2' });++ await links.updateCredentials(row.id, LEGACY_LINK_ID, {+ type: 'oauth2',+ accessToken: 'refreshed',+ });+ await save(row.id, 'issuer/second', 'second-token');+ expect((await links.listByConnectorIds([row.id])).map((l) => [l.id, l.name])).toEqual([+ [LEGACY_LINK_ID, 'Default'],+ [expect.stringMatching(/^lnk_/), 'Account 2'],+ ]);+ expect((await links.findById(row.id, LEGACY_LINK_ID))?.credentials.accessToken).toBe(+ 'refreshed',+ );+ });++ it('leaves static credentials untouched and reads them as no account', async () => {+ const row = await create({ credentials: JSON.stringify({ type: 'bearer', token: 'static' }) });+ expect(await links.listByConnectorIds([row.id])).toEqual([]);+ await links.updateStatus(row.id, LEGACY_LINK_ID, 'error');+ expect(await links.remove(row.id, LEGACY_LINK_ID)).toBeUndefined();+ await expect(links.rename(row.id, LEGACY_LINK_ID, 'x')).rejects.toBeInstanceOf(+ ConnectorLinkNotFoundError,+ );+ expect((await model.findById(row.id))?.credentials).toEqual({+ type: 'bearer',+ token: 'static',+ });+ });++ it('replaces static credentials with the first OAuth account', async () => {+ const row = await create({ credentials: JSON.stringify({ type: 'bearer', token: 'static' }) });+ await save(row.id);+ expect((await model.findById(row.id))?.credentials).toBeNull();+ expect(await links.listByConnectorIds([row.id])).toHaveLength(1);+ });++ // Each refresh locks the row and re-reads it: two accounts refreshed at once+ // must both keep their rotated tokens.+ it('keeps the tokens of accounts refreshed at the same time', async () => {+ const row = await create();+ const ids = [];+ for (let i = 0; i < 5; i++) ids.push((await save(row.id, `issuer/${i}`)).linkId);++ await Promise.all(+ ids.map((id, i) =>+ links.updateCredentials(row.id, id, {+ type: 'oauth2',+ accessToken: `rotated-${i}`,+ expiresAt: 1000 + i,+ refreshToken: `refresh-${i}`,+ }),+ ),+ );++ const result = await links.listByConnectorIds([row.id]);+ expect(result.map((l) => l.credentials.accessToken)).toEqual(ids.map((_, i) => `rotated-${i}`));+ const [stored] = await db+ .select({ tokenExpiresAt: userConnectors.tokenExpiresAt })+ .from(userConnectors)+ .where(eq(userConnectors.id, row.id));+ expect(stored.tokenExpiresAt).toEqual(new Date(1000));+ });++ it('keeps every account added at the same time', async () => {+ const row = await create();+ await Promise.all([0, 1, 2, 3].map((i) => save(row.id, `issuer/${i}`, `token-${i}`)));+ const result = await links.listByConnectorIds([row.id]);+ expect(result.map((l) => l.credentials.accessToken).sort()).toEqual([+ 'token-0',+ 'token-1',+ 'token-2',+ 'token-3',+ ]);+ expect(new Set(result.map((l) => l.name)).size).toBe(4);+ });++ it('creates, reauthorizes, deduplicates and keeps names stable', async () => {+ const row = await create();+ const first = await save(row.id, 'issuer/alice');+ expect(first.outcome).toBe('created');+ expect(await save(row.id, 'issuer/alice')).toEqual({+ linkId: first.linkId,+ outcome: 'matchedExisting',+ });+ const second = await save(row.id, 'issuer/bob');+ expect((await links.listByConnectorIds([row.id])).map((l) => l.name)).toEqual([+ 'Default',+ 'Account 2',+ ]);+ expect(+ await links.applyAuthorization(row.id, {+ target: { kind: 'existing', linkId: second.linkId },+ authorizerId: 'bob',+ credentials,+ }),+ ).toEqual({ linkId: second.linkId, outcome: 'reauthorized' });+ expect((await links.findById(row.id, second.linkId))?.authorizedByName).toBe('Bob');++ await links.rename(row.id, second.linkId, ' Work ');+ await expect(links.rename(row.id, first.linkId, 'Work')).rejects.toBeInstanceOf(+ ConnectorLinkNameTakenError,+ );+ await expect(links.rename(row.id, second.linkId, ' ')).rejects.toThrow();+ expect(await links.remove(row.id, first.linkId)).toEqual({ remaining: 1 });+ expect((await links.findById(row.id, second.linkId))?.name).toBe('Work');+ expect(await links.remove(row.id, second.linkId)).toEqual({ remaining: 0 });+ expect(await model.findById(row.id)).toMatchObject({+ credentials: null,+ status: 'disconnected',+ tokenExpiresAt: null,+ });+ });++ // Reauthorized while signed in as someone else, with identity discovery failing+ it('keeps no identity a fresh token was not shown to have', async () => {+ const row = await create();+ const a = await save(row.id, 'issuer/a', 'a-token');+ await links.applyAuthorization(row.id, {+ authorizerId: 'alice',+ credentials: { type: 'oauth2', accessToken: 'b-token' },+ target: { kind: 'existing', linkId: a.linkId },+ });+ expect(await links.findById(row.id, a.linkId)).toMatchObject({+ credentials: { accessToken: 'b-token' },+ externalAccountId: null,+ profile: null,+ });++ // Connecting A again adds it instead of overwriting the token held now+ expect(await save(row.id, 'issuer/a', 'a-token-2')).toMatchObject({ outcome: 'created' });+ expect(await links.findById(row.id, a.linkId)).toMatchObject({+ credentials: { accessToken: 'b-token' },+ });+ });++ it('refuses to reauthorize an account that no longer exists', async () => {+ const row = await create();+ await expect(+ links.applyAuthorization(row.id, {+ target: { kind: 'existing', linkId: 'lnk_gone' },+ authorizerId: 'alice',+ credentials,+ }),+ ).rejects.toBeInstanceOf(ConnectorLinkNotFoundError);+ });++ it('enforces user and workspace scope for reads and writes', async () => {+ const row = await create();+ const { linkId } = await save(row.id);+ const other = new ConnectorLinkModel(db, 'bob', undefined, vault);+ expect(await other.findById(row.id, linkId)).toBeNull();+ expect(await other.listByConnectorIds([row.id])).toEqual([]);+ await expect(other.rename(row.id, linkId, 'stolen')).rejects.toBeInstanceOf(+ ConnectorLinkNotFoundError,+ );+ await expect(other.remove(row.id, linkId)).rejects.toBeInstanceOf(ConnectorLinkNotFoundError);+ await expect(+ other.applyAuthorization(row.id, {+ target: { kind: 'new' },+ credentials,+ authorizerId: 'bob',+ }),+ ).rejects.toBeInstanceOf(ConnectorLinkNotFoundError);+ expect((await links.findById(row.id, linkId))?.name).toBe('Default');++ await db+ .insert(workspaces)+ .values({ id: 'ws', name: 'WS', slug: 'ws', primaryOwnerId: 'alice' });+ const ws = await new ConnectorModel(db, 'alice', 'ws', vault).create({+ identifier: 'shared',+ name: 'Shared',+ sourceType: 'custom',+ status: 'connected',+ });+ const shared = await new ConnectorLinkModel(db, 'alice', 'ws', vault).applyAuthorization(+ ws.id,+ { target: { kind: 'new' }, credentials, authorizerId: 'alice' },+ );+ expect(await links.findById(ws.id, shared.linkId)).toBeNull();+ expect(+ await new ConnectorLinkModel(db, 'bob', 'ws', vault).findById(ws.id, shared.linkId),+ ).toBeTruthy();+ });++ it('clears accounts when the credentials, URL or client change, and keeps them on other edits', async () => {+ for (const patch of [+ { mcpServerUrl: 'https://other.example' },+ { credentials: null },+ { oidcConfig: { scheme: 'dcr' as const, clientId: 'other' } },+ ]) {+ const row = await create();+ const a = await save(row.id);+ await save(row.id);+ await model.update(row.id, { metadata: { customHeaders: { test: 'value' } } });+ await model.update(row.id, { oidcConfig: { clientId: 'client', scheme: 'dcr' } });+ expect(await links.findById(row.id, a.linkId)).toBeTruthy();+ await model.update(row.id, patch);+ expect(await links.listByConnectorIds([row.id])).toEqual([]);+ expect(await storedPlaintext(row.id)).toBeNull();+ }+ });++ it('keeps static credentials when the URL changes', async () => {+ const row = await create({+ credentials: JSON.stringify({ type: 'bearer', token: 'static' }),+ oidcConfig: null,+ });+ await model.update(row.id, { mcpServerUrl: 'https://other.example' });+ expect((await model.findById(row.id))?.credentials).toEqual({+ type: 'bearer',+ token: 'static',+ });+ });++ it('copies the accounts with the connector', async () => {+ await db.insert(agents).values({ id: 'agent', userId: 'alice' });+ const row = await create();+ const { linkId } = await save(row.id);+ const copied = await model.copyToAgent(row.id, 'agent');+ expect(await links.listByConnectorIds([copied!.id])).toMatchObject([+ { id: linkId, name: 'Default', credentials: { accessToken: 'alice-token' } },+ ]);+ });++ it('allocates bounded unique names', () => {+ expect(allocateLinkName([], 'a')).toBe('a');+ expect(allocateLinkName(['a'], 'a')).toBe('a (2)');+ expect(allocateLinkName(['Default', 'Account 2'])).toBe('Account 3');+ expect(allocateLinkName(['x'.repeat(64)], 'x'.repeat(64))).toHaveLength(64);+ });++ it('removes every account when an agent connector is transferred to another owner', async () => {+ await db.insert(agents).values({ id: 'handover-agent', userId: 'alice' });+ const row = await create({ agentId: 'handover-agent' });+ await save(row.id, 'issuer/alice');+ await rehomeAgentConnectorsForRecipient(db, {+ agentIds: ['handover-agent'],+ recipientId: 'bob',+ });+ expect(await storedPlaintext(row.id)).toBeNull();+ expect(await new ConnectorModel(db, 'bob', undefined, vault).findById(row.id)).toMatchObject({+ userId: 'bob',+ credentials: null,+ status: 'disconnected',+ isEnabled: false,+ });+ });++ it.each([+ {+ label: 'updates an automatic name to the new identity',+ customName: undefined,+ occupiedName: undefined,+ expected: '[email protected]',+ },+ {+ label: 'preserves a custom account name',+ customName: 'Work',+ occupiedName: undefined,+ expected: 'Work',+ },+ {+ label: 'deduplicates the new automatic name against other accounts',+ customName: undefined,+ occupiedName: '[email protected]',+ expected: '[email protected] (2)',+ },+ {+ label: 'does not rename without a new identity profile',+ customName: undefined,+ occupiedName: undefined,+ expected: '[email protected]',+ noIdentity: true,+ },+ ])('$label', async ({ customName, occupiedName, expected, noIdentity }) => {+ const row = await create();+ const original = await links.applyAuthorization(row.id, {+ target: { kind: 'new' },+ credentials,+ authorizerId: 'alice',+ identity: { externalAccountId: 'issuer/a', profile: { email: '[email protected]' } },+ });+ if (customName) await links.rename(row.id, original.linkId, customName);+ if (occupiedName) {+ const other = await save(row.id, 'issuer/other');+ await links.rename(row.id, other.linkId, occupiedName);+ }+ await links.applyAuthorization(row.id, {+ target: { kind: 'existing', linkId: original.linkId },+ credentials: { type: 'oauth2', accessToken: 'b-token' },+ authorizerId: 'alice',+ identity: noIdentity+ ? undefined+ : { externalAccountId: 'issuer/b', profile: { email: '[email protected]' } },+ });+ expect(await links.findById(row.id, original.linkId)).toMatchObject({+ name: expected,+ credentials: { accessToken: 'b-token' },+ });+ });+});diff --git a/packages/database/src/models/connector.ts b/packages/database/src/models/connector.tsindex 5b9aa446ed5..e1e0f3ad30b 100644--- a/packages/database/src/models/connector.ts+++ b/packages/database/src/models/connector.ts@@ -1,4 +1,5 @@import type { ConnectorVisibility } from '@lobechat/types';+import { safeParseJSON } from '@lobechat/utils';import type { SQL } from 'drizzle-orm';import { and, asc, eq, inArray, isNotNull, isNull, or, sql } from 'drizzle-orm';import pMap from 'p-map';@@ -12,6 +13,7 @@ import {normalizeWorkspaceId,} from '../utils/workspace';import { EvalConnectorUpdateError, normalizeEvalConnectorPatch } from './connectorEval';+import { ConnectorLinkModel, isConnectorOAuthAccounts } from './connectorLink';import {connectorAccessScope,connectorAgentConfigScope,@@ -38,6 +40,7 @@ interface GateKeeper {export interface DecryptedConnector extends Omit<UserConnectorItem, 'credentials'> {credentials: ConnectorCredentials | null;+ links?: { id: string; name: string; userId?: string }[];}export interface ConnectorReference {@@ -125,6 +128,9 @@ export class ConnectorModel {this.gateKeeper = gateKeeper;}+ getLinkModel = () =>+ new ConnectorLinkModel(this.db, this.userId, this.workspaceId, this.gateKeeper);+private ownership = () =>connectorAccessScope(this.db,@@ -905,6 +911,15 @@ export class ConnectorModel {patch,gateKeeper?.decrypt.bind(gateKeeper),);+ if (+ normalized.credentials !== undefined &&+ normalized.oidcConfig === undefined &&+ safeParseJSON<ConnectorCredentials>(normalized.credentials ?? undefined)?.type !== 'oauth2'+ ) {+ // Explicit static/no-auth credentials replace OAuth. Do not leave a+ // stale client configuration presenting this as an OAuth connector.+ normalized.oidcConfig = null;+ }if (current.metadata?.agentEval && normalized.credentials && !gateKeeper) {throw new EvalConnectorUpdateError('Secure connection storage is unavailable');}@@ -918,6 +933,20 @@ export class ConnectorModel {throw error;}}+ if (+ !('credentials' in normalized) &&+ current.credentials &&+ ((normalized.mcpServerUrl !== undefined &&+ normalized.mcpServerUrl !== current.mcpServerUrl) ||+ (normalized.oidcConfig !== undefined &&+ normalized.oidcConfig?.clientId !== current.oidcConfig?.clientId)) &&+ (await isStoredOAuth(current.credentials, gateKeeper))+ ) {+ // OAuth tokens belong to the server and client that issued them: a new+ // one ends every account. Static credentials stay with the connector.+ normalized.credentials = null;+ normalized.tokenExpiresAt = null;+ }await tx.update(userConnectors).set({@@ -1018,6 +1047,11 @@ async function encryptCredentials(credentials: string, gateKeeper?: GateKeeper):return gateKeeper.encrypt(credentials);}+/**+ * Decrypt a connector row. OAuth accounts never leave as `credentials`: they+ * are read through `ConnectorLinkModel`, so no caller of this model can hand a+ * whole connector's tokens on by accident.+ */async function decryptRow(row: UserConnectorItem,gateKeeper?: GateKeeper,@@ -1028,8 +1062,21 @@ async function decryptRow(const plain = gateKeeper? (await gateKeeper.decrypt(row.credentials)).plaintext: row.credentials;- return { ...row, credentials: JSON.parse(plain) as ConnectorCredentials };+ const credentials: unknown = JSON.parse(plain);+ if (isConnectorOAuthAccounts(credentials)) return { ...row, credentials: null };+ return { ...row, credentials: credentials as ConnectorCredentials };} catch {return { ...row, credentials: null };}}++/** Whether stored credentials are OAuth: one legacy token or accounts. */+async function isStoredOAuth(ciphertext: string, gateKeeper?: GateKeeper): Promise<boolean> {+ try {+ const plain = gateKeeper ? (await gateKeeper.decrypt(ciphertext)).plaintext : ciphertext;+ return safeParseJSON<{ type?: string }>(plain)?.type === 'oauth2';+ } catch {+ // Unreadable: treat it as OAuth, since the new server cannot use it anyway.+ return true;+ }+}diff --git a/packages/database/src/models/connectorLink.ts b/packages/database/src/models/connectorLink.tsnew file mode 100644index 00000000000..cbdaf22e59f--- /dev/null+++ b/packages/database/src/models/connectorLink.ts@@ -0,0 +1,414 @@+import type {+ ConnectorCredentials,+ ConnectorLinkProfile,+ ConnectorLinkRecord,+ ConnectorLinkStatus,+ ConnectorOAuthAccounts,+ ConnectorOAuthCredentials,+} from '@lobechat/types';+import { and, eq, inArray, sql } from 'drizzle-orm';+import pMap from 'p-map';++import { ConnectorStatus, userConnectors, users } from '../schemas';+import type { LobeChatDatabase } from '../type';+import { idGenerator } from '../utils/idGenerator';+import { connectorAccessScope } from './connectorScope';++interface GateKeeper {+ decrypt: (ciphertext: string) => Promise<{ plaintext: string }>;+ encrypt: (plaintext: string) => Promise<string>;+}++export type OAuthCredentials = ConnectorOAuthCredentials;++/** One OAuth account of a connector, decrypted. */+export interface DecryptedConnectorLink {+ authorizedByAvatar?: string | null;+ authorizedByName?: string | null;+ createdAt: Date;+ credentials: OAuthCredentials;+ /** Provider identity used to recognise the same account again; `null` when unknown. */+ externalAccountId: string | null;+ /** `lnk_…`, unique within its connector. */+ id: string;+ name: string;+ profile: ConnectorLinkProfile | null;+ status: ConnectorLinkStatus;+ tokenExpiresAt: Date | null;+ /** The connector the account belongs to. */+ userConnectorId: string;+ /** The member who authorized this account. */+ userId: string;+}+export type ConnectorLinkTarget = { kind: 'new' } | { kind: 'existing'; linkId: string };+export interface ConnectorLinkIdentity {+ externalAccountId?: string;+ profile?: ConnectorLinkProfile | null;+}+export interface ConnectorLinkAuthorization {+ authorizerId: string;+ credentials: OAuthCredentials;+ identity?: ConnectorLinkIdentity;+ target: ConnectorLinkTarget;+}+export interface ConnectorLinkAuthorizationResult {+ linkId: string;+ outcome: 'created' | 'reauthorized' | 'matchedExisting';+}++export class ConnectorLinkNotFoundError extends Error {}+export class ConnectorLinkNameTakenError extends Error {}++/**+ * Id of the account read from a single `oauth2` credential written before+ * accounts existed. Ids are unique within a connector only, so every such+ * connector can use the same one; it is kept once the accounts are rewritten.+ */+export const LEGACY_LINK_ID = 'lnk_default';++/** Rows decrypted at once; decryption is local but still awaited per row. */+const DECRYPT_CONCURRENCY = 10;+const MAX_LINK_NAME_LENGTH = 64;++export const deriveLinkDisplayName = (profile?: ConnectorLinkProfile | null): string | undefined =>+ profile?.email || profile?.username || profile?.name || undefined;++export const allocateLinkName = (existingNames: string[], preferred?: string): string => {+ const names = new Set(existingNames);+ const base = preferred?.trim().slice(0, MAX_LINK_NAME_LENGTH);+ if (base && !names.has(base)) return base;+ if (base) {+ for (let i = 2; ; i++) {+ const suffix = ` (${i})`;+ const name = base.slice(0, MAX_LINK_NAME_LENGTH - suffix.length) + suffix;+ if (!names.has(name)) return name;+ }+ }+ if (!names.has('Default')) return 'Default';+ for (let i = 2; ; i++) if (!names.has(`Account ${i}`)) return `Account ${i}`;+};++/** Whether a decrypted `credentials` value holds OAuth accounts. */+export const isConnectorOAuthAccounts = (value: unknown): value is ConnectorOAuthAccounts =>+ !!value &&+ typeof value === 'object' &&+ (value as { type?: unknown }).type === 'oauth2' &&+ Array.isArray((value as { accounts?: unknown }).accounts);++type StoredCredentials = ConnectorCredentials | ConnectorOAuthAccounts;++interface ConnectorRowSlice {+ createdAt: Date;+ credentials: string | null;+ id: string;+ status: string;+ userId: string;+}++const rowColumns = {+ createdAt: userConnectors.createdAt,+ credentials: userConnectors.credentials,+ id: userConnectors.id,+ status: userConnectors.status,+ userId: userConnectors.userId,+};++/** The accounts a connector's stored credentials hold; static credentials hold none. */+const toRecords = (+ row: ConnectorRowSlice,+ stored: StoredCredentials | null,+): ConnectorLinkRecord[] => {+ if (!stored) return [];+ if (isConnectorOAuthAccounts(stored)) return stored.accounts;+ if (stored.type !== 'oauth2') return [];+ const { idToken: _idToken, ...credentials } = stored;+ return [+ {+ createdAt: row.createdAt.getTime(),+ credentials,+ id: LEGACY_LINK_ID,+ name: 'Default',+ status: row.status === ConnectorStatus.error ? 'error' : 'connected',+ userId: row.userId,+ },+ ];+};++const toLink = (connectorId: string, record: ConnectorLinkRecord): DecryptedConnectorLink => ({+ createdAt: new Date(record.createdAt),+ credentials: { ...record.credentials },+ externalAccountId: record.externalAccountId ?? null,+ id: record.id,+ name: record.name,+ profile: record.profile ?? null,+ status: record.status,+ tokenExpiresAt: record.credentials.expiresAt ? new Date(record.credentials.expiresAt) : null,+ userConnectorId: connectorId,+ userId: record.userId,+});++/** Earliest known expiry among the accounts, kept in `token_expires_at`. */+const earliestExpiry = (records: ConnectorLinkRecord[]): Date | null => {+ const expiries = records+ .map((record) => record.credentials.expiresAt)+ .filter((expiresAt): expiresAt is number => typeof expiresAt === 'number');+ return expiries.length ? new Date(Math.min(...expiries)) : null;+};++const toStoredCredentials = (credentials: OAuthCredentials): ConnectorLinkRecord['credentials'] => {+ const { idToken: _idToken, ...persisted } = credentials;+ return persisted;+};++/**+ * The OAuth accounts of connectors. They are stored together, encrypted, in+ * the connector's own `credentials` column, so a connector holds either static+ * credentials or OAuth accounts, never both, and an account follows its+ * connector through every copy and delete.+ *+ * Every change locks the connector row, re-reads its accounts, changes the+ * one it targets and writes them back in one transaction: two accounts+ * refreshed at the same time must not overwrite each other's rotated tokens.+ * The same lock serialises these changes with `ConnectorModel.update`.+ */+export class ConnectorLinkModel {+ constructor(+ private db: LobeChatDatabase,+ private userId: string,+ private workspaceId?: string,+ private gateKeeper?: GateKeeper,+ ) {}++ private scope = (db: LobeChatDatabase = this.db) =>+ connectorAccessScope(db, { userId: this.userId, workspaceId: this.workspaceId });++ /**+ * Decrypt a connector's stored credentials. `strict` throws on a value that+ * cannot be read instead of reading it as none, so a change never replaces+ * credentials it could not read.+ */+ private readStored = async (+ ciphertext: string | null,+ strict = false,+ ): Promise<StoredCredentials | null> => {+ if (!ciphertext) return null;+ try {+ const plain = this.gateKeeper+ ? (await this.gateKeeper.decrypt(ciphertext)).plaintext+ : ciphertext;+ return JSON.parse(plain) as StoredCredentials;+ } catch (error) {+ if (strict) throw error;+ return null;+ }+ };++ private encrypt = (records: ConnectorLinkRecord[]): Promise<string> => {+ const plain = JSON.stringify({+ accounts: records,+ type: 'oauth2',+ } satisfies ConnectorOAuthAccounts);+ return this.gateKeeper ? this.gateKeeper.encrypt(plain) : Promise.resolve(plain);+ };++ /**+ * Change the accounts of one connector under its row lock. `change` gets the+ * current accounts and returns the ones to store, or no `records` to leave+ * the row untouched; a connector left without any reads as disconnected.+ */+ private mutate = <T>(+ connectorId: string,+ change: (records: ConnectorLinkRecord[]) => { records?: ConnectorLinkRecord[]; result: T },+ ): Promise<T> =>+ this.db.transaction(async (tx) => {+ const [row] = await tx+ .select(rowColumns)+ .from(userConnectors)+ .where(and(eq(userConnectors.id, connectorId), this.scope(tx)))+ .for('update');+ if (!row) throw new ConnectorLinkNotFoundError('Connector not found');++ const { records, result } = change(+ toRecords(row, await this.readStored(row.credentials, true)),+ );+ if (!records) return result;+ await tx+ .update(userConnectors)+ .set({+ credentials: records.length ? await this.encrypt(records) : null,+ tokenExpiresAt: earliestExpiry(records),+ ...(!records.length && { status: ConnectorStatus.disconnected }),+ updatedAt: new Date(),+ })+ .where(eq(userConnectors.id, row.id));+ return result;+ });++ /** The accounts of the given connectors the caller may reach, oldest first per connector. */+ listByConnectorIds = async (ids: string[]): Promise<DecryptedConnectorLink[]> => {+ if (!ids.length) return [];+ const rows = await this.db+ .select(rowColumns)+ .from(userConnectors)+ .where(and(inArray(userConnectors.id, ids), this.scope()));+ const order = new Map(ids.map((id, index) => [id, index]));+ rows.sort((a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0));++ const links = (+ await pMap(+ rows,+ async (row) =>+ toRecords(row, await this.readStored(row.credentials))+ .sort((a, b) => a.createdAt - b.createdAt)+ .map((record) => toLink(row.id, record)),+ { concurrency: DECRYPT_CONCURRENCY },+ )+ ).flat();+ if (!links.length) return links;++ const authorizers = await this.db+ .select({+ avatar: users.avatar,+ id: users.id,+ name: sql<string | null>`COALESCE(${users.fullName}, ${users.username})`,+ })+ .from(users)+ .where(inArray(users.id, [...new Set(links.map((link) => link.userId))]));+ const byId = new Map(authorizers.map((user) => [user.id, user]));+ return links.map((link) => ({+ ...link,+ authorizedByAvatar: byId.get(link.userId)?.avatar ?? null,+ authorizedByName: byId.get(link.userId)?.name ?? null,+ }));+ };++ findById = async (connectorId: string, linkId: string): Promise<DecryptedConnectorLink | null> =>+ (await this.listByConnectorIds([connectorId])).find((link) => link.id === linkId) ?? null;++ /**+ * Store one completed authorization. The signed-in identity decides the+ * account: one already connected is refreshed even when another was targeted;+ * otherwise the targeted account, or a new one. A name taken from the+ * previous identity follows the new one; a name the user chose stays. OAuth+ * replaces any static credential the connector still carried.+ */+ applyAuthorization = (+ connectorId: string,+ params: ConnectorLinkAuthorization,+ ): Promise<ConnectorLinkAuthorizationResult> =>+ this.mutate<ConnectorLinkAuthorizationResult>(connectorId, (records) => {+ const { target } = params;+ const requested =+ target.kind === 'existing' ? records.find((r) => r.id === target.linkId) : undefined;+ if (target.kind === 'existing' && !requested)+ throw new ConnectorLinkNotFoundError('Connector account no longer exists');+ const matched = params.identity?.externalAccountId+ ? records.find((r) => r.externalAccountId === params.identity!.externalAccountId)+ : undefined;+ const current = matched ?? requested;+ const values = {+ credentials: toStoredCredentials(params.credentials),+ // The identity of the token stored now, never an older token's: one+ // kept from before would let a later authorization of that identity+ // match this account and overwrite the token it holds now.+ externalAccountId: params.identity?.externalAccountId ?? undefined,+ profile: params.identity?.profile ?? undefined,+ status: 'connected' as const,+ userId: params.authorizerId,+ };+ const displayName = deriveLinkDisplayName(params.identity?.profile);++ if (!current) {+ const created: ConnectorLinkRecord = {+ ...values,+ createdAt: Date.now(),+ id: idGenerator('connectorLinks'),+ name: allocateLinkName(+ records.map((r) => r.name),+ displayName,+ ),+ };+ return {+ records: [...records, created],+ result: { linkId: created.id, outcome: 'created' },+ };+ }++ const name =+ displayName && current.name === deriveLinkDisplayName(current.profile)+ ? allocateLinkName(+ records.filter((r) => r.id !== current.id).map((r) => r.name),+ displayName,+ )+ : current.name;+ return {+ records: records.map((r) => (r.id === current.id ? { ...r, ...values, name } : r)),+ result: {+ linkId: current.id,+ outcome: current.id === requested?.id ? 'reauthorized' : 'matchedExisting',+ },+ };+ });++ /** Store refreshed tokens of one account; a removed account is left removed. */+ updateCredentials = async (+ connectorId: string,+ linkId: string,+ credentials: OAuthCredentials,+ ): Promise<void> => {+ await this.mutate(connectorId, (records) => ({+ records: records.some((r) => r.id === linkId)+ ? records.map((r) =>+ r.id === linkId+ ? {+ ...r,+ credentials: toStoredCredentials(credentials),+ status: 'connected' as const,+ }+ : r,+ )+ : undefined,+ result: undefined,+ }));+ };++ updateStatus = async (+ connectorId: string,+ linkId: string,+ status: ConnectorLinkStatus,+ ): Promise<void> => {+ await this.mutate(connectorId, (records) => ({+ records: records.some((r) => r.id === linkId && r.status !== status)+ ? records.map((r) => (r.id === linkId ? { ...r, status } : r))+ : undefined,+ result: undefined,+ }));+ };++ rename = async (connectorId: string, linkId: string, name: string): Promise<void> => {+ const trimmed = name.trim();+ if (!trimmed || trimmed.length > MAX_LINK_NAME_LENGTH)+ throw new Error(`Account name must contain 1–${MAX_LINK_NAME_LENGTH} characters`);+ await this.mutate(connectorId, (records) => {+ if (!records.some((r) => r.id === linkId))+ throw new ConnectorLinkNotFoundError('Connector account not found');+ if (records.some((r) => r.id !== linkId && r.name === trimmed))+ throw new ConnectorLinkNameTakenError('An account with this name already exists');+ return {+ records: records.map((r) => (r.id === linkId ? { ...r, name: trimmed } : r)),+ result: undefined,+ };+ });+ };++ /**+ * Remove one account; reports how many its connector has left, `undefined`+ * when it has no such account.+ */+ remove = (connectorId: string, linkId: string): Promise<{ remaining: number } | undefined> =>+ this.mutate(connectorId, (records) => {+ if (!records.some((r) => r.id === linkId)) return { result: undefined };+ const remaining = records.filter((r) => r.id !== linkId);+ return { records: remaining, result: { remaining: remaining.length } };+ });+}diff --git a/packages/database/src/schemas/connector.ts b/packages/database/src/schemas/connector.tsindex f4bd7a45324..fffb0e6d48f 100644--- a/packages/database/src/schemas/connector.ts+++ b/packages/database/src/schemas/connector.ts@@ -1,4 +1,9 @@-import type { ConnectorVisibility, CustomPluginParams, ToolManifest } from '@lobechat/types';+import type {+ ConnectorOIDCConfig,+ ConnectorVisibility,+ CustomPluginParams,+ ToolManifest,+} from '@lobechat/types';import { sql } from 'drizzle-orm';import {boolean,@@ -21,66 +26,9 @@ import { workspaces } from './workspace';// user_connectors — types & consts// ─────────────────────────────────────────────────────────────────────────────-export interface OIDCConfig {- authorizationEndpoint?: string;-- /**- * Client identifier.- * - pre_registration: filled in by the user- * - dcr: written back after dynamic registration succeeds- * - client_id_metadata_document: this value IS the metadata URL- */- clientId?: string;-- /**- * Client secret for confidential clients.- * - pre_registration: filled in by the user- * - dcr: written back after dynamic registration succeeds- * Stored in plaintext (non-token credential); access/refresh tokens live- * encrypted in `credentials` instead.- */- clientSecret?: string;-- /** OIDC discovery issuer URL — preferred over manual endpoint overrides */- issuer?: string;- redirectUri?: string;- /** DCR only (RFC 7591) — dynamic client registration endpoint */- registrationEndpoint?: string;-- scheme: 'pre_registration' | 'dcr' | 'client_id_metadata_document';- scopes?: string[];- tokenEndpoint?: string;-- /**- * How the client authenticates at the token endpoint. DCR records the method- * the server registered; otherwise it is learned from the first successful- * exchange. Servers that enforce the registered method reject any other one.- */- tokenEndpointAuthMethod?: 'client_secret_basic' | 'client_secret_post' | 'none';-- /** Recommended for public clients */- usePKCE?: boolean;-}--/**- * Decrypted shape of the `credentials` column.- * Encrypted at rest via KeyVaultsGateKeeper (same as messengerInstallations).- */-export type ConnectorCredentials =- | {- type: 'oauth2';- accessToken: string;- refreshToken?: string;- clientSecret?: string;- /** DCR — token for managing the dynamic registration */- registrationAccessToken?: string;- expiresAt?: number;- scope?: string;- idToken?: string;- }- | { type: 'bearer'; token: string }- | { type: 'apikey'; apiKey: string }- | { type: 'header'; headers: Record<string, string> };+/** Declared in `@lobechat/types`; re-exported for the existing schema imports. */+export type OIDCConfig = ConnectorOIDCConfig;+export type { ConnectorCredentials } from '@lobechat/types';export const ConnectorSourceType = {builtin: 'builtin',@@ -236,7 +184,13 @@ export const userConnectors = pgTable(oidcConfig: jsonb('oidc_config').$type<OIDCConfig>(),// ── Encrypted credentials ─────────────────────────────────────────────+ /**+ * Static credentials, or every OAuth account of the connector together+ * (`ConnectorOAuthAccounts`). Accounts are read and changed through+ * `ConnectorLinkModel` only, which locks this row for each change.+ */credentials: text('credentials'),+ /** Earliest expiry among the stored OAuth tokens. */tokenExpiresAt: timestamptz('token_expires_at'),/** Safe non-sensitive metadata for display and future extensibility */diff --git a/packages/database/src/utils/idGenerator.ts b/packages/database/src/utils/idGenerator.tsindex 4642422cdc8..bfa4639d94f 100644--- a/packages/database/src/utils/idGenerator.ts+++ b/packages/database/src/utils/idGenerator.ts@@ -6,6 +6,7 @@ export const createNanoId = (size = 8) =>customAlphabet('1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', size);const prefixes = {+ connectorLinks: 'lnk',agentCronJobs: 'cron',agentSkills: 'skl',agentHistoryJobs: 'ahj',diff --git a/packages/electron-client-ipc/src/types/connectorOAuth.ts b/packages/electron-client-ipc/src/types/connectorOAuth.tsindex fabaa6a454e..1cf69d30bc3 100644--- a/packages/electron-client-ipc/src/types/connectorOAuth.ts+++ b/packages/electron-client-ipc/src/types/connectorOAuth.ts@@ -1,6 +1,7 @@export interface ConnectorOAuthRequest {authorizationUrl: string;connectorId: string;+ freshSession?: boolean;requestId?: string;}diff --git a/packages/locales/src/default/tool.ts b/packages/locales/src/default/tool.tsindex d61e0e503a4..01e248ce415 100644--- a/packages/locales/src/default/tool.ts+++ b/packages/locales/src/default/tool.ts@@ -83,6 +83,57 @@ export default {'codeInterpreter.files': 'Files:','codeInterpreter.output': 'Output:','codeInterpreter.returnValue': 'Return Value:',+ 'connector.account.alreadyConnected': '“{{name}}” is already connected',+ 'connector.account.alreadyConnectedDesc':+ 'No account was added. To connect a different one, sign in to the provider with that account and try again.',+ 'connector.account.alreadyConnectedUnnamed': 'This account is already connected',+ 'connector.account.authorizedBy': 'Authorized by {{name}}',+ 'connector.account.connect': 'Connect account',+ 'connector.account.connectAnother': 'Connect another account',+ 'connector.account.connectFailed': "Couldn't connect the account. {{reason}}",+ 'connector.account.connected': 'Connected “{{name}}”',+ 'connector.account.editDropsAccount':+ 'Changing the server URL or OAuth client removes the connected account. Saving will authorize again.',+ 'connector.account.editDropsAccounts':+ 'Changing the server URL or OAuth client removes all {{count}} connected accounts. Saving authorizes one of them again; reconnect the others under Accounts afterwards.',+ 'connector.account.editKeepsAccounts':+ "Saving keeps the connected accounts. To re-authorize one or connect another, go to Accounts on the connector's page.",+ 'connector.account.empty':+ "No account connected yet. Connect one so the AI can use this connector's tools.",+ 'connector.account.error.authFailed':+ "Authorization didn't complete. Try again, or check this connector's OAuth settings.",+ 'connector.account.error.retry': 'Try again.',+ 'connector.account.error.timeout': 'Authorization timed out. Try again.',+ 'connector.account.more': 'More actions',+ 'connector.account.namingHint':+ 'The AI picks an account by its name, so give each one a name that tells them apart.',+ 'connector.account.needsReauth_one': '{{count}} account needs re-authorization',+ 'connector.account.needsReauth_other': '{{count}} accounts need re-authorization',+ 'connector.account.reauthorize': 'Re-authorize',+ 'connector.account.reauthorizeFailed': "Couldn't re-authorize “{{name}}”. {{reason}}",+ 'connector.account.reauthorizeMismatch': "“{{name}}” wasn't updated",+ 'connector.account.reauthorizeMismatchDesc':+ 'You signed in as “{{matched}}”, which is connected separately, so its authorization was refreshed instead. To re-authorize “{{name}}”, sign in with that account.',+ 'connector.account.reauthorized': 'Re-authorized “{{name}}”',+ 'connector.account.remove': 'Remove',+ 'connector.account.removeConfirmContent':+ 'The AI will no longer use this account. You can connect it again later.',+ 'connector.account.removeConfirmOk': 'Remove account',+ 'connector.account.removeConfirmTitle': 'Remove “{{name}}”?',+ 'connector.account.removeFailed': "Couldn't remove “{{name}}”; it's still connected. {{reason}}",+ 'connector.account.removeLastConfirmContent':+ "This is the only connected account. Once it's removed, this connector's tools stop working until you connect an account again.",+ 'connector.account.rename': 'Rename',+ 'connector.account.renameConflict':+ 'This connector already has an account named “{{name}}”. Choose another name.',+ 'connector.account.renameDesc':+ 'The AI sees this name when choosing an account. Up to 64 characters, unique within this connector.',+ 'connector.account.renameFailed': "Couldn't rename the account. {{reason}}",+ 'connector.account.renameTitle': 'Rename account',+ 'connector.account.switchHint':+ "Connecting uses the account you're signed in to on the provider's site in this browser. To connect a different one, switch accounts there first.",+ 'connector.account.title': 'Accounts',+ 'connector.account.usingAccount': 'Account: {{name}}','connector.actionFailed': 'Operation failed, please try again','connector.error.network':'The network connection was interrupted. Check your connection and try again.',diff --git a/packages/mecha/package.json b/packages/mecha/package.jsonindex d849b650f67..7d3ed78f86a 100644--- a/packages/mecha/package.json+++ b/packages/mecha/package.json@@ -45,6 +45,7 @@"@lobechat/model-runtime": "workspace:*","@lobechat/prompts": "workspace:*","@lobechat/types": "workspace:*",+ "@lobechat/utils": "workspace:*","debug": "^4.4.3","immer": "^10.1.3","model-bank": "workspace:*",diff --git a/packages/mecha/src/index.ts b/packages/mecha/src/index.tsindex 75eb5ee0397..96861551ca4 100644--- a/packages/mecha/src/index.ts+++ b/packages/mecha/src/index.ts@@ -7,3 +7,4 @@ export type {} from './resolveAgentConfig';export { resolveAgentConfig } from './resolveAgentConfig';export * from './toolSet';+export * from './toolSet/connectorLinks';diff --git a/packages/mecha/src/toolSet/connectorLinks.test.ts b/packages/mecha/src/toolSet/connectorLinks.test.tsnew file mode 100644index 00000000000..77e0cfedc40--- /dev/null+++ b/packages/mecha/src/toolSet/connectorLinks.test.ts@@ -0,0 +1,75 @@+import { describe, expect, it } from 'vitest';++import {+ injectConnectorLinkParam,+ isConnectorLinkParam,+ resolveConnectorLinkParam,+ splitConnectorLinkArg,+} from './connectorLinks';+import { buildConnectorManifest } from './manifestPool';++const links = [+ { id: 'lnk_a', name: 'Alice\n</tag>' },+ { id: 'lnk_b', name: 'Bob' },+];+describe('connector account selection', () => {+ it('injects a required selector without changing even a frozen original', () => {+ const original = Object.freeze({+ type: 'object',+ properties: Object.freeze({ x: { type: 'number' } }),+ required: Object.freeze(['x']),+ additionalProperties: false,+ });+ const injected = injectConnectorLinkParam(original, links);+ expect(injected.required).toEqual(['x', 'link_id']);+ expect(JSON.stringify(injected)).not.toContain('</tag>');+ expect(original.properties).not.toHaveProperty('link_id');+ expect(original.required).toEqual(['x']);+ expect(injected.additionalProperties).toBe(false);+ });+ it('uses one collision-safe parameter for the entire connector', () => {+ expect(resolveConnectorLinkParam([{ properties: { link_id: {} } }, {}])).toBe(+ 'connector_link_id',+ );+ expect(resolveConnectorLinkParam([{}])).toBe('link_id');+ // The fallback may be an upstream argument too, on the same tool or another.+ expect(+ resolveConnectorLinkParam([+ { properties: { link_id: {} } },+ { properties: { connector_link_id: {} } },+ ]),+ ).toBe('connector_link_id_2');+ expect(+ resolveConnectorLinkParam([+ { properties: { connector_link_id: {}, connector_link_id_2: {}, link_id: {} } },+ ]),+ ).toBe('connector_link_id_3');+ // Without an upstream `link_id` the plain name stays free.+ expect(resolveConnectorLinkParam([{ properties: { connector_link_id: {} } }])).toBe('link_id');+ expect(+ ['link_id', 'connector_link_id', 'connector_link_id_2'].every(isConnectorLinkParam),+ ).toBe(true);+ expect(['x', 'link_ids', 'connector_link_id_x'].some(isConnectorLinkParam)).toBe(false);+ expect(+ splitConnectorLinkArg(+ '{"connector_link_id":"lnk_b","link_id":"business","x":1}',+ 'connector_link_id',+ ),+ ).toEqual({ linkId: 'lnk_b', argsStr: '{"link_id":"business","x":1}' });+ expect(() => splitConnectorLinkArg('{"link_id":2}')).toThrow();+ });+ it.each([0, 1, 2])('injects only when there are more than one total links (%i)', (count) => {+ const manifest = buildConnectorManifest({+ identifier: 'test',+ name: 'Test',+ isEnabled: true,+ links: links.slice(0, count),+ tools: [+ { toolName: 'echo', inputSchema: { type: 'object' } },+ { toolName: 'blocked', permission: 'disabled' },+ ],+ });+ expect(manifest!.api[0].parameters.required).toEqual(count > 1 ? ['link_id'] : undefined);+ expect(manifest!.api[1].parameters.required).toBeUndefined();+ });+});diff --git a/packages/mecha/src/toolSet/connectorLinks.ts b/packages/mecha/src/toolSet/connectorLinks.tsnew file mode 100644index 00000000000..0fb795901c2--- /dev/null+++ b/packages/mecha/src/toolSet/connectorLinks.ts@@ -0,0 +1,63 @@+import { isRecord } from '@lobechat/utils/object';++export const CONNECTOR_LINK_ID_PARAM = 'link_id';+export interface ConnectorLinkChoice {+ id: string;+ name: string;+}+export const sanitizeConnectorPromptText = (value: string): string =>+ value.replaceAll(/\s+/g, ' ').replaceAll(/[<>]/g, '').trim().slice(0, 120);++const CONNECTOR_LINK_ID_FALLBACK_PARAM = 'connector_link_id';++/** Whether an argument name is one the account selector can take. */+export const isConnectorLinkParam = (name: string): boolean =>+ name === CONNECTOR_LINK_ID_PARAM || /^connector_link_id(?:_\d+)?$/.test(name);++/**+ * The selector name for one connector: `link_id`, unless a tool of the+ * connector declares that argument itself, then the first of+ * `connector_link_id`, `connector_link_id_2`, … that no tool declares. A name+ * a tool already uses would overwrite its schema and strip its argument.+ */+export const resolveConnectorLinkParam = (schemas: readonly unknown[]): string => {+ const declared = new Set<string>();+ for (const schema of schemas) {+ if (!isRecord(schema) || !isRecord(schema.properties)) continue;+ for (const name of Object.keys(schema.properties)) declared.add(name);+ }+ if (!declared.has(CONNECTOR_LINK_ID_PARAM)) return CONNECTOR_LINK_ID_PARAM;+ if (!declared.has(CONNECTOR_LINK_ID_FALLBACK_PARAM)) return CONNECTOR_LINK_ID_FALLBACK_PARAM;+ for (let suffix = 2; ; suffix++) {+ const name = `${CONNECTOR_LINK_ID_FALLBACK_PARAM}_${suffix}`;+ if (!declared.has(name)) return name;+ }+};++export const injectConnectorLinkParam = (+ schema: Record<string, unknown>,+ links: readonly ConnectorLinkChoice[],+ param = CONNECTOR_LINK_ID_PARAM,+): Record<string, unknown> => ({+ ...schema,+ properties: {+ ...(isRecord(schema.properties) ? schema.properties : {}),+ [param]: {+ description: `Select a ${param} from these accounts: ${JSON.stringify(links.map((link) => ({ link_id: link.id, link_name: sanitizeConnectorPromptText(link.name) })))}`,+ type: 'string',+ },+ },+ required: [...new Set([...(Array.isArray(schema.required) ? schema.required : []), param])],+});++export const splitConnectorLinkArg = (+ argsStr: string,+ param = CONNECTOR_LINK_ID_PARAM,+): { argsStr: string; linkId?: string } => {+ const args: unknown = JSON.parse(argsStr || '{}');+ if (!isRecord(args) || !Object.hasOwn(args, param)) return { argsStr };+ const { [param]: linkId, ...rest } = args;+ if (typeof linkId !== 'string' || !linkId.trim())+ throw new Error(`${param} must be a non-empty string`);+ return { argsStr: JSON.stringify(rest), linkId };+};diff --git a/packages/mecha/src/toolSet/manifestPool.ts b/packages/mecha/src/toolSet/manifestPool.tsindex cf25bf330d9..6347bb141d3 100644--- a/packages/mecha/src/toolSet/manifestPool.ts+++ b/packages/mecha/src/toolSet/manifestPool.ts@@ -4,6 +4,8 @@ import type { LobeToolManifest } from '@lobechat/context-engine';import type { BuiltinToolResolveContext, LobeBuiltinTool } from '@lobechat/types';import debug from 'debug';+import { injectConnectorLinkParam, resolveConnectorLinkParam } from './connectorLinks';+const log = debug('mecha:manifestPool');/** A connector tool's permission as the connectors settings store it. */@@ -24,6 +26,7 @@ export interface ConnectorToolFacts {export interface ConnectorFacts {identifier: string;isEnabled?: boolean | null;+ links?: { id: string; name: string }[];name: string;tools: ConnectorToolFacts[];}@@ -115,6 +118,7 @@ export const buildConnectorManifest = (: [];if (modelTools.length === 0 && !entries.length) return undefined;+ const param = resolveConnectorLinkParam(connector.tools.map((tool) => tool.inputSchema));const api = modelTools.map((tool) => {const parameters = (tool.inputSchema ?? { properties: {}, type: 'object' }) as Record<string,@@ -127,7 +131,11 @@ export const buildConnectorManifest = (: (tool.description ?? ''),humanIntervention: connectorToolIntervention(tool),name: tool.toolName,- parameters,+ // A disabled tool's call is refused whatever it names: no account to select+ parameters:+ (connector.links?.length ?? 0) > 1 && tool.permission !== 'disabled'+ ? injectConnectorLinkParam(parameters, connector.links!, param)+ : parameters,};});diff --git a/packages/types/src/connector.ts b/packages/types/src/connector.tsnew file mode 100644index 00000000000..24dc46edfde--- /dev/null+++ b/packages/types/src/connector.ts@@ -0,0 +1,104 @@+export type ConnectorLinkStatus = 'connected' | 'error';+export type ConnectorAuthKind = 'oauth2' | 'bearer' | 'apikey' | 'header' | 'none';++export interface ConnectorLinkProfile {+ avatar?: string;+ email?: string;+ name?: string;+ username?: string;+}++/** OAuth/OIDC client configuration of a connector (`user_connectors.oidc_config`). */+export interface ConnectorOIDCConfig {+ authorizationEndpoint?: string;++ /**+ * Client identifier.+ * - pre_registration: filled in by the user+ * - dcr: written back after dynamic registration succeeds+ * - client_id_metadata_document: this value IS the metadata URL+ */+ clientId?: string;++ /**+ * Client secret for confidential clients.+ * - pre_registration: filled in by the user+ * - dcr: written back after dynamic registration succeeds+ * Stored in plaintext (non-token credential); access/refresh tokens live+ * encrypted in `credentials` instead.+ */+ clientSecret?: string;++ /** OIDC discovery issuer URL — preferred over manual endpoint overrides */+ issuer?: string;+ redirectUri?: string;+ /** DCR only (RFC 7591) — dynamic client registration endpoint */+ registrationEndpoint?: string;++ scheme: 'pre_registration' | 'dcr' | 'client_id_metadata_document';+ scopes?: string[];+ tokenEndpoint?: string;++ /**+ * How the client authenticates at the token endpoint. DCR records the method+ * the server registered; otherwise it is learned from the first successful+ * exchange. Servers that enforce the registered method reject any other one.+ */+ tokenEndpointAuthMethod?: 'client_secret_basic' | 'client_secret_post' | 'none';++ /** Recommended for public clients */+ usePKCE?: boolean;+}++/**+ * Decrypted shape of a connector's `credentials` column, except for a connector+ * holding OAuth accounts ({@link ConnectorOAuthAccounts}). A single `oauth2`+ * value is the slot written before accounts existed; it reads as one account.+ * Encrypted at rest via KeyVaultsGateKeeper (same as messengerInstallations).+ */+export type ConnectorCredentials =+ | {+ type: 'oauth2';+ accessToken: string;+ refreshToken?: string;+ clientSecret?: string;+ /** DCR — token for managing the dynamic registration */+ registrationAccessToken?: string;+ expiresAt?: number;+ scope?: string;+ idToken?: string;+ }+ | { type: 'bearer'; token: string }+ | { type: 'apikey'; apiKey: string }+ | { type: 'header'; headers: Record<string, string> };++export type ConnectorOAuthCredentials = Extract<ConnectorCredentials, { type: 'oauth2' }>;++/** One OAuth account connected to a connector, stored in {@link ConnectorOAuthAccounts}. */+export interface ConnectorLinkRecord {+ /** Epoch ms; accounts are listed in this order. */+ createdAt: number;+ /** `id_token` is transient identity input and never stored. */+ credentials: Omit<ConnectorOAuthCredentials, 'idToken'>;+ /** Provider identity used to recognise the same account again. */+ externalAccountId?: string;+ /** `lnk_…`, unique within the connector; the `link_id` the model selects an account with. */+ id: string;+ /** Stored display name, unique within the connector. */+ name: string;+ profile?: ConnectorLinkProfile;+ status: ConnectorLinkStatus;+ /** The member who authorized this account. */+ userId: string;+}++/**+ * Decrypted `credentials` of a connector holding OAuth accounts: all of them,+ * encrypted together on the connector row. `type` stays `oauth2` so code that+ * strips OAuth tokens before returning a connector's credentials (and code of+ * an earlier release) strips these too.+ */+export interface ConnectorOAuthAccounts {+ accounts: ConnectorLinkRecord[];+ type: 'oauth2';+}diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex 36d345994d0..597e4fd7143 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -96,6 +96,7 @@ export * from './acceptanceFlow';export * from './acceptanceReview';export * from './acceptanceReviewRound';export * from './agentRuntime';+export * from './connector';export * from './inboundWebhook';export * from './oauthApp';export * from './openai/chat';diff --git a/packages/types/src/tool/manifest.ts b/packages/types/src/tool/manifest.tsindex 1a902440447..baa1e697807 100644--- a/packages/types/src/tool/manifest.ts+++ b/packages/types/src/tool/manifest.ts@@ -20,6 +20,7 @@ export interface ToolManifest {$schema?: string;api: LobeChatPluginApi[];author?: string;+ connectorLinks?: { connectorId: string; param: string };createdAt?: string;gateway?: string;homepage?: string;@@ -44,6 +45,7 @@ export interface ToolManifest {export const ToolManifestSchema = z.object({$schema: z.string().optional(),api: z.array(LobeChatPluginApiSchema),+ connectorLinks: z.object({ connectorId: z.string(), param: z.string() }).optional(),author: z.string().optional(),createdAt: z.string().optional(),gateway: z.string().optional(),diff --git a/src/app/(backend)/oauth/connector/callback/route.test.ts b/src/app/(backend)/oauth/connector/callback/route.test.tsindex 80b707bf444..50d2828f873 100644--- a/src/app/(backend)/oauth/connector/callback/route.test.ts+++ b/src/app/(backend)/oauth/connector/callback/route.test.ts@@ -8,17 +8,34 @@ import { ConnectorToolModel } from '@/database/models/connectorTool';import { GET } from './route';-const { mockConsume, mockDiscover, mockExchange, mockFindById, mockSync, mockUpdate } = vi.hoisted(- () => ({- mockConsume: vi.fn(),- mockDiscover: vi.fn().mockResolvedValue({ token_endpoint: 'https://as/token' }),- mockExchange: vi.fn(),- mockFindById: vi.fn(),- mockSync: vi.fn(),- mockUpdate: vi.fn(),- }),-);+const {+ mockConsume,+ mockDiscover,+ mockExchange,+ mockFindById,+ mockSync,+ mockUpdate,+ mockListLinks,+ mockApplyAuthorization,+} = vi.hoisted(() => ({+ mockConsume: vi.fn(),+ mockListLinks: vi.fn(),+ mockApplyAuthorization: vi.fn(),+ mockDiscover: vi.fn().mockResolvedValue({ token_endpoint: 'https://as/token' }),+ mockExchange: vi.fn(),+ mockFindById: vi.fn(),+ mockSync: vi.fn(),+ mockUpdate: vi.fn(),+}));+vi.mock('@/database/models/connectorLink', () => ({+ ConnectorLinkModel: vi.fn(function () {+ return { applyAuthorization: mockApplyAuthorization, listByConnectorIds: mockListLinks };+ }),+}));+vi.mock('@/server/services/connector/identity', () => ({+ resolveLinkIdentity: async () => undefined,+}));vi.mock('@/database/server', () => ({ serverDB: {} }));vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'https://app.example.com' } }));vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({@@ -37,8 +54,10 @@ vi.mock('@/server/services/connector/tokens', () => ({.fn().mockReturnValue({ credentials: { accessToken: 'tok', type: 'oauth2' }, tokenExpiresAt: null }),}));+const mockSaveCompletion = vi.hoisted(() => vi.fn());vi.mock('@/server/services/connector/stateStore', () => ({consumeConnectorOAuthState: mockConsume,+ saveConnectorOAuthCompletion: mockSaveCompletion,}));vi.mock('@/database/models/connector', () => ({ConnectorModel: vi.fn(function () {@@ -55,6 +74,14 @@ const makeReq = (query = 'code=abc&state=xyz') =>beforeEach(() => {vi.clearAllMocks();+ mockListLinks.mockResolvedValue([]);+ mockApplyAuthorization+ .mockReset()+ .mockImplementation(async (_id, { target }) =>+ target.kind === 'existing'+ ? { linkId: target.linkId, outcome: 'reauthorized' }+ : { linkId: 'lnk_1', outcome: 'created' },+ );mockConsume.mockResolvedValue({authorizationServerUrl: 'https://as',codeVerifier: 'v',@@ -70,6 +97,7 @@ beforeEach(() => {},});mockUpdate.mockResolvedValue(undefined);+ mockSaveCompletion.mockResolvedValue(undefined);mockExchange.mockResolvedValue({ tokens: { access_token: 'tok' } });vi.spyOn(console, 'error').mockImplementation(() => {});});@@ -96,6 +124,8 @@ describe('connector OAuth callback', () => {const expected = {connectorId: 'c1',+ linkId: 'lnk_1',+ outcome: 'created',success: true,synced: true,type: 'lobe-connector-oauth',@@ -107,6 +137,46 @@ describe('connector OAuth callback', () => {},);+ it('reauthorizes the earliest link for a legacy OAuth state without linkTarget', async () => {+ mockListLinks.mockResolvedValue([+ { id: 'lnk_early', status: 'error' },+ { id: 'lnk_late', status: 'connected' },+ ]);+ const body = await (await GET(makeReq())).text();+ expect(body).toContain('"success":true');+ expect(body).toContain('"linkId":"lnk_early"');+ expect(body).toContain('"outcome":"reauthorized"');+ });++ it('creates the first account for a legacy OAuth state when no links exist', async () => {+ const body = await (await GET(makeReq())).text();+ expect(body).toContain('"linkId":"lnk_1"');+ expect(body).toContain('"outcome":"created"');+ });++ it('keeps an explicit new-account target even when older links exist', async () => {+ mockConsume.mockResolvedValue({+ authorizationServerUrl: 'https://as',+ codeVerifier: 'v',+ connectorId: 'c1',+ lobeUserId: 'u1',+ linkTarget: { kind: 'new' },+ });+ mockListLinks.mockResolvedValue([{ id: 'lnk_early' }]);+ const body = await (await GET(makeReq())).text();+ expect(body).toContain('"outcome":"created"');+ });++ // The record only serves a window that misses the callback's message+ it('reports a stored authorization as done though recording its outcome failed', async () => {+ mockSaveCompletion.mockRejectedValueOnce(new Error('redis down'));++ const body = await (await GET(makeReq())).text();++ expect(body).toContain('"success":true');+ expect(body).toContain('"outcome":"created"');+ });+it('reports synced:false when auth succeeds but tool sync fails', async () => {mockSync.mockRejectedValue(new Error('mcp down'));@@ -136,6 +206,7 @@ describe('connector OAuth callback', () => {expect(mockSync).toHaveBeenCalledWith('c1',expect.objectContaining({ serverDB, userId: 'u1' }),+ { linkId: 'lnk_1' },);});@@ -202,7 +273,7 @@ describe('connector OAuth callback', () => {await GET(makeReq());- expect(mockUpdate.mock.calls[0][1]).not.toHaveProperty('oidcConfig');+ expect(mockUpdate).not.toHaveBeenCalled();});});diff --git a/src/app/(backend)/oauth/connector/callback/route.ts b/src/app/(backend)/oauth/connector/callback/route.tsindex 54b05d047f4..5e0c95b43e1 100644--- a/src/app/(backend)/oauth/connector/callback/route.ts+++ b/src/app/(backend)/oauth/connector/callback/route.ts@@ -3,16 +3,21 @@ import debug from 'debug';import { type NextRequest, NextResponse } from 'next/server';import { ConnectorModel } from '@/database/models/connector';+import { ConnectorLinkModel } from '@/database/models/connectorLink';import { ConnectorToolModel } from '@/database/models/connectorTool';import { serverDB } from '@/database/server';import { appEnv } from '@/envs/app';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';+import { resolveLinkIdentity } from '@/server/services/connector/identity';import {discoverConnectorAuthorizationServerMetadata,exchangeConnectorCode,toClientInformation,} from '@/server/services/connector/oauth';-import { consumeConnectorOAuthState } from '@/server/services/connector/stateStore';+import {+ consumeConnectorOAuthState,+ saveConnectorOAuthCompletion,+} from '@/server/services/connector/stateStore';import { syncConnectorToolsById } from '@/server/services/connector/sync';import { tokensToCredentials } from '@/server/services/connector/tokens';@@ -57,6 +62,8 @@ const renderResultPage = (result: {success: boolean;/** Whether the tool list synced. `false` = authorized but tools unavailable. */synced?: boolean;+ linkId?: string;+ outcome?: 'created' | 'reauthorized' | 'matchedExisting';}): NextResponse => {const payload = jsonForScript({ type: 'lobe-connector-oauth', ...result });const html = `<!doctype html>@@ -150,15 +157,31 @@ export const GET = async (req: NextRequest) => {resource: connector.mcpServerUrl ?? undefined,});- const { credentials, tokenExpiresAt } = tokensToCredentials(tokens, {+ const { credentials } = tokensToCredentials(tokens, {clientSecret: oidc.clientSecret,});- await connectorModel.update(payload.connectorId, {- credentials: JSON.stringify(credentials),- // Remember the auth method that worked so refreshes don't fail the same way.- ...(authMethod && { oidcConfig: { ...oidc, tokenEndpointAuthMethod: authMethod } }),- tokenExpiresAt,+ if (authMethod)+ await connectorModel.update(payload.connectorId, {+ oidcConfig: { ...oidc, tokenEndpointAuthMethod: authMethod },+ });+ const connectorLinkModel = new ConnectorLinkModel(+ serverDB,+ payload.lobeUserId,+ payload.workspaceId,+ gateKeeper,+ );+ if (credentials.type !== 'oauth2') return renderFailure('invalid_credentials');+ const earliestLink = payload.linkTarget+ ? undefined+ : (await connectorLinkModel.listByConnectorIds([payload.connectorId]))[0];+ const authorization = await connectorLinkModel.applyAuthorization(payload.connectorId, {+ target:+ payload.linkTarget ??+ (earliestLink ? { kind: 'existing', linkId: earliestLink.id } : { kind: 'new' }),+ identity: await resolveLinkIdentity({ tokens, metadata }),+ credentials,+ authorizerId: payload.lobeUserId,});// Sync the tool list server-side so the connector is immediately usable —@@ -171,13 +194,18 @@ export const GET = async (req: NextRequest) => {);let synced = false;try {- const { toolCount } = await syncConnectorToolsById(payload.connectorId, {- connectorModel,- connectorToolModel,- // A connector set to connect through the device lists on the user's device- serverDB,- userId: payload.lobeUserId,- });+ const { toolCount } = await syncConnectorToolsById(+ payload.connectorId,+ {+ connectorModel,+ connectorLinkModel,+ connectorToolModel,+ // A connector set to connect through the device lists on the user's device+ serverDB,+ userId: payload.lobeUserId,+ },+ { linkId: authorization.linkId },+ );synced = true;log('connector %s authorized + synced %d tools', payload.connectorId, toolCount);} catch (err) {@@ -187,7 +215,22 @@ export const GET = async (req: NextRequest) => {log('post-OAuth tool sync failed for connector=%s: %O', payload.connectorId, err);}- return renderResultPage({ connectorId: payload.connectorId, success: true, synced });+ // Only a fallback for a window that misses the result below: the account+ // is stored, so failing to record how the flow ended must not fail it.+ await saveConnectorOAuthCompletion(state, {+ connectorId: payload.connectorId,+ lobeUserId: payload.lobeUserId,+ workspaceId: payload.workspaceId,+ ...authorization,+ }).catch((err) => {+ log('recording the OAuth completion of connector=%s failed: %O', payload.connectorId, err);+ });+ return renderResultPage({+ connectorId: payload.connectorId,+ success: true,+ synced,+ ...authorization,+ });} catch (err) {if (IssuerMismatchError.isInstance(err)) return renderFailure('issuer_mismatch', err);const message = err instanceof Error ? err.message : 'internal_error';diff --git a/src/features/Connectors/ConnectorActionErrorText.tsx b/src/features/Connectors/ConnectorActionErrorText.tsxindex 760f28471b1..0c3053dcb49 100644--- a/src/features/Connectors/ConnectorActionErrorText.tsx+++ b/src/features/Connectors/ConnectorActionErrorText.tsx@@ -4,7 +4,7 @@ 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 { memo, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';import { type ConnectorActionError } from '@/utils/connectorActionError';@@ -27,27 +27,32 @@ const styles = stylex.create({},});+/**+ * Red, in-place reason of a failed action. It stays where the action was taken,+ * so the user still sees what happened after any toast is gone.+ */+export const InlineErrorText = memo<{ children: ReactNode }>(({ children }) => (+ <div role={'alert'} {...stylex.props(styles.error)}>+ <span {...stylex.props(styles.icon)}>+ <Icon icon={CircleAlert} size={12} />+ </span>+ <span>{children}</span>+ </div>+));++InlineErrorText.displayName = 'InlineErrorText';+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.- */+/** A failed connect / remove of a whole connector, worded for the settings list. */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>- );+ return <InlineErrorText>{formatConnectorActionError(t, error, name)}</InlineErrorText>;});ConnectorActionErrorText.displayName = 'ConnectorActionErrorText';diff --git a/src/features/Connectors/ConnectorDetail/ConnectorAccounts.tsx b/src/features/Connectors/ConnectorDetail/ConnectorAccounts.tsxnew file mode 100644index 00000000000..3a57dd61994--- /dev/null+++ b/src/features/Connectors/ConnectorDetail/ConnectorAccounts.tsx@@ -0,0 +1,276 @@+'use client';++import { isDesktop } from '@lobechat/const';+import { ActionIcon, Button, Center, DropdownMenu, Flexbox, Icon, Tag, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import {+ MoreHorizontalIcon,+ PencilIcon,+ PlusIcon,+ RefreshCwIcon,+ Trash2Icon,+ UserRoundIcon,+} from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import Avatar from '@/components/Avatar';+import type { ConnectorLinkSummary, ConnectorWithTools } from '@/store/tool/slices/connector';++import { InlineErrorText } from '../ConnectorActionErrorText';+import { getAccountDetails, getAccountsSectionModel, getRowBusyAction } from './accountsModel';+import ManageTooltip from './ManageTooltip';+import Section from './Section';+import { useConnectorAccountFlows } from './useConnectorAccountFlows';++const AVATAR_SIZE = 28;++const styles = stylex.create({+ empty: {+ color: cssVar.colorTextSecondary,+ fontSize: 13,+ lineHeight: 1.6,+ paddingBlock: 20,+ paddingInline: 16,+ textAlign: 'center',+ },+ glyph: {+ backgroundColor: cssVar.colorFillSecondary,+ borderRadius: '50%',+ color: cssVar.colorTextSecondary,+ flex: 'none',+ height: AVATAR_SIZE,+ width: AVATAR_SIZE,+ },+ hint: {+ color: cssVar.colorTextDescription,+ fontSize: 12,+ lineHeight: 1.5,+ },+ list: {+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: 8,+ borderStyle: 'solid',+ borderWidth: 1,+ paddingInline: 12,+ },+ row: {+ borderBlockEndColor: {+ ':last-child': 'transparent',+ 'default': cssVar.colorBorderSecondary,+ },+ borderBlockEndStyle: 'solid',+ borderBlockEndWidth: 1,+ minHeight: 52,+ paddingBlock: 12,+ },+});++/** An account without a picture keeps one shared glyph, never initials of its name. */+const AccountGlyph = () => (+ <Center {...stylex.props(styles.glyph)}>+ <Icon icon={UserRoundIcon} size={16} />+ </Center>+);++const AccountAvatar = ({ link }: { link: ConnectorLinkSummary }) =>+ link.profile?.avatar ? (+ <Avatar+ avatar={link.profile.avatar}+ brokenFallback={<AccountGlyph />}+ name={link.name}+ shape={'circle'}+ size={AVATAR_SIZE}+ />+ ) : (+ <AccountGlyph />+ );++interface AccountRowProps {+ /** The action running on this row, if any. */+ busyAction?: 'reauthorize' | 'remove';+ details: string;+ disabled: boolean;+ disabledReason?: string;+ link: ConnectorLinkSummary;+ onReauthorize: () => void;+ onRemove: () => void;+ onRename: () => void;+}++const AccountRow = ({+ busyAction,+ details,+ disabled,+ disabledReason,+ link,+ onReauthorize,+ onRemove,+ onRename,+}: AccountRowProps) => {+ const { t } = useTranslation('tool');+ const hasError = link.status === 'error';++ const menuItems = [+ {+ icon: <Icon icon={PencilIcon} />,+ key: 'rename',+ label: t('connector.account.rename'),+ onClick: onRename,+ },+ {+ icon: <Icon icon={RefreshCwIcon} />,+ key: 'reauthorize',+ label: t('connector.account.reauthorize'),+ onClick: onReauthorize,+ },+ { type: 'divider' as const },+ {+ danger: true,+ icon: <Icon icon={Trash2Icon} />,+ key: 'remove',+ label: t('connector.account.remove'),+ onClick: onRemove,+ },+ ];++ // A tap target on mobile too: no account action is hover-only.+ const moreButton = (+ <ActionIcon+ disabled={disabled}+ icon={MoreHorizontalIcon}+ loading={!hasError && !!busyAction}+ size={'small'}+ title={t('connector.account.more')}+ />+ );++ return (+ <Flexbox horizontal align={'center'} gap={12} {...stylex.props(styles.row)}>+ <AccountAvatar link={link} />+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>+ <Text ellipsis strong>+ {link.name}+ </Text>+ {/* The status sits on the second line so a narrow row (with the+ Re-authorize button beside it) never truncates the name first. */}+ {(hasError || details) && (+ <Flexbox horizontal align={'center'} gap={6} style={{ minWidth: 0 }}>+ {hasError && (+ <Tag color={'error'} size={'small'} style={{ flex: 'none' }}>+ {t('connector.authError')}+ </Tag>+ )}+ {details && (+ <Text ellipsis fontSize={12} type={'secondary'}>+ {details}+ </Text>+ )}+ </Flexbox>+ )}+ </Flexbox>+ {/* A broken account's next step is on the row, not behind the menu. */}+ {hasError && (+ <ManageTooltip title={disabledReason}>+ <Button+ disabled={disabled}+ loading={busyAction === 'reauthorize'}+ size={'small'}+ style={{ flex: 'none' }}+ onClick={onReauthorize}+ >+ {t('connector.account.reauthorize')}+ </Button>+ </ManageTooltip>+ )}+ <ManageTooltip title={disabledReason}>+ {disabled ? (+ moreButton+ ) : (+ <DropdownMenu items={menuItems} placement={'bottomRight'}>+ {moreButton}+ </DropdownMenu>+ )}+ </ManageTooltip>+ </Flexbox>+ );+};++interface ConnectorAccountsProps {+ /** Account writes follow the connector's maintenance gate (`assertConnectorMaintainable`). */+ canManage: boolean;+ connector: ConnectorWithTools;+ /** Why the controls are disabled, shown on hover; absent while the gate is loading. */+ disabledReason?: string;+}++/**+ * The OAuth accounts connected to one connector. Each account is a `link_id`+ * the model picks by name once there is more than one, so the names here are+ * what the model reads. Mount it keyed by connector id so a running flow's+ * state never shows on another connector.+ */+const ConnectorAccounts = ({ canManage, connector, disabledReason }: ConnectorAccountsProps) => {+ const { t } = useTranslation('tool');+ const workspaceId = useActiveWorkspaceId();+ const { busy, connect, failure, reauthorize, remove, rename } =+ useConnectorAccountFlows(connector);++ const links = connector.links ?? [];+ const model = getAccountsSectionModel({ busy, canManage, connector, isDesktop });+ // A personal space has one member, so every account was authorized by the viewer.+ const formatAuthorizer = workspaceId+ ? (name: string) => t('connector.account.authorizedBy', { name })+ : undefined;++ const addButton = model.add && (+ <ManageTooltip title={disabledReason}>+ <Button+ disabled={!canManage || (!!busy && busy.kind !== 'connect')}+ icon={<Icon icon={PlusIcon} />}+ loading={busy?.kind === 'connect'}+ size={'small'}+ type={model.add.primary ? 'primary' : 'default'}+ onClick={() => void connect()}+ >+ {model.add.kind === 'connect'+ ? t('connector.account.connect')+ : t('connector.account.connectAnother')}+ </Button>+ </ManageTooltip>+ );++ return (+ <Section extra={addButton || undefined} label={t('connector.account.title')}>+ {model.empty ? (+ <div {...stylex.props(styles.list, styles.empty)}>{t('connector.account.empty')}</div>+ ) : (+ <div {...stylex.props(styles.list)}>+ {links.map((link) => (+ <AccountRow+ busyAction={getRowBusyAction(busy, link.id)}+ details={getAccountDetails(link, formatAuthorizer)}+ disabled={model.locked}+ disabledReason={disabledReason}+ key={link.id}+ link={link}+ onReauthorize={() => void reauthorize(link)}+ onRemove={() => remove(link)}+ onRename={() => rename(link)}+ />+ ))}+ </div>+ )}+ {failure && <InlineErrorText>{failure}</InlineErrorText>}+ {model.showNamingHint && (+ <div {...stylex.props(styles.hint)}>{t('connector.account.namingHint')}</div>+ )}+ {model.showSwitchHint && (+ <div {...stylex.props(styles.hint)}>{t('connector.account.switchHint')}</div>+ )}+ </Section>+ );+};++export default ConnectorAccounts;diff --git a/src/features/Connectors/ConnectorDetail/ConnectorOverviewInfo.tsx b/src/features/Connectors/ConnectorDetail/ConnectorOverviewInfo.tsxindex 6685f5d32fc..1396c35d08a 100644--- a/src/features/Connectors/ConnectorDetail/ConnectorOverviewInfo.tsx+++ b/src/features/Connectors/ConnectorDetail/ConnectorOverviewInfo.tsx@@ -67,9 +67,9 @@ interface ConnectorOverviewInfoProps {}/**- * Overview facts of a connector: whether it is authorized and who authorized- * it. The kind of object sits under the page title; tool permissions live in- * the Tools tab.+ * Overview facts of a connector: whether it is authorized and, for a single+ * credential, who authorized it. The kind of object sits under the page title;+ * tool permissions live in the Tools tab.*/const ConnectorOverviewInfo = memo<ConnectorOverviewInfoProps>(({ connector }) => {const { t } = useTranslation('tool');@@ -95,12 +95,18 @@ const ConnectorOverviewInfo = memo<ConnectorOverviewInfoProps>(({ connector }) =? { color: 'error' as const, label: t('connector.authError') }: { label: t('connector.notConnected') };+ // An OAuth connector is authorized per account, and each account names its+ // own authorizer under Accounts. A connector-wide "Authorized by" would name+ // only the creator — even before anyone has authorized an account.+ const showAuthorizer =+ !!connector.authorizedByName && connector.authKind !== 'oauth2' && !connector.links?.length;+return (<div {...stylex.props(styles.list)}><Row label={t('connector.overview.status')}><Tag color={status.color}>{status.label}</Tag></Row>- {connector.authorizedByName && (+ {showAuthorizer && (<Row label={t('connector.overview.authorizedBy')}>{connector.authorizedByAvatar && (<Avatar avatar={connector.authorizedByAvatar} shape={'circle'} size={20} />diff --git a/src/features/Connectors/ConnectorDetail/ManageTooltip.tsx b/src/features/Connectors/ConnectorDetail/ManageTooltip.tsxnew file mode 100644index 00000000000..896d8a048cd--- /dev/null+++ b/src/features/Connectors/ConnectorDetail/ManageTooltip.tsx@@ -0,0 +1,18 @@+import { Tooltip } from '@lobehub/ui';+import type { ReactNode } from 'react';++/**+ * Tooltip wrapper for the manage gate. Disabled native buttons swallow hover+ * events, so the tooltip needs an enabled wrapper element to anchor on; when+ * there is no gate message, render children untouched.+ */+const ManageTooltip = ({ children, title }: { children: ReactNode; title?: string }) =>+ title ? (+ <Tooltip title={title}>+ <span style={{ display: 'inline-flex' }}>{children}</span>+ </Tooltip>+ ) : (+ children+ );++export default ManageTooltip;diff --git a/src/features/Connectors/ConnectorDetail/Section.tsx b/src/features/Connectors/ConnectorDetail/Section.tsxnew file mode 100644index 00000000000..924a78fe698--- /dev/null+++ b/src/features/Connectors/ConnectorDetail/Section.tsx@@ -0,0 +1,36 @@+import { Flexbox } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import type { ReactNode } from 'react';++const styles = stylex.create({+ label: {+ color: cssVar.colorTextTertiary,+ fontSize: 12,+ fontWeight: 500,+ },+});++interface SectionProps {+ children: ReactNode;+ /** The section's own action (e.g. "Connect another account"), aligned with its label. */+ extra?: ReactNode;+ label: string;+}++/** One labelled block of the connector Overview tab. */+const Section = ({ children, extra, label }: SectionProps) => (+ <Flexbox gap={8}>+ {extra ? (+ <Flexbox horizontal align={'center'} gap={12} justify={'space-between'}>+ <span {...stylex.props(styles.label)}>{label}</span>+ {extra}+ </Flexbox>+ ) : (+ <span {...stylex.props(styles.label)}>{label}</span>+ )}+ {children}+ </Flexbox>+);++export default Section;diff --git a/src/features/Connectors/ConnectorDetail/accountFlowError.ts b/src/features/Connectors/ConnectorDetail/accountFlowError.tsnew file mode 100644index 00000000000..62761734cc8--- /dev/null+++ b/src/features/Connectors/ConnectorDetail/accountFlowError.ts@@ -0,0 +1,44 @@+import { type TFunction } from 'i18next';++import { getConnectorActionErrorCode } from '@/utils/connectorActionError';+import { ConnectorOAuthError } from '@/utils/connectorOAuth';++/** The user closed the authorization window themselves: nothing failed, so nothing to report. */+export const isDismissedAuthorization = (error: unknown): boolean =>+ error instanceof ConnectorOAuthError && error.reason === 'dismissed';++/**+ * A 403 means the cached manage policy was stale. The caller refetches it so+ * the controls turn disabled with their reason, instead of reporting an error+ * for a button that looked usable.+ */+export const isPermissionRejection = (error: unknown): boolean =>+ (error as { data?: { httpStatus?: number } } | undefined)?.data?.httpStatus === 403;++/**+ * Why an account action failed, as one sentence that ends with what to do+ * next. Callers put it after a lead naming the action and the account.+ */+export const formatAccountErrorReason = (t: TFunction<'tool'>, error: unknown): string => {+ if (error instanceof ConnectorOAuthError) {+ switch (error.reason) {+ case 'blocked': {+ return t('dev.oauthError.blocked', { ns: 'plugin' });+ }+ case 'timeout': {+ return t('connector.account.error.timeout');+ }+ default: {+ return t('connector.account.error.authFailed');+ }+ }+ }++ const code = getConnectorActionErrorCode(error);+ if (code === 'NETWORK') return t('connector.error.network');+ // A BAD_REQUEST carries a reason the user can act on (e.g. an OAuth server+ // that rejects the registration), so it is shown as the server worded it.+ if (code === 'BAD_REQUEST' && error instanceof Error && error.message) return error.message;++ return t('connector.account.error.retry');+};diff --git a/src/features/Connectors/ConnectorDetail/accountsModel.test.ts b/src/features/Connectors/ConnectorDetail/accountsModel.test.tsnew file mode 100644index 00000000000..9583179c8ea--- /dev/null+++ b/src/features/Connectors/ConnectorDetail/accountsModel.test.ts@@ -0,0 +1,128 @@+import { describe, expect, it } from 'vitest';++import type { ConnectorLinkSummary, ConnectorWithTools } from '@/store/tool/slices/connector/types';++import { getAccountDetails, getAccountsSectionModel, getRowBusyAction } from './accountsModel';++const makeLink = (patch: Partial<ConnectorLinkSummary> & { id: string; name: string }) =>+ ({+ authorizedByAvatar: null,+ authorizedByName: null,+ createdAt: '2026-11-01T00:00:00.000Z',+ profile: null,+ status: 'connected',+ ...patch,+ }) as ConnectorLinkSummary;++const work = makeLink({+ id: 'lnk_work',+ name: '[email protected]',+ profile: { email: '[email protected]' },+});+const personal = makeLink({+ id: 'lnk_personal',+ name: 'Personal',+ profile: { email: '[email protected]' },+});++const makeConnector = (links: ConnectorLinkSummary[], patch: Partial<ConnectorWithTools> = {}) =>+ ({+ authKind: 'oauth2',+ id: 'connector-1',+ links,+ mcpConnectionType: 'http',+ sourceType: 'custom',+ ...patch,+ }) as ConnectorWithTools;++const sectionFor = (+ links: ConnectorLinkSummary[],+ options: Partial<Parameters<typeof getAccountsSectionModel>[0]> = {},+) =>+ getAccountsSectionModel({+ canManage: true,+ connector: makeConnector(links),+ isDesktop: false,+ ...options,+ });++describe('getAccountsSectionModel', () => {+ it('makes connecting the first account the primary action', () => {+ expect(sectionFor([])).toEqual({+ add: { kind: 'connect', primary: true },+ empty: true,+ locked: false,+ showNamingHint: false,+ showSwitchHint: false,+ });+ });++ it('offers another account next to the switch-account hint once one is connected', () => {+ expect(sectionFor([work])).toEqual({+ add: { kind: 'connectAnother', primary: false },+ empty: false,+ locked: false,+ // A single account gets no link_id, so its name is not a choice yet.+ showNamingHint: false,+ showSwitchHint: true,+ });+ });++ it('asks for distinguishable names once the model chooses between accounts', () => {+ expect(sectionFor([work, personal]).showNamingHint).toBe(true);+ });++ it('drops the switch hint on desktop, whose window starts signed out', () => {+ expect(sectionFor([work], { isDesktop: true }).showSwitchHint).toBe(false);+ });++ it('has no add action on a connector that cannot hold several accounts', () => {+ const model = getAccountsSectionModel({+ canManage: true,+ connector: makeConnector([], { mcpConnectionType: 'stdio' }),+ isDesktop: false,+ });+ expect(model.add).toBeUndefined();+ expect(model.showSwitchHint).toBe(false);+ });++ it('locks the controls for a viewer who cannot manage, and while a flow runs', () => {+ expect(sectionFor([work], { canManage: false }).locked).toBe(true);+ expect(sectionFor([work], { busy: { kind: 'connect' } }).locked).toBe(true);+ });+});++describe('getRowBusyAction', () => {+ it('marks only the row the running action belongs to', () => {+ const busy = { kind: 'reauthorize', linkId: 'lnk_work' } as const;+ expect(getRowBusyAction(busy, 'lnk_work')).toBe('reauthorize');+ expect(getRowBusyAction(busy, 'lnk_personal')).toBeUndefined();+ expect(getRowBusyAction({ kind: 'connect' }, 'lnk_work')).toBeUndefined();+ });+});++describe('getAccountDetails', () => {+ const authorizer = (name: string) => `by ${name}`;++ it('skips an identity the name already shows', () => {+ expect(getAccountDetails(work)).toBe('');+ expect(getAccountDetails({ ...work, name: '[email protected]' })).toBe('');+ });++ it('shows the identity under a renamed account', () => {+ expect(getAccountDetails(personal)).toBe('[email protected]');+ expect(+ getAccountDetails(makeLink({ id: 'l', name: 'Bot', profile: { username: 'octocat' } })),+ ).toBe('octocat');+ });++ it('adds nothing for an account without identity', () => {+ expect(getAccountDetails(makeLink({ id: 'l', name: 'Default' }), authorizer)).toBe('');+ });++ it('names the authorizer only when asked to (in a workspace)', () => {+ const shared = { ...personal, authorizedByName: 'Alex' };+ expect(getAccountDetails(shared)).toBe('[email protected]');+ expect(getAccountDetails(shared, authorizer)).toBe('[email protected] · by Alex');+ });+});diff --git a/src/features/Connectors/ConnectorDetail/accountsModel.ts b/src/features/Connectors/ConnectorDetail/accountsModel.tsnew file mode 100644index 00000000000..af6ea34a19c--- /dev/null+++ b/src/features/Connectors/ConnectorDetail/accountsModel.ts@@ -0,0 +1,79 @@+import {+ type ConnectorLinkSummary,+ type ConnectorWithTools,+ supportsMultipleConnectorAccounts,+} from '@/store/tool/slices/connector/types';++/** The account flow running in the Accounts section, if any. Only one window at a time. */+export type AccountBusy =+ | { kind: 'connect' }+ | { kind: 'reauthorize'; linkId: string }+ | { kind: 'remove'; linkId: string };++export interface AccountsSectionModel {+ /** The section's add button, absent when this connector cannot take another account. */+ add?: { kind: 'connect' | 'connectAnother'; primary: boolean };+ empty: boolean;+ /** Every account control is off: the viewer cannot manage, or a flow is running. */+ locked: boolean;+ /** With two or more accounts the model picks one by name, so names must differ. */+ showNamingHint: boolean;+ /**+ * A browser reuses whoever is signed in to the provider; the desktop window+ * starts from a clean session for a new account, so it needs no hint.+ */+ showSwitchHint: boolean;+}++export const getAccountsSectionModel = ({+ busy,+ canManage,+ connector,+ isDesktop,+}: {+ busy?: AccountBusy;+ canManage: boolean;+ connector: ConnectorWithTools;+ isDesktop: boolean;+}): AccountsSectionModel => {+ const count = connector.links?.length ?? 0;+ const canAdd = supportsMultipleConnectorAccounts(connector);++ return {+ // The first account is the section's main task; later ones are optional.+ add: canAdd+ ? { kind: count > 0 ? 'connectAnother' : 'connect', primary: count === 0 }+ : undefined,+ empty: count === 0,+ locked: !canManage || !!busy,+ showNamingHint: count > 1,+ showSwitchHint: canAdd && !isDesktop && count > 0,+ };+};++/** The action running on one account row. */+export const getRowBusyAction = (+ busy: AccountBusy | undefined,+ linkId: string,+): 'reauthorize' | 'remove' | undefined =>+ busy && busy.kind !== 'connect' && busy.linkId === linkId ? busy.kind : undefined;++/**+ * Second line of an account row: the signed-in identity when the name does not+ * already say it (the default name is the email), then who authorized it when+ * `formatAuthorizer` is given (in a workspace; in a personal space it is always+ * the viewer). Empty when there is nothing to add.+ */+export const getAccountDetails = (+ link: ConnectorLinkSummary,+ formatAuthorizer?: (name: string) => string,+): string => {+ const identity = link.profile?.email || link.profile?.username;++ return [+ identity && identity.toLowerCase() !== link.name.toLowerCase() ? identity : undefined,+ formatAuthorizer && link.authorizedByName ? formatAuthorizer(link.authorizedByName) : undefined,+ ]+ .filter(Boolean)+ .join(' · ');+};diff --git a/src/features/Connectors/ConnectorDetail/index.test.tsx b/src/features/Connectors/ConnectorDetail/index.test.tsxindex 36a6186cea4..456139c7cd1 100644--- a/src/features/Connectors/ConnectorDetail/index.test.tsx+++ b/src/features/Connectors/ConnectorDetail/index.test.tsx@@ -18,8 +18,10 @@ const mocks = vi.hoisted(() => ({updateTools: [],},connectors: [] as Array<{+ authKind?: string;authorizedByName?: string;id: string;+ links?: Array<{ id: string; name: string }>;identifier: string;isEnabled?: boolean;metadata?: { description?: string };@@ -101,6 +103,12 @@ vi.mock('../CustomConnectorModal', () => ({default: () => <div data-testid="custom-connector-modal" />,}));+vi.mock('./ConnectorAccounts', () => ({+ default: ({ connector }: { connector: { links?: unknown[] } }) => (+ <div data-testid="connector-accounts">{connector.links?.length ?? 0}</div>+ ),+}));+vi.mock('./ToolPermissionGroup', () => ({default: ({ label }: { label: string }) => <div data-testid="permission-group">{label}</div>,}));@@ -313,4 +321,39 @@ describe('ConnectorDetail', () => {expect(screen.getByText('connector.enabled')).toBeInTheDocument();});++ it('shows accounts only for an OAuth connector, each naming its own authorizer', () => {+ mocks.toolState.connectors[0] = {+ ...mocks.toolState.connectors[0],+ authorizedByName: 'Avery',+ sourceType: ConnectorSourceType.custom,+ status: 'connected',+ };++ const { unmount } = render(<ConnectorDetail connectorId="connector-1" />);+ // A static credential has no accounts; its one authorizer stays on the connector.+ expect(screen.queryByTestId('connector-accounts')).not.toBeInTheDocument();+ expect(screen.getByText('Avery')).toBeInTheDocument();+ unmount();++ // Before any account is connected nobody has authorized it yet either.+ mocks.toolState.connectors[0] = { ...mocks.toolState.connectors[0], authKind: 'oauth2' };+ const { unmount: unmountEmpty } = render(<ConnectorDetail connectorId="connector-1" />);+ expect(screen.getByTestId('connector-accounts')).toHaveTextContent('0');+ expect(screen.queryByText('Avery')).not.toBeInTheDocument();+ unmountEmpty();++ mocks.toolState.connectors[0] = {+ ...mocks.toolState.connectors[0],+ links: [+ { id: 'lnk_1', name: '[email protected]' },+ { id: 'lnk_2', name: 'Personal' },+ ],+ };+ render(<ConnectorDetail connectorId="connector-1" />);++ expect(screen.getByTestId('connector-accounts')).toHaveTextContent('2');+ expect(screen.queryByText('connector.overview.authorizedBy')).not.toBeInTheDocument();+ expect(screen.queryByText('Avery')).not.toBeInTheDocument();+ });});diff --git a/src/features/Connectors/ConnectorDetail/index.tsx b/src/features/Connectors/ConnectorDetail/index.tsxindex b3bc1a977d8..a61c7b9519d 100644--- a/src/features/Connectors/ConnectorDetail/index.tsx+++ b/src/features/Connectors/ConnectorDetail/index.tsx@@ -3,7 +3,7 @@ import {getLobehubSkillProviderById,hasCallableMcpEndpoint,} from '@lobechat/const';-import { Button, confirmModal, Flexbox, Tabs, Text, toast, Tooltip } from '@lobehub/ui';+import { Button, confirmModal, Flexbox, Tabs, Text, toast } from '@lobehub/ui';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';import { PencilIcon, RefreshCwIcon, Trash2 } from 'lucide-react';@@ -22,9 +22,12 @@ import { type ConnectorActionError, toConnectorActionError } from '@/utils/conneimport ConnectorActionErrorText from '../ConnectorActionErrorText';import CustomConnectorModal from '../CustomConnectorModal';import { formatConnectorActionErrorToast } from '../formatConnectorActionError';+import ConnectorAccounts from './ConnectorAccounts';import ConnectorDetailIcon from './ConnectorDetailIcon';import ConnectorOverviewInfo, { getConnectorKind } from './ConnectorOverviewInfo';import { getLocalizedConnectorDetail } from './localization';+import ManageTooltip from './ManageTooltip';+import Section from './Section';import ToolPermissionGroup from './ToolPermissionGroup';interface ConnectorDetailProps {@@ -45,20 +48,6 @@ interface ConnectorDetailProps {onDelete?: () => void;}-/**- * Tooltip wrapper for the manage gate. Disabled native buttons swallow hover- * events, so the tooltip needs an enabled wrapper element to anchor on; when- * there is no gate message, render children untouched.- */-const ManageTooltip = ({ children, title }: { children: ReactNode; title?: string }) =>- title ? (- <Tooltip title={title}>- <span style={{ display: 'inline-flex' }}>{children}</span>- </Tooltip>- ) : (- children- );-type ConnectorDetailTab = 'overview' | 'tools';const styles = stylex.create({@@ -89,11 +78,6 @@ const styles = stylex.create({flexDirection: 'column',height: '100%',},- sectionLabel: {- color: cssVar.colorTextTertiary,- fontSize: 12,- fontWeight: 500,- },tabs: {borderBlockEndColor: cssVar.colorBorderSecondary,borderBlockEndStyle: 'solid',@@ -109,13 +93,6 @@ const styles = stylex.create({},});-const Section = ({ children, label }: { children: ReactNode; label: string }) => (- <Flexbox gap={8}>- <span {...stylex.props(styles.sectionLabel)}>{label}</span>- {children}- </Flexbox>-);-const ConnectorDetail = memo<ConnectorDetailProps>(({ agentTitle, connectorId, lifecycleActions, middleSlot, onDelete }) => {const { t } = useTranslation('tool');@@ -251,6 +228,8 @@ const ConnectorDetail = memo<ConnectorDetailProps>(const handleUninstall = () => {if (!connector) return;confirmModal({+ // The modal's built-in label is not localized.+ cancelText: t('cancel', { ns: 'common' }),content: deleteConfirmContent,okButtonProps: { danger: true },onOk: async () => {@@ -378,6 +357,7 @@ const ConnectorDetail = memo<ConnectorDetailProps>(size="small"onClick={() => {confirmModal({+ cancelText: t('cancel', { ns: 'common' }),content: deleteConfirmContent,okButtonProps: { danger: true },onOk: async () => {@@ -436,6 +416,17 @@ const ConnectorDetail = memo<ConnectorDetailProps>(</Flexbox></Section>+ {/* Accounts are their own section: removing one account is not the+ connector-level Disconnect / Delete above. */}+ {connector.authKind === 'oauth2' && (+ <ConnectorAccounts+ canManage={canManage}+ connector={connector}+ disabledReason={manageTooltip}+ key={connectorId}+ />+ )}+{middleSlot}</Flexbox>);diff --git a/src/features/Connectors/ConnectorDetail/useConnectorAccountFlows.test.ts b/src/features/Connectors/ConnectorDetail/useConnectorAccountFlows.test.tsnew file mode 100644index 00000000000..c9b6dc21cce--- /dev/null+++ b/src/features/Connectors/ConnectorDetail/useConnectorAccountFlows.test.ts@@ -0,0 +1,340 @@+/**+ * @vitest-environment happy-dom+ */+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { ConnectorLinkSummary, ConnectorWithTools } from '@/store/tool/slices/connector/types';+import { ConnectorOAuthError } from '@/utils/connectorOAuth';++import { useConnectorAccountFlows } from './useConnectorAccountFlows';++const mocks = vi.hoisted(() => ({+ confirmModal: vi.fn(),+ openConnectorOAuthPopup: vi.fn(),+ openRenameModal: vi.fn(),+ refreshConnectorManagePolicy: vi.fn(),+ state: {+ connectConnectorAccount: vi.fn(),+ connectors: [] as Array<{ id: string; links?: Array<{ id: string; name: string }> }>,+ reauthorizeConnectorAccount: vi.fn(),+ removeConnectorAccount: vi.fn(),+ renameConnectorAccount: vi.fn(),+ },+ toast: { error: vi.fn(), info: vi.fn(), success: vi.fn(), warning: vi.fn() },+}));++// Keys come back with their interpolation values, so a test can tell which+// message (and which account) a toast or line names.+vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, options?: Record<string, unknown>) => {+ const values = Object.entries(options ?? {})+ .filter(([name]) => name !== 'ns')+ .map(([name, value]) => `${name}=${value}`)+ .join(',');+ return values ? `${key}(${values})` : key;+ },+ }),+}));++vi.mock('@lobehub/ui', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ confirmModal: mocks.confirmModal,+ toast: mocks.toast,+}));++vi.mock('@/components/RenameModal', () => ({ openRenameModal: mocks.openRenameModal }));++vi.mock('@/services/connectorManagePolicy', () => ({+ refreshConnectorManagePolicy: mocks.refreshConnectorManagePolicy,+}));++vi.mock('@/store/tool', () => {+ const useToolStore = (selector: (state: typeof mocks.state) => unknown) => selector(mocks.state);+ useToolStore.getState = () => mocks.state;+ return { useToolStore };+});++vi.mock('@/store/tool/slices/connector', async () => ({+ ...(await import('@/store/tool/slices/connector/types')),+ connectorSelectors: {+ connectorLinkName: (connectorId: string, linkId: string) => (state: typeof mocks.state) =>+ state.connectors.find((c) => c.id === connectorId)?.links?.find((link) => link.id === linkId)+ ?.name,+ },+}));++vi.mock('@/utils/connectorOAuth', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ openConnectorOAuthPopup: mocks.openConnectorOAuthPopup,+}));++const makeLink = (id: string, name: string) =>+ ({+ authorizedByAvatar: null,+ authorizedByName: null,+ createdAt: '2026-11-01T00:00:00.000Z',+ id,+ name,+ profile: null,+ status: 'connected',+ }) as ConnectorLinkSummary;++const work = makeLink('lnk_work', '[email protected]');+const personal = makeLink('lnk_personal', 'Personal');++const setup = (links: ConnectorLinkSummary[]) => {+ const connector = { id: 'connector-1', links } as ConnectorWithTools;+ mocks.state.connectors = [{ id: connector.id, links }];+ return renderHook(() => useConnectorAccountFlows(connector));+};++describe('useConnectorAccountFlows', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.openConnectorOAuthPopup.mockReturnValue({ close: vi.fn() });+ });++ describe('connect', () => {+ it('opens the popup before awaiting and announces the new account', async () => {+ mocks.state.connectConnectorAccount.mockImplementation(async () => {+ // The action refetches the list before it resolves.+ mocks.state.connectors[0].links = [work, makeLink('lnk_new', 'Account 2')];+ return { linkId: 'lnk_new', outcome: 'created' };+ });+ const { result } = setup([work]);++ let running!: Promise<void>;+ act(() => {+ running = result.current.connect();+ });+ // Synchronously within the click, or the browser blocks the window.+ expect(mocks.openConnectorOAuthPopup).toHaveBeenCalledTimes(1);+ expect(result.current.busy).toEqual({ kind: 'connect' });+ await act(() => running);++ expect(mocks.state.connectConnectorAccount).toHaveBeenCalledWith('connector-1', {+ popup: expect.anything(),+ });+ expect(mocks.toast.success).toHaveBeenCalledWith(+ 'connector.account.connected(name=Account 2)',+ );+ expect(result.current.busy).toBeUndefined();+ });++ it('says the account was already connected when nothing was added', async () => {+ mocks.state.connectConnectorAccount.mockResolvedValue({+ linkId: 'lnk_work',+ outcome: 'matchedExisting',+ });+ const { result } = setup([work]);++ await act(() => result.current.connect());++ expect(mocks.toast.info).toHaveBeenCalledWith({+ description: 'connector.account.alreadyConnectedDesc',+ title: 'connector.account.alreadyConnected([email protected])',+ });+ expect(mocks.toast.success).not.toHaveBeenCalled();+ });++ it('still says so when the matched account cannot be named', async () => {+ mocks.state.connectConnectorAccount.mockResolvedValue({ outcome: 'matchedExisting' });+ const { result } = setup([work]);++ await act(() => result.current.connect());++ expect(mocks.toast.info).toHaveBeenCalledWith({+ description: 'connector.account.alreadyConnectedDesc',+ title: 'connector.account.alreadyConnectedUnnamed',+ });+ });++ it('stays quiet when the user closes the authorization window', async () => {+ mocks.state.connectConnectorAccount.mockRejectedValue(new ConnectorOAuthError('dismissed'));+ const { result } = setup([work]);++ await act(() => result.current.connect());++ expect(mocks.toast.error).not.toHaveBeenCalled();+ expect(result.current.failure).toBeUndefined();+ });++ it('keeps a retryable failure in place and frees the button', async () => {+ mocks.state.connectConnectorAccount.mockRejectedValue(new ConnectorOAuthError('timeout'));+ const { result } = setup([work]);++ await act(() => result.current.connect());++ const message = 'connector.account.connectFailed(reason=connector.account.error.timeout)';+ expect(mocks.toast.error).toHaveBeenCalledWith(message);+ expect(result.current.failure).toBe(message);+ expect(result.current.busy).toBeUndefined();+ });++ it('passes on the reason a server gives for refusing', async () => {+ const refusal = Object.assign(new Error('Dynamic client registration failed: 403'), {+ data: { code: 'BAD_REQUEST' },+ });+ mocks.state.connectConnectorAccount.mockRejectedValue(refusal);+ const { result } = setup([work]);++ await act(() => result.current.connect());++ expect(result.current.failure).toBe(+ 'connector.account.connectFailed(reason=Dynamic client registration failed: 403)',+ );+ });++ it('reports a blocked window without starting the flow', async () => {+ mocks.openConnectorOAuthPopup.mockReturnValue(null);+ const { result } = setup([work]);++ await act(() => result.current.connect());++ expect(mocks.state.connectConnectorAccount).not.toHaveBeenCalled();+ expect(result.current.failure).toBe(+ 'connector.account.connectFailed(reason=dev.oauthError.blocked)',+ );+ });++ it('refetches the manage policy instead of reporting a stale-permission rejection', async () => {+ mocks.state.connectConnectorAccount.mockRejectedValue({ data: { httpStatus: 403 } });+ const { result } = setup([work]);++ await act(() => result.current.connect());++ expect(mocks.refreshConnectorManagePolicy).toHaveBeenCalled();+ expect(mocks.toast.error).not.toHaveBeenCalled();+ expect(result.current.failure).toBeUndefined();+ });+ });++ describe('reauthorize', () => {+ it('re-authorizes the chosen account', async () => {+ mocks.state.reauthorizeConnectorAccount.mockResolvedValue({+ linkId: 'lnk_personal',+ outcome: 'reauthorized',+ });+ const { result } = setup([work, personal]);++ await act(() => result.current.reauthorize(personal));++ expect(mocks.openConnectorOAuthPopup).toHaveBeenCalledTimes(1);+ expect(mocks.state.reauthorizeConnectorAccount).toHaveBeenCalledWith(+ 'connector-1',+ 'lnk_personal',+ { popup: expect.anything() },+ );+ expect(mocks.toast.success).toHaveBeenCalledWith(+ 'connector.account.reauthorized(name=Personal)',+ );+ });++ it('warns when the provider signed in as another connected account', async () => {+ mocks.state.reauthorizeConnectorAccount.mockResolvedValue({+ linkId: 'lnk_work',+ outcome: 'matchedExisting',+ });+ const { result } = setup([work, personal]);++ await act(() => result.current.reauthorize(personal));++ expect(mocks.toast.warning).toHaveBeenCalledWith({+ description:+ 'connector.account.reauthorizeMismatchDesc([email protected],name=Personal)',+ title: 'connector.account.reauthorizeMismatch(name=Personal)',+ });+ expect(mocks.toast.success).not.toHaveBeenCalled();+ });+ });++ describe('rename', () => {+ const openRename = (link: ConnectorLinkSummary, links = [work, personal]) => {+ const { result } = setup(links);+ act(() => result.current.rename(link));+ return mocks.openRenameModal.mock.calls[0][0] as {+ defaultValue: string;+ description: string;+ maxLength: number;+ onSave: (name: string) => Promise<void>;+ };+ };++ it('explains what the name is for and saves it', async () => {+ const modal = openRename(work);++ expect(modal).toMatchObject({+ defaultValue: '[email protected]',+ description: 'connector.account.renameDesc',+ maxLength: 64,+ });++ await modal.onSave('Work');+ expect(mocks.state.renameConnectorAccount).toHaveBeenCalledWith(+ 'connector-1',+ 'lnk_work',+ 'Work',+ );+ });++ it('keeps the dialog open and names the clash when another account has the name', async () => {+ mocks.state.renameConnectorAccount.mockRejectedValue({ data: { code: 'CONFLICT' } });+ const modal = openRename(work);++ // A rejected save is what keeps RenameModal open with the typed name.+ await expect(modal.onSave('Personal')).rejects.toBeTruthy();+ expect(mocks.toast.error).toHaveBeenCalledWith(+ 'connector.account.renameConflict(name=Personal)',+ );+ });+ });++ describe('remove', () => {+ it('warns that the tools stop working when removing the last account', () => {+ const { result } = setup([work]);++ act(() => result.current.remove(work));++ expect(mocks.confirmModal).toHaveBeenCalledWith(+ expect.objectContaining({+ cancelText: 'cancel',+ content: 'connector.account.removeLastConfirmContent',+ okButtonProps: { danger: true },+ okText: 'connector.account.removeConfirmOk',+ title: 'connector.account.removeConfirmTitle([email protected])',+ }),+ );+ });++ it('describes only this account when others stay connected, then removes it', async () => {+ const { result } = setup([work, personal]);++ act(() => result.current.remove(personal));+ const config = mocks.confirmModal.mock.calls[0][0];+ expect(config).toMatchObject({+ content: 'connector.account.removeConfirmContent',+ title: 'connector.account.removeConfirmTitle(name=Personal)',+ });++ await act(() => config.onOk());+ expect(mocks.state.removeConnectorAccount).toHaveBeenCalledWith(+ 'connector-1',+ 'lnk_personal',+ );+ });++ it('says the account is still connected when removing fails', async () => {+ mocks.state.removeConnectorAccount.mockRejectedValue(new Error('boom'));+ const { result } = setup([work, personal]);++ act(() => result.current.remove(work));+ await act(() => mocks.confirmModal.mock.calls[0][0].onOk());++ expect(result.current.failure).toBe(+ 'connector.account.removeFailed([email protected],reason=connector.account.error.retry)',+ );+ });+ });+});diff --git a/src/features/Connectors/ConnectorDetail/useConnectorAccountFlows.ts b/src/features/Connectors/ConnectorDetail/useConnectorAccountFlows.tsnew file mode 100644index 00000000000..f89fee4604a--- /dev/null+++ b/src/features/Connectors/ConnectorDetail/useConnectorAccountFlows.ts@@ -0,0 +1,202 @@+import { confirmModal, toast } from '@lobehub/ui';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import { openRenameModal } from '@/components/RenameModal';+import { refreshConnectorManagePolicy } from '@/services/connectorManagePolicy';+import { useToolStore } from '@/store/tool';+import {+ type ConnectorAccountFlowResult,+ type ConnectorLinkSummary,+ connectorSelectors,+ type ConnectorWithTools,+ isConnectorLinkNameConflict,+} from '@/store/tool/slices/connector';+import { ConnectorOAuthError, openConnectorOAuthPopup } from '@/utils/connectorOAuth';++import {+ formatAccountErrorReason,+ isDismissedAuthorization,+ isPermissionRejection,+} from './accountFlowError';+import { type AccountBusy } from './accountsModel';++/** Server rule: a trimmed name of 1–64 characters, unique within the connector. */+export const MAX_ACCOUNT_NAME_LENGTH = 64;++/**+ * Connect, re-authorize, rename and remove the OAuth accounts of one+ * connector, with the feedback each outcome needs. Use it from a component+ * keyed by connector id, so a running flow's state never shows on another one.+ */+export const useConnectorAccountFlows = (connector: ConnectorWithTools) => {+ const { t } = useTranslation('tool');++ const connectConnectorAccount = useToolStore((s) => s.connectConnectorAccount);+ const reauthorizeConnectorAccount = useToolStore((s) => s.reauthorizeConnectorAccount);+ const renameConnectorAccount = useToolStore((s) => s.renameConnectorAccount);+ const removeConnectorAccount = useToolStore((s) => s.removeConnectorAccount);++ const [busy, setBusy] = useState<AccountBusy>();+ // A failed authorization stays in place: the toast is usually gone by the+ // time the user is back from the provider's window.+ const [failure, setFailure] = useState<string>();++ const nameOf = (linkId?: string) =>+ linkId+ ? connectorSelectors.connectorLinkName(connector.id, linkId)(useToolStore.getState())+ : undefined;++ const reportFailure = (error: unknown, lead: (reason: string) => string) => {+ if (isDismissedAuthorization(error)) return;+ // A stale manage policy: refetch it so the controls turn disabled with+ // their reason, as the rest of the connector page does.+ if (isPermissionRejection(error)) {+ void refreshConnectorManagePolicy();+ return;+ }+ const message = lead(formatAccountErrorReason(t, error));+ toast.error(message);+ setFailure(message);+ };++ const announceConnect = (result: ConnectorAccountFlowResult) => {+ const name = nameOf(result.linkId);+ if (result.outcome === 'matchedExisting') {+ // Nothing new shows up in the list, so this is the only sign of what happened.+ toast.info({+ description: t('connector.account.alreadyConnectedDesc'),+ title: name+ ? t('connector.account.alreadyConnected', { name })+ : t('connector.account.alreadyConnectedUnnamed'),+ });+ return;+ }+ // The new row is the result; the toast only acknowledges it.+ if (name) toast.success(t('connector.account.connected', { name }));+ };++ const announceReauthorize = (+ result: ConnectorAccountFlowResult,+ target: ConnectorLinkSummary,+ ) => {+ if (result.outcome === 'matchedExisting') {+ // The provider signed in as another connected account; that one was+ // refreshed, the account the user picked was not.+ toast.warning({+ description: t('connector.account.reauthorizeMismatchDesc', {+ // The store is refetched before the action resolves, so the matched+ // account is listed; its raw id is the last resort.+ matched: nameOf(result.linkId) ?? result.linkId ?? '',+ name: target.name,+ }),+ title: t('connector.account.reauthorizeMismatch', { name: target.name }),+ });+ return;+ }+ toast.success(+ t('connector.account.reauthorized', { name: nameOf(result.linkId) ?? target.name }),+ );+ };++ /** Call from the click itself: the web popup must open before any await. */+ const connect = async () => {+ const popup = openConnectorOAuthPopup();+ const lead = (reason: string) => t('connector.account.connectFailed', { reason });+ setFailure(undefined);+ if (popup === null) {+ reportFailure(new ConnectorOAuthError('blocked'), lead);+ return;+ }+ setBusy({ kind: 'connect' });+ try {+ announceConnect(await connectConnectorAccount(connector.id, { popup }));+ } catch (error) {+ reportFailure(error, lead);+ } finally {+ setBusy(undefined);+ }+ };++ /** Call from the click itself, like {@link connect}. */+ const reauthorize = async (link: ConnectorLinkSummary) => {+ const popup = openConnectorOAuthPopup();+ const lead = (reason: string) =>+ t('connector.account.reauthorizeFailed', { name: link.name, reason });+ setFailure(undefined);+ if (popup === null) {+ reportFailure(new ConnectorOAuthError('blocked'), lead);+ return;+ }+ setBusy({ kind: 'reauthorize', linkId: link.id });+ try {+ announceReauthorize(+ await reauthorizeConnectorAccount(connector.id, link.id, { popup }),+ link,+ );+ } catch (error) {+ reportFailure(error, lead);+ } finally {+ setBusy(undefined);+ }+ };++ const rename = (link: ConnectorLinkSummary) => {+ openRenameModal({+ defaultValue: link.name,+ description: t('connector.account.renameDesc'),+ maxLength: MAX_ACCOUNT_NAME_LENGTH,+ title: t('connector.account.renameTitle'),+ onSave: async (name) => {+ try {+ await renameConnectorAccount(connector.id, link.id, name);+ } catch (error) {+ // Same as the other writes: refetch the stale gate and let the+ // controls turn disabled; the dialog closes on its own.+ if (isPermissionRejection(error)) {+ void refreshConnectorManagePolicy();+ return;+ }+ toast.error(+ isConnectorLinkNameConflict(error)+ ? t('connector.account.renameConflict', { name })+ : t('connector.account.renameFailed', {+ reason: formatAccountErrorReason(t, error),+ }),+ );+ // Rejecting keeps the dialog open with the typed name to fix.+ throw error;+ }+ },+ });+ };++ const remove = (link: ConnectorLinkSummary) => {+ confirmModal({+ // The modal's built-in label is not localized.+ cancelText: t('cancel', { ns: 'common' }),+ content:+ (connector.links?.length ?? 0) <= 1+ ? t('connector.account.removeLastConfirmContent')+ : t('connector.account.removeConfirmContent'),+ okButtonProps: { danger: true },+ okText: t('connector.account.removeConfirmOk'),+ onOk: async () => {+ setFailure(undefined);+ setBusy({ kind: 'remove', linkId: link.id });+ try {+ await removeConnectorAccount(connector.id, link.id);+ } catch (error) {+ reportFailure(error, (reason) =>+ t('connector.account.removeFailed', { name: link.name, reason }),+ );+ } finally {+ setBusy(undefined);+ }+ },+ title: t('connector.account.removeConfirmTitle', { name: link.name }),+ });+ };++ return { busy, connect, failure, reauthorize, remove, rename };+};diff --git a/src/features/Connectors/CustomConnectorModal/index.test.tsx b/src/features/Connectors/CustomConnectorModal/index.test.tsxindex 0b311b44e53..8ba33daf5f9 100644--- a/src/features/Connectors/CustomConnectorModal/index.test.tsx+++ b/src/features/Connectors/CustomConnectorModal/index.test.tsx@@ -1,16 +1,26 @@/*** @vitest-environment happy-dom*/+import type { LobeToolCustomPlugin } from '@lobechat/types';import { render, screen, waitFor } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { DevModalOAuthFields, DevModalOAuthPlan } from '@/features/PluginDevModal';import { restoreConnector } from '@/store/tool/slices/connector/replaceConnector';import CustomConnectorModal from './index';import { saveOAuthConnectorEdit } from './oauthEdit';const mocks = vi.hoisted(() => ({- onSave: undefined as undefined | ((value: unknown, ctx?: unknown) => Promise<void>),+ devModal: undefined as+ | undefined+ | {+ getOAuthPlan?: (fields: DevModalOAuthFields) => DevModalOAuthPlan;+ onSave?: (+ value: LobeToolCustomPlugin,+ ctx?: { oauthPopup?: Window | null },+ ) => Promise<void>;+ },state: {connector: undefined as unknown,createConnector: vi.fn(),@@ -47,9 +57,9 @@ vi.mock('@/store/tool/slices/connector', () => ({// The form itself is a heavy antd form; what matters here is the value the// modal seeds it with.vi.mock('@/features/PluginDevModal', () => ({- default: ({ onSave, value }: { onSave?: (value: unknown) => Promise<void>; value?: unknown }) => {- mocks.onSave = onSave;- return <div data-testid="seed">{JSON.stringify(value ?? null)}</div>;+ default: (props: NonNullable<typeof mocks.devModal> & { value?: unknown }) => {+ mocks.devModal = props;+ return <div data-testid="seed">{JSON.stringify(props.value ?? null)}</div>;},}));@@ -218,7 +228,7 @@ describe('CustomConnectorModal edit save', () => {render(<CustomConnectorModal open connectorId="c1" onClose={() => {}} />);await waitFor(() => expect(screen.getByTestId('seed').textContent).not.toBe('null'));- await mocks.onSave!({+ await mocks.devModal!.onSave!({customParams: {mcp: { args: ['--port', '1'], command: ' uvx ', env: { API_KEY: 'new' }, type: 'stdio' },},@@ -247,7 +257,7 @@ describe('CustomConnectorModal edit save', () => {render(<CustomConnectorModal open connectorId="c1" onClose={() => {}} />);await waitFor(() => expect(screen.getByTestId('seed').textContent).not.toBe('null'));- await mocks.onSave!({+ await mocks.devModal!.onSave!({customParams: { mcp: { type: 'http', url: 'https://new.example.com' } },identifier: 'my-mcp',});@@ -273,7 +283,7 @@ describe('CustomConnectorModal edit save', () => {await waitFor(() => expect(screen.getByTestId('seed').textContent).not.toBe('null'));await expect(- mocks.onSave!({+ mocks.devModal!.onSave!({customParams: { mcp: { command: 'not-a-command', type: 'stdio' } },identifier: 'my-mcp',}),@@ -299,7 +309,7 @@ describe('CustomConnectorModal edit save', () => {render(<CustomConnectorModal open connectorId="c1" onClose={() => {}} />);await waitFor(() => expect(screen.getByTestId('seed').textContent).not.toBe('null'));- await mocks.onSave!(+ await mocks.devModal!.onSave!({customParams: {mcp: { auth: { type: 'oauth2' }, type: 'http', url: 'https://new.example.com' },@@ -324,3 +334,99 @@ describe('CustomConnectorModal edit save', () => {expect(popup.close).toHaveBeenCalled();});});++/**+ * Editing a connected OAuth connector used to open the authorization window on+ * every save and re-send `{ clientId: undefined, scheme: 'dcr' }`, replacing the+ * resolved client. With several accounts that cost every account its tokens.+ */+describe('CustomConnectorModal OAuth on save', () => {+ const URL = 'https://mail.example.com/mcp';+ const oauthValue = (url = URL): LobeToolCustomPlugin =>+ ({+ customParams: { mcp: { auth: { type: 'oauth2' }, type: 'http', url } },+ identifier: 'mail',+ type: 'customPlugin',+ }) as LobeToolCustomPlugin;++ const openEdit = async (accountCount: number) => {+ mocks.state.connector = {+ authKind: 'oauth2',+ id: 'c1',+ identifier: 'mail',+ links: Array.from({ length: accountCount }, (_, i) => ({ id: `lnk_${i}`, name: `A${i}` })),+ mcpConnectionType: 'http',+ mcpServerUrl: URL,+ metadata: {},+ name: 'Mail',+ sourceType: 'custom',+ };+ mocks.state.getConnectorForEdit.mockResolvedValue({+ credentials: null,+ mcpStdioConfig: null,+ metadata: {},+ oidcConfig: { clientId: 'dcr-issued-id', scheme: 'dcr' },+ });+ render(<CustomConnectorModal open connectorId="c1" onClose={() => {}} />);+ await waitFor(() => expect(screen.getByTestId('seed').textContent).not.toBe('null'));+ return mocks.devModal!;+ };++ beforeEach(() => {+ vi.clearAllMocks();+ mocks.state.startConnectorOAuth.mockResolvedValue('https://auth.example.com/authorize');+ });++ it('saves an untouched connector in place, keeping its client and accounts', async () => {+ const modal = await openEdit(2);++ expect(modal.getOAuthPlan!({ url: URL })).toEqual({+ authorize: false,+ notice: { text: 'connector.account.editKeepsAccounts', type: 'info' },+ });++ await modal.onSave!(oauthValue());++ const patch = mocks.state.updateConnector.mock.calls[0][1];+ expect(patch).not.toHaveProperty('oidcConfig');+ expect(patch).not.toHaveProperty('credentials');+ expect(saveOAuthConnectorEdit).not.toHaveBeenCalled();+ });++ it('authorizes again, with a fresh client, when the server URL changed', async () => {+ const modal = await openEdit(2);+ const next = 'https://other.example.com/mcp';++ expect(modal.getOAuthPlan!({ url: next })).toEqual({+ authorize: true,+ notice: { text: 'connector.account.editDropsAccounts', type: 'warning' },+ });++ await modal.onSave!(oauthValue(next), { oauthPopup: null });++ expect(saveOAuthConnectorEdit).toHaveBeenCalledWith(+ 'c1',+ expect.objectContaining({+ credentials: null,+ mcpServerUrl: next,+ oidcConfig: expect.objectContaining({ scheme: 'dcr' }),+ }),+ null,+ expect.any(Function),+ );+ });++ it('authorizes a connector that has no account yet', async () => {+ const modal = await openEdit(0);++ expect(modal.getOAuthPlan!({ url: URL })).toEqual({ authorize: true });++ await modal.onSave!(oauthValue(), { oauthPopup: null });+ expect(saveOAuthConnectorEdit).toHaveBeenCalledWith(+ 'c1',+ expect.any(Object),+ null,+ expect.any(Function),+ );+ });+});diff --git a/src/features/Connectors/CustomConnectorModal/index.tsx b/src/features/Connectors/CustomConnectorModal/index.tsxindex 602eb3c2b4e..89a87b9f0a0 100644--- a/src/features/Connectors/CustomConnectorModal/index.tsx+++ b/src/features/Connectors/CustomConnectorModal/index.tsx@@ -1,10 +1,14 @@import { type LobeToolCustomPlugin, type McpConnectVia } from '@lobechat/types';import { connectorConnectVia, connectorDeviceBinding } from '@lobechat/utils/mcpEndpoint';import { memo, useEffect, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';import type { ConnectorCredentials, OIDCConfig } from '@/database/schemas';import { ConnectorSourceType } from '@/database/schemas';-import DevModal from '@/features/PluginDevModal';+import DevModal, {+ type DevModalOAuthFields,+ type DevModalOAuthPlan,+} from '@/features/PluginDevModal';import { useToolStore } from '@/store/tool';import { connectorSelectors } from '@/store/tool/slices/connector';import { waitForConnectorOAuth } from '@/utils/connectorOAuth';@@ -13,6 +17,13 @@ import { executeOAuthCreate } from '@/utils/connectorOAuthCreate';import { saveConnectorEdit } from './connectorEdit';import { executeLegacyMigrationSave } from './legacyPluginMigration';import { saveOAuthConnectorEdit } from './oauthEdit';+import {+ countDroppedAccounts,+ isOAuthClientChanged,+ isServerUrlChanged,+ type OAuthBaseline,+ requiresOAuth,+} from './oauthPlan';interface CustomConnectorModalProps {connectorId?: string;@@ -66,9 +77,12 @@ interface StdioConfig {* - Pre-fills the form from the existing connector record* - Calls updateConnector instead of createConnector on save* - Clears credentials when the server URL changes+ * - Authorizes only when the URL or OAuth client changed, or no account is+ * connected yet (see `requiresOAuth`); other edits keep the accounts*/const CustomConnectorModal = memo<CustomConnectorModalProps>(({ open, onClose, connectorId, legacyPlugin, onEditSuccess }) => {+ const { t } = useTranslation('tool');const createConnector = useToolStore((s) => s.createConnector);const deleteConnector = useToolStore((s) => s.deleteConnector);const getConnectorForEdit = useToolStore((s) => s.getConnectorForEdit);@@ -207,6 +221,45 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(};}, [isEditMode, isMigrationMode, legacyPlugin, connector, editFetchedData]);+ // The stored OAuth setup the form opened with. Undefined while creating,+ // migrating or loading, where every OAuth save authorizes.+ const oauthBaseline = useMemo((): OAuthBaseline | undefined => {+ if (!isEditMode || !connector || editFetchedData === null) return undefined;+ const { credentials, oidcConfig } = editFetchedData;+ return {+ accountCount: connector.links?.length ?? 0,+ authType: oidcConfig ? 'oauth2' : (credentials?.type ?? 'none'),+ clientId: oidcConfig?.scheme === 'pre_registration' ? oidcConfig.clientId : undefined,+ mcpServerUrl: connector.mcpServerUrl,+ };+ }, [isEditMode, connector, editFetchedData]);++ const getOAuthPlan = (fields: DevModalOAuthFields): DevModalOAuthPlan => {+ const authorize = requiresOAuth(oauthBaseline, fields);+ if (!oauthBaseline) return { authorize };++ const dropped = countDroppedAccounts(oauthBaseline, fields);+ if (dropped > 0)+ return {+ authorize,+ notice: {+ // Two keys rather than plural forms: zh has one form, and the many+ // case says that only one account comes back on save.+ text:+ dropped === 1+ ? t('connector.account.editDropsAccount')+ : t('connector.account.editDropsAccounts', { count: dropped }),+ type: 'warning',+ },+ };+ if (!authorize)+ return {+ authorize,+ notice: { text: t('connector.account.editKeepsAccounts'), type: 'info' },+ };+ return { authorize };+ };+const handleSave = async (value: LobeToolCustomPlugin,ctx?: { oauthPopup?: Window | null },@@ -275,6 +328,11 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(if (isEditMode && connectorId) {const newUrl = isHttp ? mcp.url?.trim() : undefined;const urlChanged = newUrl !== (connector?.mcpServerUrl ?? undefined);+ const oauthFields: DevModalOAuthFields = {+ clientId: mcp.auth?.clientId,+ clientSecret: mcp.auth?.clientSecret,+ url: mcp.url,+ };const patch: Record<string, any> = {};@@ -323,7 +381,16 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(patch.credentials = null;}- if (authType === 'oauth2') {+ // Write the OAuth client only when it (or the server it belongs to)+ // changed. Re-sending the form's `{ clientId: undefined, scheme: 'dcr' }`+ // on every save would replace the client the server resolved, and with+ // it the refresh tokens of every connected account.+ if (+ authType === 'oauth2' &&+ (!oauthBaseline ||+ isServerUrlChanged(oauthBaseline, oauthFields) ||+ isOAuthClientChanged(oauthBaseline, oauthFields))+ ) {const clientId = mcp.auth?.clientId?.trim();patch.oidcConfig = {clientId: clientId || undefined,@@ -332,7 +399,8 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(};}- if (isHttp && authType === 'oauth2') {+ // Same rule DevModal used to decide whether to open the popup.+ if (isHttp && authType === 'oauth2' && requiresOAuth(oauthBaseline, oauthFields)) {// Synced by its callback; a failed authorization undoes the editconst popup = ctx?.oauthPopup;try {@@ -466,6 +534,7 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(<DevModalenableDeviceBindingenableOAuth+ getOAuthPlan={getOAuthPlan}mode={isEditMode || isMigrationMode ? 'edit' : 'create'}open={open}value={editValue}diff --git a/src/features/Connectors/CustomConnectorModal/oauthPlan.test.ts b/src/features/Connectors/CustomConnectorModal/oauthPlan.test.tsnew file mode 100644index 00000000000..2f51052f333--- /dev/null+++ b/src/features/Connectors/CustomConnectorModal/oauthPlan.test.ts@@ -0,0 +1,66 @@+import { describe, expect, it } from 'vitest';++import {+ countDroppedAccounts,+ isOAuthClientChanged,+ type OAuthBaseline,+ requiresOAuth,+} from './oauthPlan';++const URL = 'https://mail.example.com/mcp';++/** An OAuth connector on a server-resolved (DCR) client with two accounts. */+const connected: OAuthBaseline = { accountCount: 2, authType: 'oauth2', mcpServerUrl: URL };+const untouched = { url: URL };++describe('requiresOAuth', () => {+ it('authorizes a connector that is being created', () => {+ expect(requiresOAuth(undefined, untouched)).toBe(true);+ });++ it('saves in place when neither the server nor the client changed', () => {+ expect(requiresOAuth(connected, untouched)).toBe(false);+ // Whitespace and an emptied optional field are not edits.+ expect(requiresOAuth(connected, { clientId: ' ', clientSecret: '', url: ` ${URL} ` })).toBe(+ false,+ );+ });++ it('authorizes when the server URL changed', () => {+ expect(requiresOAuth(connected, { url: 'https://other.example.com/mcp' })).toBe(true);+ });++ it('authorizes when the OAuth client changed', () => {+ expect(requiresOAuth(connected, { clientId: 'my-client', url: URL })).toBe(true);+ expect(requiresOAuth(connected, { clientSecret: 'new-secret', url: URL })).toBe(true);+ });++ it('authorizes when no account is connected yet', () => {+ expect(requiresOAuth({ ...connected, accountCount: 0 }, untouched)).toBe(true);+ });+});++describe('isOAuthClientChanged', () => {+ it('keeps a hand-registered client whose id is left as it was', () => {+ const preRegistered = { ...connected, clientId: 'my-client' };+ expect(isOAuthClientChanged(preRegistered, { clientId: 'my-client', url: URL })).toBe(false);+ expect(isOAuthClientChanged(preRegistered, { url: URL })).toBe(true);+ });++ it('treats switching another auth type to OAuth as a new client', () => {+ expect(isOAuthClientChanged({ accountCount: 0, authType: 'bearer' }, untouched)).toBe(true);+ });+});++describe('countDroppedAccounts', () => {+ it('counts every account when the URL or client id changes', () => {+ expect(countDroppedAccounts(connected, { url: 'https://other.example.com/mcp' })).toBe(2);+ expect(countDroppedAccounts(connected, { clientId: 'my-client', url: URL })).toBe(2);+ });++ it('drops nothing for a new secret, a plain save, or a new connector', () => {+ expect(countDroppedAccounts(connected, { clientSecret: 'new-secret', url: URL })).toBe(0);+ expect(countDroppedAccounts(connected, untouched)).toBe(0);+ expect(countDroppedAccounts(undefined, untouched)).toBe(0);+ });+});diff --git a/src/features/Connectors/CustomConnectorModal/oauthPlan.ts b/src/features/Connectors/CustomConnectorModal/oauthPlan.tsnew file mode 100644index 00000000000..c68d38afd7e--- /dev/null+++ b/src/features/Connectors/CustomConnectorModal/oauthPlan.ts@@ -0,0 +1,71 @@+/** What the edit form knew about the connector's OAuth setup when it opened. */+export interface OAuthBaseline {+ /** OAuth accounts connected now. */+ accountCount: number;+ /** Auth type the stored connector uses (`oauth2`, `bearer`, `none`, …). */+ authType?: string;+ /**+ * The hand-registered client id. A client the server resolved (DCR / CIMD)+ * is never shown in the form, so it stays `undefined` here as well.+ */+ clientId?: string;+ mcpServerUrl?: string | null;+}++/** The OAuth-relevant fields of the form as they would be saved. */+export interface OAuthFormFields {+ clientId?: string;+ clientSecret?: string;+ url?: string;+}++const normalize = (value?: string | null) => value?.trim() || undefined;++export const isServerUrlChanged = (baseline: OAuthBaseline, fields: OAuthFormFields): boolean =>+ normalize(fields.url) !== normalize(baseline.mcpServerUrl);++/** A different client id: the server then drops every connected account. */+export const isOAuthClientIdChanged = (baseline: OAuthBaseline, fields: OAuthFormFields): boolean =>+ normalize(fields.clientId) !== normalize(baseline.clientId);++/**+ * The OAuth client the form would save differs from the stored one: switching+ * to OAuth, another client id, or a newly typed secret (the stored secret is+ * never sent to the browser, so an empty field means "keep it").+ */+export const isOAuthClientChanged = (baseline: OAuthBaseline, fields: OAuthFormFields): boolean =>+ baseline.authType !== 'oauth2' ||+ isOAuthClientIdChanged(baseline, fields) ||+ !!normalize(fields.clientSecret);++/**+ * Whether saving an OAuth connector must take the user through authorization:+ * a new connector, a new server URL or OAuth client, or a connector with no+ * account yet. Any other edit (headers, description) saves in place and keeps+ * the connected accounts; re-authorizing one is on its row under Accounts.+ */+export const requiresOAuth = (+ baseline: OAuthBaseline | undefined,+ fields: OAuthFormFields,+): boolean => {+ if (!baseline) return true;+ return (+ isServerUrlChanged(baseline, fields) ||+ isOAuthClientChanged(baseline, fields) ||+ baseline.accountCount === 0+ );+};++/**+ * How many connected accounts saving would remove: the server clears them when+ * the URL or the client id changes, since their tokens belong to the old ones.+ */+export const countDroppedAccounts = (+ baseline: OAuthBaseline | undefined,+ fields: OAuthFormFields,+): number => {+ if (!baseline || baseline.accountCount === 0) return 0;+ return isServerUrlChanged(baseline, fields) || isOAuthClientIdChanged(baseline, fields)+ ? baseline.accountCount+ : 0;+};diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Arguments/index.test.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Arguments/index.test.tsxindex 40959ab0cb8..bd4e90f3016 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Arguments/index.test.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Arguments/index.test.tsx@@ -7,6 +7,27 @@ import { describe, expect, it, vi } from 'vitest';import Arguments from './index';+const accountNames: Record<string, string> = { lnk_work: '[email protected]' };++vi.mock('@/store/tool', () => ({+ useToolStore: <T,>(selector: (state: object) => T) => selector({}),+}));++vi.mock('@/store/tool/slices/connector', () => ({+ connectorSelectors: {+ // Names resolve only on the connector the call runs on, for the agent that ran it+ connectorLinkNameForTool: (identifier: string, linkId: string, agentId?: string) => () =>+ identifier === 'mail' && agentId === 'agt_mail' ? accountNames[linkId] : undefined,+ },+}));++vi.mock('../../../../../store', () => ({+ useConversationStore: <T,>(selector: (state: object) => T) =>+ selector({ context: { agentId: 'agt_mail' }, dbMessages: [] }),+}));++const scope = { identifier: 'mail', messageId: 'msg_1' };+vi.mock('@lobehub/ui', async (importOriginal) => ({...(await importOriginal<object>()),ActionIcon: ({@@ -67,4 +88,50 @@ describe('Arguments', () => {'true',);});++ it('names the connector account a call uses instead of its link id', () => {+ render(+ <Arguments+ {...scope}+ arguments={JSON.stringify({ link_id: 'lnk_work', subject: 'Hello', to: 'lnk_work' })}+ />,+ );++ const values = screen.getByTestId('descriptions');+ expect(values).toHaveTextContent('[email protected]');+ expect(values).toHaveTextContent('Hello');+ // Only the account argument is translated; a lookalike value elsewhere is data.+ expect(values).toHaveTextContent('lnk_work');+ });++ it('uses the renamed argument when the tool has its own link_id', () => {+ render(+ <Arguments+ {...scope}+ arguments={JSON.stringify({ connector_link_id: 'lnk_work', link_id: 'https://a.b/c' })}+ />,+ );++ expect(screen.getByTestId('descriptions')).toHaveTextContent('[email protected]://a.b/c');+ });++ it('shows an id that names no known account as it was sent', () => {+ render(<Arguments {...scope} arguments={JSON.stringify({ link_id: 'lnk_gone' })} />);++ expect(screen.getByTestId('descriptions')).toHaveTextContent('lnk_gone');+ });++ // Account ids repeat across connectors (every legacy one is `lnk_default`)+ it("never names an account from a connector other than the call's", () => {+ render(+ <Arguments+ arguments={JSON.stringify({ link_id: 'lnk_work' })}+ identifier="calendar"+ messageId="msg_1"+ />,+ );++ expect(screen.getByTestId('descriptions')).toHaveTextContent('lnk_work');+ expect(screen.getByTestId('descriptions')).not.toHaveTextContent('[email protected]');+ });});diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Arguments/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Arguments/index.tsxindex 7e3ea5054d7..26bb7a323ba 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Arguments/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Arguments/index.tsx@@ -10,6 +10,9 @@ import Descriptions from '@/components/Descriptions';import { useYamlArguments } from '@/hooks/useYamlArguments';import { shinyTextStyles } from '@/styles';+import type { ConnectorAccountScope } from '../useConnectorAccountNames';+import { useConnectorAccountNames } from '../useConnectorAccountNames';+const formatValue = (value: any): string => {if (Array.isArray(value)) {return value.map((v) => (typeof v === 'object' ? JSON.stringify(v) : v)).join(', ');@@ -23,96 +26,103 @@ const formatValue = (value: any): string => {return String(value);};-export interface ArgumentsProps {+export interface ArgumentsProps extends ConnectorAccountScope {actions?: ReactNode;arguments?: string;loading?: boolean;}-const Arguments = memo<ArgumentsProps>(({ arguments: args = '', loading, actions }) => {- const { t } = useTranslation('plugin');- const [wrap, setWrap] = useState(false);+const Arguments = memo<ArgumentsProps>(+ ({ arguments: args = '', loading, actions, identifier, messageId }) => {+ const { t } = useTranslation('plugin');+ const [wrap, setWrap] = useState(false);- const displayArgs = useMemo(() => {- try {- const obj = parse(args);- if (Object.keys(obj).length === 0) return {};- return obj;- } catch {- return args;- }- }, [args]);+ const displayArgs = useMemo(() => {+ try {+ const obj = parse(args);+ if (Object.keys(obj).length === 0) return {};+ return obj;+ } catch {+ return args;+ }+ }, [args]);- const yaml = useYamlArguments(args);+ const yaml = useYamlArguments(args);+ // A multi-account connector's `link_id` is an opaque id; show whose account+ // the call uses, as named in the connector's Accounts.+ const accountNames = useConnectorAccountNames(displayArgs, { identifier, messageId });- let contentNode;+ let contentNode;- if (typeof displayArgs === 'string') {- contentNode = !!yaml && (- <Highlighter language={'yaml'} showLanguage={false} wrap={wrap}>- {yaml}- </Highlighter>- );- } else if (Object.keys(displayArgs).length === 0) {- contentNode = null;- } else {- const items: DescriptionItem[] = Object.entries(displayArgs).map(([key, value]) => ({- copyable: true,- key,- label: key,- value: formatValue(value),- }));-- contentNode = (- <Flexbox paddingBlock={4} paddingInline={16}>- <Descriptions- bordered={false}- items={items}- labelWidth={140}- maxItemWidth={'100%'}- wrap={wrap}- classNames={{- label: cx(loading && shinyTextStyles.shinyText),- }}- styles={{- label: loading- ? { color: `color-mix(in srgb, ${cssVar.colorText} 33%, transparent)` }- : {},- }}- />- </Flexbox>- );- }+ if (typeof displayArgs === 'string') {+ contentNode = !!yaml && (+ <Highlighter language={'yaml'} showLanguage={false} wrap={wrap}>+ {yaml}+ </Highlighter>+ );+ } else if (Object.keys(displayArgs).length === 0) {+ contentNode = null;+ } else {+ const items: DescriptionItem[] = Object.entries(displayArgs).map(([key, value]) => ({+ copyable: true,+ key,+ label: key,+ value: accountNames[key] ?? formatValue(value),+ }));- return (- <>- <Flexbox- horizontal- align={'center'}- gap={4}- justify={'space-between'}- paddingBlock={8}- paddingInline={16}- >- <Text>{t('arguments.title')}</Text>- <Flexbox horizontal gap={4}>- <ActionIcon- active={wrap}- icon={WrapText}- size={'small'}- title={t(- wrap ? 'workingPanel.review.wordWrap.disable' : 'workingPanel.review.wordWrap.enable',- { ns: 'chat' },- )}- onClick={() => setWrap((value) => !value)}+ contentNode = (+ <Flexbox paddingBlock={4} paddingInline={16}>+ <Descriptions+ bordered={false}+ items={items}+ labelWidth={140}+ maxItemWidth={'100%'}+ wrap={wrap}+ classNames={{+ label: cx(loading && shinyTextStyles.shinyText),+ }}+ styles={{+ label: loading+ ? { color: `color-mix(in srgb, ${cssVar.colorText} 33%, transparent)` }+ : {},+ }}/>- {actions}</Flexbox>- </Flexbox>- <Divider style={{ marginBlock: 0 }} />- {contentNode}- </>- );-});+ );+ }++ return (+ <>+ <Flexbox+ horizontal+ align={'center'}+ gap={4}+ justify={'space-between'}+ paddingBlock={8}+ paddingInline={16}+ >+ <Text>{t('arguments.title')}</Text>+ <Flexbox horizontal gap={4}>+ <ActionIcon+ active={wrap}+ icon={WrapText}+ size={'small'}+ title={t(+ wrap+ ? 'workingPanel.review.wordWrap.disable'+ : 'workingPanel.review.wordWrap.enable',+ { ns: 'chat' },+ )}+ onClick={() => setWrap((value) => !value)}+ />+ {actions}+ </Flexbox>+ </Flexbox>+ <Divider style={{ marginBlock: 0 }} />+ {contentNode}+ </>+ );+ },+);export default Arguments;diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.test.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.test.tsxindex bc532b071f8..47a46195312 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.test.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.test.tsx@@ -20,7 +20,7 @@ const metaMap: Record<string, { avatar?: string; title?: string }> = {vi.mock('react-i18next', () => ({useTranslation: () => ({- t: (key: string, options?: { count?: number; defaultValue?: string }) =>+ t: (key: string, options?: { count?: number; defaultValue?: string; name?: string }) =>(({'builtins.lobe-activator.apiName.activateTools': 'Activate Tools',@@ -30,7 +30,9 @@ vi.mock('react-i18next', () => ({)[key] ||(key === 'tool.intervention.viewParameters'? `View parameters (${options?.count ?? 0})`- : options?.defaultValue || key),+ : key === 'connector.account.usingAccount'+ ? `Account: ${options?.name}`+ : options?.defaultValue || key),}),}));@@ -84,6 +86,16 @@ vi.mock('@/store/tool', () => ({useToolStore: (selector: (state: unknown) => unknown) => selector({}),}));+const accountNames: Record<string, string> = { lnk_work: '[email protected]' };++vi.mock('@/store/tool/slices/connector', () => ({+ connectorSelectors: {+ // Names resolve only on the connector the call runs on, for the agent that ran it+ connectorLinkNameForTool: (identifier: string, linkId: string, agentId?: string) => () =>+ identifier === 'mail' && agentId === 'agt_mail' ? accountNames[linkId] : undefined,+ },+}));+vi.mock('@/store/chat', () => ({useChatStore: (selector: (state: unknown) => unknown) =>selector({ runQuestionSubmission: vi.fn() }),@@ -113,6 +125,8 @@ vi.mock('../../../../../store', () => ({}) => unknown,) =>selector({+ context: { agentId: 'agt_mail' },+ dbMessages: [],cancelToolInteraction: vi.fn(),skipToolInteraction: vi.fn(),submitHeteroIntervention,@@ -172,6 +186,38 @@ describe('FallbackIntervention', () => {expect(screen.getByText(reason)).toBeInTheDocument();});+ // Parameters start collapsed, so approving a connector call must name the+ // account it acts as without expanding them.+ it('names the account a multi-account connector call will use', () => {+ render(+ <FallbackIntervention+ apiName="send_email"+ assistantGroupId="assistant-group-1"+ id="message-1"+ identifier="mail"+ requestArgs={JSON.stringify({ link_id: 'lnk_work', to: '[email protected]' })}+ toolCallId="tool-call-1"+ />,+ );++ expect(screen.getByText('Account: [email protected]')).toBeInTheDocument();+ });++ it('adds no account line when the id names no known account', () => {+ render(+ <FallbackIntervention+ apiName="send_email"+ assistantGroupId="assistant-group-1"+ id="message-1"+ identifier="mail"+ requestArgs={JSON.stringify({ link_id: 'lnk_gone' })}+ toolCallId="tool-call-1"+ />,+ );++ expect(screen.queryByText(/^Account:/)).not.toBeInTheDocument();+ });+it('renders URL avatars as images instead of visible text', () => {const iconUrl = 'https://example.com/icon.png';metaMap.search.avatar = iconUrl;diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.tsxindex fd8b9454f13..23223dba6f9 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.tsx@@ -21,6 +21,7 @@ import { toolInterventionSelectors } from '@/store/user/selectors';import { dataSelectors, useConversationStore } from '../../../../../store';import Arguments from '../Arguments';+import { useConnectorAccountNames } from '../useConnectorAccountNames';import ApprovalActions from './ApprovalActions';import KeyValueEditor from './KeyValueEditor';@@ -62,7 +63,7 @@ interface FallbackInterventionProps {const FallbackIntervention = memo<FallbackInterventionProps>(({ requestArgs, id, identifier, apiName, toolCallId, assistantGroupId, actionsPortalTarget }) => {- const { t } = useTranslation(['chat', 'plugin', 'common']);+ const { t } = useTranslation(['chat', 'plugin', 'common', 'tool']);const approvalMode = useUserStore(toolInterventionSelectors.approvalMode);const [isEditing, setIsEditing] = useState(false);const [showArgs, setShowArgs] = useState(false);@@ -97,6 +98,11 @@ const FallbackIntervention = memo<FallbackInterventionProps>([pendingEditedArguments, requestArgs],);const argCount = typeof parsedArgs === 'object' ? Object.keys(parsedArgs).length : 0;+ // The parameters start collapsed, so the account a connector call acts as+ // is named next to the action: approving "send email" must say from where.+ const accountName = Object.values(+ useConnectorAccountNames(parsedArgs, { identifier, messageId: id }),+ )[0];const isActivateToolsIntervention =identifier === LobeActivatorIdentifier && apiName === ActivatorApiName.activateTools;const requestedToolIdentifiers = useMemo(() => {@@ -156,7 +162,9 @@ const FallbackIntervention = memo<FallbackInterventionProps>(if (isEditing)return (- <Suspense fallback={<Arguments arguments={renderedArgs} />}>+ <Suspense+ fallback={<Arguments arguments={renderedArgs} identifier={identifier} messageId={id} />}+ ><KeyValueEditorinitialValue={parsedArgs}onCancel={handleCancel}@@ -204,6 +212,11 @@ const FallbackIntervention = memo<FallbackInterventionProps>(</Flexbox>{activationReason && <div {...stylex.props(styles.reason)}>{activationReason}</div>}+ {accountName && (+ <div {...stylex.props(styles.reason)}>+ {t('connector.account.usingAccount', { name: accountName, ns: 'tool' })}+ </div>+ )}{argCount > 0 && (<>@@ -233,7 +246,9 @@ const FallbackIntervention = memo<FallbackInterventionProps>(/>)}</Flexbox>- {showArgs && <Arguments arguments={renderedArgs} />}+ {showArgs && (+ <Arguments arguments={renderedArgs} identifier={identifier} messageId={id} />+ )}</>)}diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsxindex ae39d5ea596..61bb74a0f07 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx@@ -287,7 +287,9 @@ const Intervention = memo<InterventionProps>(if (BuiltinToolInterventionRender) {if (isEditing)return (- <Suspense fallback={<Arguments arguments={requestArgs} />}>+ <Suspense+ fallback={<Arguments arguments={requestArgs} identifier={identifier} messageId={id} />}+ ><KeyValueEditorinitialValue={parsedArgs}onCancel={handleCancel}diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/LoadingPlaceholder/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/LoadingPlaceholder/index.tsxindex 07a377e09ff..18b68e9b751 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/LoadingPlaceholder/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/LoadingPlaceholder/index.tsx@@ -31,7 +31,14 @@ const LoadingPlaceholder = memo<LoadingPlaceholderProps>();}- return <Arguments arguments={requestArgs} loading={loading} />;+ return (+ <Arguments+ arguments={requestArgs}+ identifier={identifier}+ loading={loading}+ messageId={messageId}+ />+ );},);diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Render/FallbacktArgumentRender.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Render/FallbacktArgumentRender.tsxindex a1aeb69043d..14b415d9e90 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Render/FallbacktArgumentRender.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Render/FallbacktArgumentRender.tsx@@ -6,12 +6,14 @@ import Arguments from '../Arguments';interface FallbackArgumentRenderProps {content: string;+ identifier?: string;+ messageId?: string;requestArgs?: string;toolCallId: string;}export const FallbackArgumentRender = memo<FallbackArgumentRenderProps>(- ({ toolCallId, content, requestArgs }) => {+ ({ toolCallId, content, identifier, messageId, requestArgs }) => {const { t } = useTranslation('plugin');// Parse and display result content@@ -31,7 +33,7 @@ export const FallbackArgumentRender = memo<FallbackArgumentRenderProps>(// Default render: show arguments and resultreturn (<Block id={toolCallId} variant={'outlined'} width={'100%'}>- <Arguments arguments={requestArgs} />+ <Arguments arguments={requestArgs} identifier={identifier} messageId={messageId} />{content && (<><Divider style={{ marginBlock: 0 }} />diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Render/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Render/index.tsxindex 8433e5cd1dc..ed578e15ca7 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Render/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Render/index.tsx@@ -79,6 +79,8 @@ const ToolRender = memo<ToolRenderProps>(const fallback = (<FallbackArgumentRendercontent={resolvedContent}+ identifier={plugin?.identifier}+ messageId={messageId}requestArgs={plugin?.arguments}toolCallId={toolCallId}/>diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/useConnectorAccountNames.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/useConnectorAccountNames.tsnew file mode 100644index 00000000000..e65feba614b--- /dev/null+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/useConnectorAccountNames.ts@@ -0,0 +1,45 @@+import { isConnectorLinkParam } from '@lobechat/mecha';+import isEqual from 'fast-deep-equal';++import { mcpAppAgentIdSelector } from '@/features/MCPApp/viewAgent';+import { useToolStore } from '@/store/tool';+import { connectorSelectors } from '@/store/tool/slices/connector';++import { useConversationStore } from '../../../../store';++const NO_NAMES: Record<string, string> = {};++export interface ConnectorAccountScope {+ /** The tool's identifier: a connector tool's is its connector's. */+ identifier?: string;+ /** A message of the call, to find the agent that ran it. */+ messageId?: string;+}++/**+ * Account names for the account arguments of a tool call, keyed by argument.+ * Account ids are unique per connector only, so names come from the connector+ * this call runs on (as the call resolves it), never from another connector+ * that happens to hold the same id. An id that names no account there (another+ * workspace, a removed account, a value still streaming in) is left out, so+ * callers show it as it was sent.+ */+export const useConnectorAccountNames = (+ args: unknown,+ { identifier, messageId }: ConnectorAccountScope,+): Record<string, string> => {+ const agentId = useConversationStore(mcpAppAgentIdSelector(messageId));++ return useToolStore((s) => {+ if (!identifier || !args || typeof args !== 'object') return NO_NAMES;++ let names: Record<string, string> | undefined;+ // `link_id`, or `connector_link_id…` when a tool declares `link_id` itself.+ for (const [param, value] of Object.entries(args)) {+ if (typeof value !== 'string' || !isConnectorLinkParam(param)) continue;+ const name = connectorSelectors.connectorLinkNameForTool(identifier, value, agentId)(s);+ if (name) (names ??= {})[param] = name;+ }+ return names ?? NO_NAMES;+ }, isEqual);+};diff --git a/src/features/Conversation/WorkingSidebar/McpEntryPane.tsx b/src/features/Conversation/WorkingSidebar/McpEntryPane.tsxindex 6aec35bff25..f6afac0d159 100644--- a/src/features/Conversation/WorkingSidebar/McpEntryPane.tsx+++ b/src/features/Conversation/WorkingSidebar/McpEntryPane.tsx@@ -29,6 +29,7 @@ export const McpEntryPane = ({const entry = parseMcpEntryTab(tab);const identifier = entry?.identifier;const toolName = entry?.toolName;+ const linkId = entry?.linkId;const [title] = useMcpAppIdentity(identifier ?? '', agentId);const id = mcpEntryInstanceId(scope, tab);useEffect(() => {@@ -38,7 +39,8 @@ export const McpEntryPane = ({const state = useMcpAppStore(mcpAppSelectors.entry(id));const open = () => {setUnsupported(false);- if (identifier && toolName) void openMcpAppEntrypoint({ agentId, id, identifier, toolName });+ if (identifier && toolName)+ void openMcpAppEntrypoint({ agentId, id, identifier, linkId, toolName });};// Context the view reported belongs to this instance onlyuseEffect(() => () => mcpAppContext.clear(id), [id]);@@ -71,6 +73,7 @@ export const McpEntryPane = ({arguments={'{}'}fallback={<Text>{t('mcpApp.entrypoint.error')}</Text>}identifier={entry.identifier}+ linkId={linkId}resourceUri={app.resourceUri}result={{ content: result.content, state: unwrapMcpToolState(result.state) }}server={app.server}diff --git a/src/features/Conversation/WorkingSidebar/McpEntryTabLabel.tsx b/src/features/Conversation/WorkingSidebar/McpEntryTabLabel.tsxindex af555dc6273..24fe5c92f93 100644--- a/src/features/Conversation/WorkingSidebar/McpEntryTabLabel.tsx+++ b/src/features/Conversation/WorkingSidebar/McpEntryTabLabel.tsx@@ -1,6 +1,10 @@import { useTranslation } from 'react-i18next';-import { parseMcpEntryTab, selectMcpAppEntrypoints } from '@/features/MCPApp/entrypoints';+import {+ isEntryOfTab,+ parseMcpEntryTab,+ selectMcpAppEntrypoints,+} from '@/features/MCPApp/entrypoints';import { useToolStore } from '@/store/tool';import { LazyPluginAvatar } from './LazyPluginAvatar';@@ -8,12 +12,12 @@ import { LazyPluginAvatar } from './LazyPluginAvatar';export const McpEntryTabLabel = ({ tab, agentId }: { tab: string; agentId?: string }) => {const parsed = parseMcpEntryTab(tab);const { t } = useTranslation('plugin');- const title = useToolStore(- (s) =>- selectMcpAppEntrypoints(s, true, agentId).find(- (entry) => entry.identifier === parsed?.identifier && entry.toolName === parsed?.toolName,- )?.title,- );+ const title = useToolStore((s) => {+ const entry = selectMcpAppEntrypoints(s, true, agentId).find((item) =>+ isEntryOfTab(item, parsed),+ );+ return entry?.accountName ? `${entry.title} · ${entry.accountName}` : entry?.title;+ });return <>{title ?? parsed?.toolName ?? t('mcpApp.entrypoints')}</>;};@@ -21,9 +25,7 @@ export const McpEntryTabIcon = ({ tab, agentId }: { tab: string; agentId?: strinconst parsed = parseMcpEntryTab(tab);const icon = useToolStore((s) =>- selectMcpAppEntrypoints(s, true, agentId).find(- (entry) => entry.identifier === parsed?.identifier && entry.toolName === parsed?.toolName,- )?.icon,+ selectMcpAppEntrypoints(s, true, agentId).find((entry) => isEntryOfTab(entry, parsed))?.icon,);return <LazyPluginAvatar avatar={icon || 'MCP_AVATAR'} size={14} />;};diff --git a/src/features/Conversation/WorkingSidebar/useOpenMenuItems.tsx b/src/features/Conversation/WorkingSidebar/useOpenMenuItems.tsxindex 2cb833bc187..7ddb63bebb8 100644--- a/src/features/Conversation/WorkingSidebar/useOpenMenuItems.tsx+++ b/src/features/Conversation/WorkingSidebar/useOpenMenuItems.tsx@@ -113,10 +113,10 @@ export const useOpenMenuItems = ({key: 'mcp-apps',label: groupLabel(t('mcpApp.entrypoints', { ns: 'plugin' })),children: entries.map((entry) => {- const key = mcpEntryTabKey(entry.identifier, entry.toolName);+ const key = mcpEntryTabKey(entry.identifier, entry.toolName, entry.linkId);return {key,- label: entry.title,+ label: entry.accountName ? `${entry.title} · ${entry.accountName}` : entry.title,icon: entry.icon ? (<img alt={''} height={14} src={entry.icon} width={14} />) : (@@ -135,6 +135,7 @@ export const useOpenMenuItems = ({agentId,id,identifier: entry.identifier,+ linkId: entry.linkId,toolName: entry.toolName,}),);diff --git a/src/features/MCPApp/McpAppView.tsx b/src/features/MCPApp/McpAppView.tsxindex 9142c7b9d2b..b460f487b28 100644--- a/src/features/MCPApp/McpAppView.tsx+++ b/src/features/MCPApp/McpAppView.tsx@@ -56,6 +56,11 @@ export interface McpAppViewProps {fallback: ReactNode;host: Pick<AppViewContext, 'agentId' | 'sendMessage' | 'canSendMessage'>;identifier: string;+ /**+ * The connector account the view acts as, when its arguments cannot name+ * one: an entrypoint opens with `{}`.+ */+ linkId?: string;/** The message carrying the result; its agent is the one the view acts as. */messageId?: string;/** This desktop's own MCP process produced the result: the view is read, and calls, there. */@@ -91,6 +96,7 @@ const McpAppView = memo<McpAppViewProps>(fallback,identifier,host,+ linkId,presentation,onThisDevice = false,resourceUri,@@ -112,8 +118,10 @@ const McpAppView = memo<McpAppViewProps>(const useFetchMcpAppResource = useToolStore((s) => s.useFetchMcpAppResource);const { data, error, isLoading } = useFetchMcpAppResource(identifier, resourceUri, {agentId,+ linkId,onThisDevice,server,+ toolArguments: args,});const resource = pickAppResource(data, resourceUri);@@ -170,6 +178,7 @@ const McpAppView = memo<McpAppViewProps>(canSendMessage,identifier,isDark,+ linkId,onThisDevice,result,sendMessage,diff --git a/src/features/MCPApp/appHost.test.ts b/src/features/MCPApp/appHost.test.tsindex 5f688303098..e856487f08f 100644--- a/src/features/MCPApp/appHost.test.ts+++ b/src/features/MCPApp/appHost.test.ts@@ -25,7 +25,8 @@ const {vi.mock('@/services/mcp', () => ({ mcpService: { invokeMcpToolCall } }));-vi.mock('@/store/tool', () => ({ getToolStoreState: () => ({}) }));+const toolState = vi.hoisted(() => ({ value: {} as any }));+vi.mock('@/store/tool', () => ({ getToolStoreState: () => toolState.value }));vi.mock('./appName', () => ({ mcpAppNameSelector: () => () => 'Weather Demo' }));@@ -38,7 +39,11 @@ const flush = () => new Promise((resolve) => setTimeout(resolve, 0));const disposers: (() => void)[] = [];/** Connect a view in a fresh frame, as McpAppView does once the frame has loaded. */-const setup = ({ canSendMessage = true }: { canSendMessage?: boolean } = {}) => {+const setup = ({+ canSendMessage = true,+ args = '{"city":"Paris"}',+ linkId,+}: { canSendMessage?: boolean; args?: string; linkId?: string } = {}) => {const iframe = document.createElement('iframe');document.body.append(iframe);const target = iframe.contentWindow!;@@ -51,7 +56,8 @@ const setup = ({ canSendMessage = true }: { canSendMessage?: boolean } = {}) =>const { dispose, teardown } = connectAppView({getContext: () => ({agentId: 'agt_1',- args: '{"city":"Paris"}',+ args,+ linkId,canSendMessage,identifier: 'weather-demo',isDark: false,@@ -152,6 +158,7 @@ describe('getAppViewPhase', () => {describe('connectAppView', () => {beforeEach(() => {+ toolState.value = {};vi.clearAllMocks();getAppToolCallPolicy.mockResolvedValue('confirm');sendMessage.mockImplementation(async ({ onMessageAccepted }) => onMessageAccepted?.());@@ -566,6 +573,35 @@ describe('connectAppView', () => {dispose();expect(signal.aborted).toBe(true);});+ it('keeps view tools/call bound to the initiating account including collision fallback', async () => {+ toolState.value = {+ connectors: [+ { identifier: 'weather-demo', tools: [{ inputSchema: { properties: { link_id: {} } } }] },+ ],+ };+ getAppToolCallPolicy.mockResolvedValue('allow');+ invokeMcpToolCall.mockResolvedValue({ content: 'ok', success: true });+ const { call } = setup({ args: '{"connector_link_id":"lnk_bob","link_id":"business"}' });+ await call(401);+ expect(invokeMcpToolCall).toHaveBeenLastCalledWith(+ expect.anything(),+ expect.objectContaining({ fromMcpApp: true, linkId: 'lnk_bob' }),+ );+ });+ // An entrypoint opens with `{}`: its account comes with the view instead+ it("keeps an entrypoint view's tools/call on the account it opened as", async () => {+ toolState.value = {+ connectors: [{ identifier: 'weather-demo', tools: [{ inputSchema: { properties: {} } }] }],+ };+ getAppToolCallPolicy.mockResolvedValue('allow');+ invokeMcpToolCall.mockResolvedValue({ content: 'ok', success: true });+ const { call } = setup({ args: '{}', linkId: 'lnk_bob' });+ await call(402);+ expect(invokeMcpToolCall).toHaveBeenLastCalledWith(+ expect.anything(),+ expect.objectContaining({ fromMcpApp: true, linkId: 'lnk_bob' }),+ );+ });});describe('a view that is leaving', () => {diff --git a/src/features/MCPApp/appHost.ts b/src/features/MCPApp/appHost.tsindex c380e1a593e..ceba8df6d8d 100644--- a/src/features/MCPApp/appHost.ts+++ b/src/features/MCPApp/appHost.ts@@ -1,10 +1,13 @@+import { resolveConnectorLinkParam } from '@lobechat/mecha';import type { SendMessageParams } from '@lobechat/types';import { safeParseJSON } from '@lobechat/utils';+import { isRecord } from '@lobechat/utils/object';import type { AppBridge } from '@modelcontextprotocol/ext-apps/app-bridge';import type { TFunction } from 'i18next';import { mcpService } from '@/services/mcp';import { getToolStoreState } from '@/store/tool';+import { connectorSelectors } from '@/store/tool/slices/connector/selectors';import { anySignal } from './abortSignal';import { mcpAppNameSelector } from './appName';@@ -35,6 +38,8 @@ export interface AppViewContext {identifier: string;isDark: boolean;lifecycle?: McpAppBridgeHost['lifecycle'];+ /** The account the view acts as, when its arguments cannot name one (an entrypoint's `{}`). */+ linkId?: string;/** This desktop's own MCP process produced the result; the view's calls run there. */onThisDevice: boolean;/** Tool call result envelope (`{ content, state, success }`). */@@ -151,7 +156,16 @@ export const connectAppView = ({// Views may only call tools on the server that rendered them, and// under the same approval rules as the conversation.callTool: async (name, toolArgs, request) => {- const { agentId, identifier, onThisDevice, server, t } = getContext();+ const {+ agentId,+ identifier,+ onThisDevice,+ server,+ t,+ args: initiatingArgs,+ linkId: viewLinkId,+ } = getContext();+ const linkId = viewLinkId ?? getMcpAppLinkId(identifier, agentId, initiatingArgs);const policy = await getAppToolCallPolicy(identifier, name, { agentId, toolArgs });let allowed = policy === 'allow';if (policy === 'confirm') {@@ -200,7 +214,7 @@ export const connectAppView = ({type: 'mcp',},// The view's HTML came from this machine for a local server, so its calls do too- { agentId, fromMcpApp: true, onThisDevice, server, signal },+ { agentId, fromMcpApp: true, onThisDevice, server, signal, linkId },),);} finally {@@ -314,3 +328,18 @@ export const getAppViewPhase = ({if (!srcDoc || navigated) return 'fallback';return 'view';};++/** Bind a view to the account of the tool call that created it. */+export const getMcpAppLinkId = (+ identifier: string,+ agentId?: string,+ args?: string,+): string | undefined => {+ const connector = connectorSelectors.connectorByIdentifierForAgent(+ identifier,+ agentId,+ )(getToolStoreState());+ const param = resolveConnectorLinkParam(connector?.tools.map((tool) => tool.inputSchema) ?? []);+ const input: unknown = safeParseJSON(args ?? '{}');+ return isRecord(input) && typeof input[param] === 'string' ? (input[param] as string) : undefined;+};diff --git a/src/features/MCPApp/entrypoints.test.ts b/src/features/MCPApp/entrypoints.test.tsindex d4756fc0113..911d883eb2e 100644--- a/src/features/MCPApp/entrypoints.test.ts+++ b/src/features/MCPApp/entrypoints.test.ts@@ -2,7 +2,12 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import type { ToolStore } from '@/store/tool/store';-import { mcpEntryTabKey, parseMcpEntryTab, selectMcpAppEntrypoints } from './entrypoints';+import {+ isEntryOfTab,+ mcpEntryTabKey,+ parseMcpEntryTab,+ selectMcpAppEntrypoints,+} from './entrypoints';const env = vi.hoisted(() => ({ desktop: false, gateway: true }));vi.mock('@lobechat/const', async (importOriginal) => ({@@ -57,6 +62,48 @@ describe('sidebar app entries', () => {});expect(parseMcpEntryTab('mcp-entry:bad:%XX')).toBeUndefined();});+ // An entrypoint's call carries no arguments, so it can't select an account+ it('offers an app once per account of a connector holding several', () => {+ const connector = (links: { id: string; name: string }[]) =>+ ({+ ...state,+ connectors: [+ {+ id: 'mail',+ identifier: 'mail',+ isEnabled: true,+ links,+ mcpServerUrl: 'https://example.com',+ tools: [{ metadata: { threadEntry: entry }, permission: 'auto', toolName: 'open' }],+ },+ ],+ installedPlugins: [],+ }) as unknown as ToolStore;++ expect(+ selectMcpAppEntrypoints(+ connector([+ { id: 'lnk_a', name: 'Work' },+ { id: 'lnk_b', name: 'Personal' },+ ]),+ true,+ ),+ ).toEqual([+ { ...entry, accountName: 'Work', identifier: 'mail', linkId: 'lnk_a' },+ { ...entry, accountName: 'Personal', identifier: 'mail', linkId: 'lnk_b' },+ ]);+ expect(selectMcpAppEntrypoints(connector([{ id: 'lnk_a', name: 'Work' }]), true)).toEqual([+ { ...entry, identifier: 'mail' },+ ]);+ });+ it("keeps an entry's account in its tab", () => {+ const tab = parseMcpEntryTab(mcpEntryTabKey('mail', 'open', 'lnk_b'));+ expect(tab).toEqual({ identifier: 'mail', linkId: 'lnk_b', toolName: 'open' });+ const base = { ...entry, identifier: 'mail' };+ expect(isEntryOfTab({ ...base, linkId: 'lnk_b' }, tab)).toBe(true);+ expect(isEntryOfTab({ ...base, linkId: 'lnk_a' }, tab)).toBe(false);+ expect(isEntryOfTab(base, parseMcpEntryTab(mcpEntryTabKey('mail', 'open')))).toBe(true);+ });it('offers apps only a desktop can run (stdio) on the desktop alone', () => {const open = { title: 'Local', toolName: 'open' };const desktopOnly = {diff --git a/src/features/MCPApp/entrypoints.ts b/src/features/MCPApp/entrypoints.tsindex 8e9e27b9317..692e237b618 100644--- a/src/features/MCPApp/entrypoints.ts+++ b/src/features/MCPApp/entrypoints.ts@@ -12,22 +12,43 @@ import { connectorSelectors } from '@/store/tool/slices/connector/selectors';import type { ToolStore } from '@/store/tool/store';export interface AppEntrypoint extends McpAppThreadEntry {+ /** Name of the account it opens as, on a connector holding several. */+ accountName?: string;identifier: string;+ /**+ * The account it opens as, on a connector holding several: an entrypoint's+ * call carries no arguments to select one, so each account is its own entry.+ */+ linkId?: string;}-export const mcpEntryTabKey = (identifier: string, toolName: string) =>- `mcp-entry:${encodeURIComponent(identifier)}:${encodeURIComponent(toolName)}`;+export const mcpEntryTabKey = (identifier: string, toolName: string, linkId?: string) =>+ `mcp-entry:${encodeURIComponent(identifier)}:${encodeURIComponent(toolName)}${+ linkId ? `:${encodeURIComponent(linkId)}` : ''+ }`;/** One entrypoint tab's app instance: per conversation (`scope`) and tab. */export const mcpEntryInstanceId = (scope: string, tab: string) => `${scope}:${tab}`;-export const parseMcpEntryTab = (tab: string) => {+export const parseMcpEntryTab = (+ tab: string,+): { identifier: string; linkId?: string; toolName: string } | undefined => {if (!tab.startsWith('mcp-entry:')) return;const parts = tab.slice(10).split(':');- if (parts.length !== 2) return;+ if (parts.length !== 2 && parts.length !== 3) return;try {- return { identifier: decodeURIComponent(parts[0]), toolName: decodeURIComponent(parts[1]) };+ const [identifier, toolName, linkId] = parts.map(decodeURIComponent);+ return { identifier, toolName, ...(linkId && { linkId }) };} catch {return;}};+/** The entry a tab opens: the same tool, and the same account on a connector holding several. */+export const isEntryOfTab = (+ entry: AppEntrypoint,+ tab: { identifier: string; linkId?: string; toolName: string } | undefined,+) =>+ !!tab &&+ entry.identifier === tab.identifier &&+ entry.toolName === tab.toolName &&+ entry.linkId === tab.linkId;/*** Whether an app's MCP server opens only in the desktop app: elsewhere the@@ -74,12 +95,23 @@ export const selectMcpAppEntrypoints = (return entry ? [entry] : [];}): (plugin?.manifest?.mcpAppEntrypoints ?? []);+ // One entry per account when the connector holds several: its call can't select one+ const accounts = isMcp && (connector.links?.length ?? 0) > 1 ? connector.links! : undefined;return entries.filter((entry) =>connector?.tools.find((tool) => tool.toolName === entry.toolName)?.permission !=='disabled',)- .map((entry) => ({ ...entry, identifier }));+ .flatMap((entry): AppEntrypoint[] =>+ accounts+ ? accounts.map((account) => ({+ ...entry,+ accountName: account.name,+ identifier,+ linkId: account.id,+ }))+ : [{ ...entry, identifier }],+ );});};diff --git a/src/features/MCPApp/openEntrypoint.test.ts b/src/features/MCPApp/openEntrypoint.test.tsindex b8ffc7fe1d8..9904badb9d0 100644--- a/src/features/MCPApp/openEntrypoint.test.ts+++ b/src/features/MCPApp/openEntrypoint.test.ts@@ -60,6 +60,18 @@ describe('openMcpAppEntrypoint', () => {expect(entry()).toMatchObject({ result: { content: 'first' }, status: 'ready' });});+ it('opens as the account its entry names on a connector holding several', async () => {+ mocks.invoke.mockResolvedValue(viewResult('bob'));++ await openMcpAppEntrypoint({ ...call, linkId: 'lnk_bob' });++ expect(mocks.invoke).toHaveBeenCalledWith(expect.objectContaining({ arguments: '{}' }), {+ agentId: 'agent',+ fromEntrypoint: true,+ linkId: 'lnk_bob',+ });+ });+it('shows the tab as opening until the call answers', async () => {let answer!: (value: unknown) => void;mocks.invoke.mockReturnValue(new Promise((resolve) => (answer = resolve)));diff --git a/src/features/MCPApp/openEntrypoint.ts b/src/features/MCPApp/openEntrypoint.tsindex 2ddc916b69b..cc83a5965e4 100644--- a/src/features/MCPApp/openEntrypoint.ts+++ b/src/features/MCPApp/openEntrypoint.ts@@ -10,6 +10,8 @@ export interface McpAppEntrypointCall {/** The tab instance: one per topic and entrypoint. */id: string;identifier: string;+ /** The account to open as, on a connector holding several. */+ linkId?: string;toolName: string;}@@ -18,6 +20,7 @@ export const callMcpAppEntrypoint = async ({agentId,id,identifier,+ linkId,toolName,}: McpAppEntrypointCall): Promise<MCPToolCallResult> => {// Entrypoints ignore `_meta.ui.visibility`; the agent's tool rules still apply@@ -29,7 +32,7 @@ export const callMcpAppEntrypoint = async ({const response = await mcpService.invokeMcpToolCall({ apiName: toolName, arguments: '{}', id, identifier, type: 'mcp' },- { agentId, fromEntrypoint: true },+ { agentId, fromEntrypoint: true, linkId },);if (!response?.success || !getMcpAppFromState(response.state)) {throw new Error('The entrypoint returned no app view');diff --git a/src/features/MCPApp/useMcpAppPresentation.ts b/src/features/MCPApp/useMcpAppPresentation.tsindex 45f2d0debee..7bfab066a2f 100644--- a/src/features/MCPApp/useMcpAppPresentation.ts+++ b/src/features/MCPApp/useMcpAppPresentation.ts@@ -12,6 +12,8 @@ import { pickAppResource } from './utils';export interface AppPresentationOptions {agentId?: string;+ /** The tool call's arguments: they name the account it ran as. */+ arguments?: string;icon?: string;identifier: string;location: 'inline' | 'fullscreen';@@ -31,6 +33,7 @@ let lastHostInstance = 0;/** Ownership and protocol callbacks shared by the inline and sidebar hosts. */export const useMcpAppPresentation = ({agentId,+ arguments: toolArguments,icon,identifier,location,@@ -68,6 +71,7 @@ export const useMcpAppPresentation = ({agentId,onThisDevice,server,+ toolArguments,});useEffect(() => {if (!deciding || isLoading) return;diff --git a/src/features/PluginDevModal/MCPManifestForm/index.tsx b/src/features/PluginDevModal/MCPManifestForm/index.tsxindex f1d2f921a36..afcf4f75dec 100644--- a/src/features/PluginDevModal/MCPManifestForm/index.tsx+++ b/src/features/PluginDevModal/MCPManifestForm/index.tsx@@ -1,6 +1,15 @@import { type LobeToolCustomPlugin, type McpConnectVia } from '@lobechat/types';import { isDeviceOnlyMcpEndpoint } from '@lobechat/utils/mcpEndpoint';-import { Alert, Button, Divider, Flexbox, Input, InputPassword, RadioGroup } from '@lobehub/ui';+import {+ Alert,+ Button,+ Divider,+ Flexbox,+ Input,+ InputPassword,+ RadioGroup,+ Text,+} from '@lobehub/ui';import { type FieldPath, Form, type FormInstance, useWatch } from '@lobehub/ui/form';import isEqual from 'fast-deep-equal';import { useEffect, useState } from 'react';@@ -35,14 +44,24 @@ interface MCPManifestFormProps {enableOAuth?: boolean;form: FormInstance<LobeToolCustomPlugin>;isEditMode?: boolean;+ /** What saving the OAuth settings will do to the connected accounts. */+ oauthNotice?: OAuthNotice;/*** Run the connector OAuth authorize flow. Called instead of the token-less* manifest test when the OAuth auth type is selected (testing an OAuth server- * without authorizing first only ever 401s).+ * without authorizing first only ever 401s). Omitted while saving would not+ * authorize (an edit that keeps the connected accounts), which hides the+ * button: there is nothing to authorize or test.*/onAuthorizeOAuth?: () => void;}+export interface OAuthNotice {+ text: string;+ /** `warning` when saving removes accounts; `info` when it keeps them. */+ type: 'info' | 'warning';+}+const HTTP_URL_KEY = 'customParams.mcp.url';const CONNECT_VIA = 'customParams.mcp.connectVia';const BOUND_DEVICE = 'customParams.mcp.boundDeviceId';@@ -83,6 +102,7 @@ const MCPManifestForm = ({enableDeviceBinding,enableOAuth,onAuthorizeOAuth,+ oauthNotice,}: MCPManifestFormProps) => {const { t } = useTranslation('plugin');const mcpType = useWatch(form, MCP_TYPE);@@ -401,17 +421,28 @@ const MCPManifestForm = ({<BoundDeviceSelect /></Form.Field>)}- <Form.Field label={t('dev.mcp.testConnectionTip')} layout={'horizontal'}>- <Flexbox horizontal align={'center'} gap={8} justify={'flex-end'}>- <Button- loading={isTesting}- type={!!mcpType ? 'primary' : undefined}- onClick={isOAuth ? onAuthorizeOAuth : handleTestConnection}- >- {isOAuth ? t('dev.mcp.auth.oauth.authorize') : t('dev.mcp.testConnection')}- </Button>- </Flexbox>- </Form.Field>+ {isOAuth &&+ oauthNotice &&+ (oauthNotice.type === 'warning' ? (+ <Alert showIcon title={oauthNotice.text} type={'warning'} />+ ) : (+ <Text fontSize={12} type={'secondary'}>+ {oauthNotice.text}+ </Text>+ ))}+ {(!isOAuth || onAuthorizeOAuth) && (+ <Form.Field label={t('dev.mcp.testConnectionTip')} layout={'horizontal'}>+ <Flexbox horizontal align={'center'} gap={8} justify={'flex-end'}>+ <Button+ loading={isTesting}+ type={!!mcpType ? 'primary' : undefined}+ onClick={isOAuth ? onAuthorizeOAuth : handleTestConnection}+ >+ {isOAuth ? t('dev.mcp.auth.oauth.authorize') : t('dev.mcp.testConnection')}+ </Button>+ </Flexbox>+ </Form.Field>+ )}{(connectionError || testState.error) && (<Alertclosablediff --git a/src/features/PluginDevModal/index.tsx b/src/features/PluginDevModal/index.tsxindex 59a70d72a13..c4675b57138 100644--- a/src/features/PluginDevModal/index.tsx+++ b/src/features/PluginDevModal/index.tsx@@ -9,6 +9,12 @@ import { useTranslation } from 'react-i18next';import { openConnectorOAuthPopup } from '@/utils/connectorOAuth';import MCPManifestForm from './MCPManifestForm';+import {+ AUTHORIZE_ALWAYS,+ type DevModalOAuthFields,+ type DevModalOAuthPlan,+ planOAuthSave,+} from './oauthSavePlan';import PluginPreview from './PluginPreview';import { pruneHiddenFields } from './pruneHiddenFields';import { getSaveErrorToast } from './saveErrorToast';@@ -17,11 +23,19 @@ const INITIAL_VALUES = {customParams: { mcp: { auth: { type: 'none' }, type: 'http' } },} as LobeToolCustomPlugin;+export type { DevModalOAuthFields, DevModalOAuthPlan } from './oauthSavePlan';+interface DevModalProps {/** Let a device-run server be bound to one device (connectors only, see MCPManifestForm). */enableDeviceBinding?: boolean;/** Enable the connector-backed OAuth auth type in the MCP form (see MCPManifestForm). */enableOAuth?: boolean;+ /**+ * For the OAuth fields as they stand: whether saving authorizes, and what to+ * tell the user about the connected accounts. Without it every OAuth save+ * authorizes (creating a connector has nothing to keep).+ */+ getOAuthPlan?: (fields: DevModalOAuthFields) => DevModalOAuthPlan;mode?: 'edit' | 'create';onDelete?: () => void;onOpenChange: (open: boolean) => void;@@ -45,6 +59,7 @@ const DevModal = memo<DevModalProps>(onDelete,enableDeviceBinding,enableOAuth,+ getOAuthPlan,}) => {const isEditMode = mode === 'edit';const { t } = useTranslation('plugin');@@ -61,7 +76,11 @@ const DevModal = memo<DevModalProps>(onValueChange?.(values);},});- const authType = useWatch(form, 'customParams.mcp.auth.type');+ const serverUrl = useWatch(form, 'customParams.mcp.url');+ const clientId = useWatch(form, 'customParams.mcp.auth.clientId');+ const clientSecret = useWatch(form, 'customParams.mcp.auth.clientSecret');+ const oauthPlan =+ getOAuthPlan?.({ clientId, clientSecret, url: serverUrl }) ?? AUTHORIZE_ALWAYS;// Seed the form once per modal open, waiting for `value` to arrive (it may// be undefined initially while edit-mode credentials are being fetched).@@ -125,7 +144,10 @@ const DevModal = memo<DevModalProps>(};const handlePrimaryClick = () => {- if (enableOAuth && authType === 'oauth2') return runOAuthFlow();+ // Decided on the values being saved, so the popup opens exactly when the+ // save handler will authorize (it applies the same plan).+ if (planOAuthSave({ enableOAuth, getOAuthPlan, values: form.getValues() }).authorize)+ return runOAuthFlow();form.submit();};@@ -215,7 +237,8 @@ const DevModal = memo<DevModalProps>(enableOAuth={enableOAuth}form={form}isEditMode={isEditMode}- onAuthorizeOAuth={runOAuthFlow}+ oauthNotice={oauthPlan.notice}+ onAuthorizeOAuth={oauthPlan.authorize ? runOAuthFlow : undefined}/></Flexbox><PluginPreview form={form} />diff --git a/src/features/PluginDevModal/oauthSavePlan.test.ts b/src/features/PluginDevModal/oauthSavePlan.test.tsnew file mode 100644index 00000000000..d32115b657e--- /dev/null+++ b/src/features/PluginDevModal/oauthSavePlan.test.ts@@ -0,0 +1,63 @@+import type { LobeToolCustomPlugin } from '@lobechat/types';+import { describe, expect, it, vi } from 'vitest';++import { planOAuthSave } from './oauthSavePlan';++const URL = 'https://mail.example.com/mcp';++const valuesWith = (auth: Record<string, unknown>) =>+ ({+ customParams: { mcp: { auth, type: 'http', url: URL } },+ identifier: 'mail',+ type: 'customPlugin',+ }) as LobeToolCustomPlugin;++/**+ * The save button opens the authorization window only when this says so; the+ * edit form used to open it on every OAuth save.+ */+describe('planOAuthSave', () => {+ it('saves in place when the caller says the edit keeps the accounts', () => {+ const notice = { text: 'keeps accounts', type: 'info' as const };+ const getOAuthPlan = vi.fn(() => ({ authorize: false, notice }));++ expect(+ planOAuthSave({+ enableOAuth: true,+ getOAuthPlan,+ values: valuesWith({ clientId: 'id', clientSecret: 'secret', type: 'oauth2' }),+ }),+ ).toEqual({ authorize: false, notice });+ // The caller decides from exactly the fields being saved.+ expect(getOAuthPlan).toHaveBeenCalledWith({ clientId: 'id', clientSecret: 'secret', url: URL });+ });++ it('authorizes when the caller says so', () => {+ expect(+ planOAuthSave({+ enableOAuth: true,+ getOAuthPlan: () => ({ authorize: true }),+ values: valuesWith({ type: 'oauth2' }),+ }).authorize,+ ).toBe(true);+ });++ it('authorizes every OAuth save without a caller plan (creating a connector)', () => {+ expect(planOAuthSave({ enableOAuth: true, values: valuesWith({ type: 'oauth2' }) })).toEqual({+ authorize: true,+ });+ });++ it('never authorizes another auth type, or a form without connector OAuth', () => {+ const getOAuthPlan = vi.fn(() => ({ authorize: true }));++ expect(+ planOAuthSave({ enableOAuth: true, getOAuthPlan, values: valuesWith({ type: 'bearer' }) })+ .authorize,+ ).toBe(false);+ expect(planOAuthSave({ getOAuthPlan, values: valuesWith({ type: 'oauth2' }) }).authorize).toBe(+ false,+ );+ expect(getOAuthPlan).not.toHaveBeenCalled();+ });+});diff --git a/src/features/PluginDevModal/oauthSavePlan.ts b/src/features/PluginDevModal/oauthSavePlan.tsnew file mode 100644index 00000000000..03b86d5168b--- /dev/null+++ b/src/features/PluginDevModal/oauthSavePlan.ts@@ -0,0 +1,47 @@+import { type LobeToolCustomPlugin } from '@lobechat/types';++import { type OAuthNotice } from './MCPManifestForm';++/** The OAuth fields that decide whether a save has to authorize. */+export interface DevModalOAuthFields {+ clientId?: string;+ clientSecret?: string;+ url?: string;+}++export interface DevModalOAuthPlan {+ /** Saving opens the authorization window; otherwise it saves in place. */+ authorize: boolean;+ notice?: OAuthNotice;+}++/** Without a caller-supplied plan every OAuth save authorizes (creating has nothing to keep). */+export const AUTHORIZE_ALWAYS: DevModalOAuthPlan = { authorize: true };++const readMcp = (values: LobeToolCustomPlugin) =>+ values.customParams?.mcp as+ | { auth?: { clientId?: string; clientSecret?: string; type?: string }; url?: string }+ | undefined;++export const readOAuthFields = (values: LobeToolCustomPlugin): DevModalOAuthFields => {+ const mcp = readMcp(values);+ return { clientId: mcp?.auth?.clientId, clientSecret: mcp?.auth?.clientSecret, url: mcp?.url };+};++/**+ * What the save button does with the values being saved: authorize (open the+ * window inside the click, before validation or network IO) or save in place.+ * Only the connector-backed OAuth auth type can authorize.+ */+export const planOAuthSave = ({+ enableOAuth,+ getOAuthPlan,+ values,+}: {+ enableOAuth?: boolean;+ getOAuthPlan?: (fields: DevModalOAuthFields) => DevModalOAuthPlan;+ values: LobeToolCustomPlugin;+}): DevModalOAuthPlan => {+ if (!enableOAuth || readMcp(values)?.auth?.type !== 'oauth2') return { authorize: false };+ return getOAuthPlan?.(readOAuthFields(values)) ?? AUTHORIZE_ALWAYS;+};diff --git a/src/features/Settings/skill/features/ConnectorRowFeedback.tsx b/src/features/Settings/skill/features/ConnectorRowFeedback.tsxindex 247f98bc683..71abf1dd8dd 100644--- a/src/features/Settings/skill/features/ConnectorRowFeedback.tsx+++ b/src/features/Settings/skill/features/ConnectorRowFeedback.tsx@@ -6,7 +6,10 @@ import { SquareArrowOutUpRight } from 'lucide-react';import { memo, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';-import ConnectorActionErrorText from '@/features/Connectors/ConnectorActionErrorText';+import ConnectorActionErrorText, {+ InlineErrorText,+} from '@/features/Connectors/ConnectorActionErrorText';+import { type ConnectorLinkSummary } from '@/store/tool/slices/connector';import { type ConnectorActionError } from '@/utils/connectorActionError';const styles = stylex.create({@@ -106,3 +109,20 @@ export const DisabledConnect = memo<DisabledConnectProps>(({ size = 'small' }) =});DisabledConnect.displayName = 'DisabledConnect';++/** OAuth accounts of a connector whose authorization expired or was revoked. */+export const countAccountsNeedingReauth = (links?: ConnectorLinkSummary[]): number =>+ links?.filter((link) => link.status === 'error').length ?? 0;++/**+ * Row line for a connector with broken accounts: tool calls through them fail+ * until they are re-authorized, which the user would otherwise only learn from+ * a failed chat. Healthy accounts add nothing to the row.+ */+export const AccountsNeedReauth = memo<{ count: number }>(({ count }) => {+ const { t } = useTranslation('tool');++ return <InlineErrorText>{t('connector.account.needsReauth', { count })}</InlineErrorText>;+});++AccountsNeedReauth.displayName = 'AccountsNeedReauth';diff --git a/src/features/Settings/skill/features/McpSkillItem.tsx b/src/features/Settings/skill/features/McpSkillItem.tsxindex 4181058b563..0e4ab6f7de2 100644--- a/src/features/Settings/skill/features/McpSkillItem.tsx+++ b/src/features/Settings/skill/features/McpSkillItem.tsx@@ -3,7 +3,7 @@import { Avatar, createModal, Flexbox, Icon } from '@lobehub/ui';import { McpIcon } from '@lobehub/ui/icons';import * as stylex from '@stylexjs/stylex';-import { memo, Suspense } from 'react';+import { memo, type ReactNode, Suspense } from 'react';import { useTranslation } from 'react-i18next';import MCPTag from '@/components/Plugins/MCPTag';@@ -22,6 +22,8 @@ import { styles } from './style';interface McpSkillItemProps {author?: string;avatar?: string;+ /** Feedback line under the title (list row only). */+ description?: ReactNode;identifier: string;isSelected?: boolean;onSelect?: () => void;@@ -31,7 +33,7 @@ interface McpSkillItemProps {}const McpSkillItem = memo<McpSkillItemProps>(- ({ identifier, title, avatar, type, runtimeType, author, isSelected, onSelect }) => {+ ({ identifier, title, avatar, description, type, runtimeType, author, isSelected, onSelect }) => {const { t } = useTranslation('plugin');const iconSize = useSkillListVariant() === 'page' ? 20 : 18;const isMCP = runtimeType === 'mcp';@@ -68,6 +70,7 @@ const McpSkillItem = memo<McpSkillItemProps>(return (<SkillListRowactive={isSelected}+ description={description}title={title}icon={() =>avatar && avatar !== 'MCP_AVATAR' ? (diff --git a/src/features/Settings/skill/features/SkillList.tsx b/src/features/Settings/skill/features/SkillList.tsxindex ca85f3f405e..47c2d3b5143 100644--- a/src/features/Settings/skill/features/SkillList.tsx+++ b/src/features/Settings/skill/features/SkillList.tsx@@ -38,6 +38,7 @@ import AgentConnectorItem from './AgentConnectorItem';import AgentSkillItem from './AgentSkillItem';import BuiltinSkillItem from './BuiltinSkillItem';import ComposioSkillItem from './ComposioSkillItem';+import { AccountsNeedReauth, countAccountsNeedingReauth } from './ConnectorRowFeedback';import LobehubSkillItem from './LobehubSkillItem';import McpSkillItem from './McpSkillItem';import type { ToolDetailType } from './SkillDetail';@@ -401,17 +402,23 @@ const SkillList = memo<SkillListProps>(// Custom connectors from the connector store (user-added OAuth MCP servers)const renderCustomConnectors = () =>- customConnectors.map((c) => (- <McpSkillItem- identifier={c.identifier}- isSelected={selectedIdentifier === c.identifier}- key={c.id}- runtimeType="mcp"- title={c.name || c.identifier}- type={'customPlugin' as LobeToolType}- onSelect={onSelect ? () => onSelect(c.identifier, 'mcp-connector') : undefined}- />- ));+ customConnectors.map((c) => {+ const brokenAccounts = countAccountsNeedingReauth(c.links);+ return (+ <McpSkillItem+ identifier={c.identifier}+ isSelected={selectedIdentifier === c.identifier}+ key={c.id}+ runtimeType="mcp"+ title={c.name || c.identifier}+ type={'customPlugin' as LobeToolType}+ description={+ brokenAccounts > 0 ? <AccountsNeedReauth count={brokenAccounts} /> : undefined+ }+ onSelect={onSelect ? () => onSelect(c.identifier, 'mcp-connector') : undefined}+ />+ );+ });// Split integrations into builtin tools vs builtin skillsconst builtinToolItems = integrations.filter((i) => i.type === 'builtin');diff --git a/src/helpers/toolEngineering/buildClientConnectorManifests.ts b/src/helpers/toolEngineering/buildClientConnectorManifests.tsindex 8d1176e6e0f..e5e11cc55de 100644--- a/src/helpers/toolEngineering/buildClientConnectorManifests.ts+++ b/src/helpers/toolEngineering/buildClientConnectorManifests.ts@@ -19,6 +19,7 @@ export const buildClientConnectorManifests = (connectors: ConnectorWithTools[]):identifier: connector.identifier,isEnabled: connector.isEnabled,name: connector.name,+ links: connector.links,tools: connector.tools ?? [],},!!getServerConfigStoreState() &&diff --git a/src/libs/mcp/__tests__/fixtures/oauthMcpServer.ts b/src/libs/mcp/__tests__/fixtures/oauthMcpServer.tsnew file mode 100644index 00000000000..3ef770fae37--- /dev/null+++ b/src/libs/mcp/__tests__/fixtures/oauthMcpServer.ts@@ -0,0 +1,189 @@+import { createServer } from 'node:http';++export type OAuthMcpVariant = 'idtoken' | 'userinfo' | 'none';++/** A real HTTP OAuth/MCP fixture, also usable by local product acceptance. */+export const startOAuthMcpServer = async (+ variant: OAuthMcpVariant = 'idtoken',+ port = 0,+ options: { collidingTool?: boolean } = {},+) => {+ const requests: {+ authorization: string | null;+ arguments: Record<string, unknown>;+ tool: string;+ }[] = [];+ const refreshes: string[] = [];+ let base = '';+ let sequence = 0;+ const server = createServer(async (req, res) => {+ try {+ const url = new URL(req.url!, base);+ const json = (value: unknown, status = 200, headers: Record<string, string> = {}) => {+ res.writeHead(status, { 'Content-Type': 'application/json', ...headers });+ res.end(JSON.stringify(value));+ };+ let raw = '';+ for await (const chunk of req) raw += chunk.toString();+ const metadata = {+ issuer: base,+ authorization_endpoint: `${base}/authorize`,+ token_endpoint: `${base}/token`,+ registration_endpoint: `${base}/register`,+ response_types_supported: ['code'],+ grant_types_supported: ['authorization_code', 'refresh_token'],+ code_challenge_methods_supported: ['S256'],+ token_endpoint_auth_methods_supported: ['none'],+ scopes_supported: ['tools', 'offline_access', 'openid', 'profile', 'email'],+ prompt_values_supported: ['consent', 'select_account'],+ ...(variant === 'userinfo' ? { userinfo_endpoint: `${base}/userinfo` } : {}),+ };+ if (url.pathname === '/__requests') return json({ requests, refreshes });+ if (url.pathname.startsWith('/.well-known/oauth-protected-resource'))+ return json({+ resource: `${base}/mcp`,+ authorization_servers: [base],+ scopes_supported: ['tools'],+ });+ if (+ url.pathname === '/.well-known/oauth-authorization-server' ||+ url.pathname === '/.well-known/openid-configuration'+ )+ return json(metadata);+ if (url.pathname === '/register')+ return json(+ { ...JSON.parse(raw), client_id: 'fixture-client', token_endpoint_auth_method: 'none' },+ 201,+ );+ if (url.pathname === '/authorize') {+ const account = url.searchParams.get('account');+ if (!account) {+ res.writeHead(200, { 'Content-Type': 'text/html' });+ const choice = (name: string) => {+ const next = new URL(url);+ next.searchParams.set('account', name);+ return `<a href="${next.pathname}${next.search.replaceAll('&', '&')}">${name}</a>`;+ };+ res.end(`<h1>Choose account</h1>${choice('alice')} ${choice('bob')}`);+ return;+ }+ const callback = new URL(url.searchParams.get('redirect_uri')!);+ callback.searchParams.set('code', account);+ callback.searchParams.set('state', url.searchParams.get('state')!);+ callback.searchParams.set('iss', base);+ res.writeHead(302, { Location: callback.href }).end();+ return;+ }+ if (url.pathname === '/token') {+ const form = new URLSearchParams(raw);+ const refresh = form.get('refresh_token');+ if (refresh) refreshes.push(refresh);+ const account = (refresh ?? form.get('code') ?? 'alice')+ .replace(/^refresh-/, '')+ .split('-')[0];+ const payload = Buffer.from(+ JSON.stringify({+ iss: base,+ sub: account,+ email: `${account}@example.com`,+ name: account,+ }),+ ).toString('base64url');+ return json({+ access_token: `tok-${account}-${++sequence}`,+ refresh_token: `refresh-${account}-${sequence}`,+ token_type: 'Bearer',+ expires_in: 120,+ ...(variant === 'idtoken' ? { id_token: `header.${payload}.signature` } : {}),+ });+ }+ if (url.pathname === '/userinfo') {+ const account = /tok-(alice|bob)-/.exec(req.headers.authorization ?? '')?.[1];+ return account+ ? json({ sub: account, email: `${account}@example.com`, preferred_username: account })+ : json({ error: 'unauthorized' }, 401);+ }+ if (url.pathname !== '/mcp') return json({ error: 'not_found' }, 404);+ if (!req.headers.authorization?.startsWith('Bearer tok-'))+ return json({ error: 'unauthorized' }, 401, {+ 'WWW-Authenticate': `Bearer resource_metadata="${base}/.well-known/oauth-protected-resource/mcp", scope="tools"`,+ });+ if (req.method === 'GET') {+ res.writeHead(405).end();+ return;+ }+ const rpc = JSON.parse(raw);+ if (rpc.id === undefined) {+ res.writeHead(202).end();+ return;+ }+ const reply = (result: unknown) => json({ jsonrpc: '2.0', id: rpc.id, result });+ if (rpc.method === 'initialize')+ return reply({+ protocolVersion: rpc.params.protocolVersion,+ capabilities: { tools: {} },+ serverInfo: { name: 'oauth-accounts-fixture', version: '1.0.0' },+ });+ if (rpc.method === 'tools/list')+ return reply({+ tools: [+ {+ name: 'whoami',+ description: 'Return the selected account',+ inputSchema: { type: 'object', properties: {} },+ },+ {+ name: 'echo_args',+ description: 'Return received arguments',+ inputSchema: { type: 'object', properties: { x: { type: 'number' } } },+ },+ ...(options.collidingTool+ ? [+ {+ name: 'native_link_id',+ description: 'Echo a business link_id',+ inputSchema: { type: 'object', properties: { link_id: { type: 'string' } } },+ },+ ]+ : []),+ ],+ });+ if (rpc.method === 'tools/call') {+ requests.push({+ authorization: req.headers.authorization ?? null,+ arguments: rpc.params.arguments ?? {},+ tool: rpc.params.name,+ });+ return reply({+ content: [+ {+ type: 'text',+ text: JSON.stringify({+ account: /tok-(alice|bob)-/.exec(req.headers.authorization)?.[1],+ arguments: rpc.params.arguments ?? {},+ }),+ },+ ],+ });+ }+ json({ jsonrpc: '2.0', id: rpc.id, error: { code: -32601, message: 'Method not found' } });+ } catch (error) {+ res.writeHead(500).end(error instanceof Error ? error.message : 'Fixture error');+ }+ });+ await new Promise<void>((resolve) => server.listen(port, '127.0.0.1', resolve));+ const address = server.address();+ if (!address || typeof address === 'string') throw new Error('Missing OAuth fixture address');+ base = `http://127.0.0.1:${address.port}`;+ return {+ base,+ requests,+ refreshes,+ close: async () => {+ server.closeAllConnections();+ await new Promise<void>((resolve, reject) =>+ server.close((error) => (error ? reject(error) : resolve())),+ );+ },+ };+};diff --git a/src/libs/mcp/buildConnectorManifests.ts b/src/libs/mcp/buildConnectorManifests.tsindex f0c539b3452..b85297a0a96 100644--- a/src/libs/mcp/buildConnectorManifests.ts+++ b/src/libs/mcp/buildConnectorManifests.ts@@ -1,4 +1,4 @@-import { buildConnectorManifest } from '@lobechat/mecha';+import { buildConnectorManifest, resolveConnectorLinkParam } from '@lobechat/mecha';import type { ToolManifest } from '@lobechat/types';import { connectorConnectVia, connectorDeviceBinding } from '@lobechat/utils/mcpEndpoint';@@ -38,6 +38,7 @@ export function buildConnectorManifests(identifier: connector.identifier,isEnabled: connector.isEnabled,name: connector.name,+ links: connector.links,tools: toolsByConnector.get(connector.id) ?? [],},mcpApps,@@ -47,7 +48,19 @@ export function buildConnectorManifests(manifests.push({...(manifest as ToolManifest),// @ts-ignore — mcpParams is a runtime-only field not in the public type- mcpParams: buildMcpParams(connector),+ mcpParams: buildMcpParams(+ (connector.links?.length ?? 0) > 1 ? { ...connector, credentials: null } : connector,+ ),+ ...((connector.links?.length ?? 0) > 1+ ? {+ connectorLinks: {+ connectorId: connector.id,+ param: resolveConnectorLinkParam(+ (toolsByConnector.get(connector.id) ?? []).map((tool) => tool.inputSchema),+ ),+ },+ }+ : {}),});}diff --git a/src/libs/mcp/localConnector.test.ts b/src/libs/mcp/localConnector.test.tsnew file mode 100644index 00000000000..36106be5135--- /dev/null+++ b/src/libs/mcp/localConnector.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from 'vitest';++import { takeLocalConnectorAccount } from './localConnector';++const tools = [{ inputSchema: { properties: { x: {} } } }];+const holding = (count: number) => ({+ links: Array.from({ length: count }, (_, i) => ({ id: `lnk_${i}` })),+});++describe('takeLocalConnectorAccount', () => {+ it('takes the selector out of the arguments the MCP server receives', () => {+ expect(takeLocalConnectorAccount(holding(2), tools, '{"link_id":"lnk_1","x":1}')).toEqual({+ args: '{"x":1}',+ linkId: 'lnk_1',+ });+ });++ it('requires a selection while several accounts remain', () => {+ expect(() => takeLocalConnectorAccount(holding(2), tools, '{"x":1}')).toThrow(+ 'link_id is required',+ );+ });++ // A call made while two accounts existed, run after one was removed+ it('keeps the selection with one account left, so a removed one is not swapped', () => {+ expect(takeLocalConnectorAccount(holding(1), tools, '{"link_id":"lnk_gone","x":1}')).toEqual({+ args: '{"x":1}',+ linkId: 'lnk_gone',+ });+ expect(takeLocalConnectorAccount(holding(1), tools, '{"x":1}')).toEqual({+ args: '{"x":1}',+ linkId: undefined,+ });+ });++ it('leaves a connector without accounts untouched', () => {+ expect(takeLocalConnectorAccount(holding(0), tools, '{"link_id":"x"}')).toEqual({+ args: '{"link_id":"x"}',+ });+ });++ it('refuses a view selection that contradicts the arguments', () => {+ expect(() =>+ takeLocalConnectorAccount(holding(2), tools, '{"link_id":"lnk_0"}', 'lnk_1'),+ ).toThrow('Conflicting account selections');+ });+});diff --git a/src/libs/mcp/localConnector.ts b/src/libs/mcp/localConnector.tsindex 7eebadec17d..804fa666676 100644--- a/src/libs/mcp/localConnector.ts+++ b/src/libs/mcp/localConnector.ts@@ -1,3 +1,4 @@+import { resolveConnectorLinkParam, splitConnectorLinkArg } from '@lobechat/mecha';import { toRecord } from '@lobechat/utils/object';/** Reuse the same credential/header mapping for local HTTP calls and resource reads. */@@ -54,3 +55,29 @@ export const resolveLocalConnectorHttpParams = async (? { ...http, auth: { accessToken: oauth.accessToken, type: 'oauth2' as const } }: http;};++/**+ * The account a call this desktop runs itself goes out as, for a connector+ * with accounts (`links`): the model's selector, or the one a view's call+ * carries, taken out of the arguments the MCP server receives. As its+ * server-run calls do, a connector holding several fails without a selection,+ * and a selection is kept with one account left: a call made for an account+ * removed since must fail rather than go out as the one that remains.+ */+export const takeLocalConnectorAccount = (+ connector: { links?: readonly unknown[] | null },+ tools: readonly { inputSchema?: unknown }[],+ args: string | undefined,+ selected?: string,+): { args: string; linkId?: string } => {+ const accounts = connector.links?.length ?? 0;+ if (!accounts) return { args: args || '{}', linkId: selected };+ const param = resolveConnectorLinkParam(tools.map((tool) => tool.inputSchema));+ const split = splitConnectorLinkArg(args || '{}', param);+ if (selected && split.linkId && selected !== split.linkId)+ throw new Error('Conflicting account selections');+ const linkId = selected ?? split.linkId;+ if (!linkId && accounts > 1)+ throw new Error(`${param} is required: select one of the accounts listed for this tool`);+ return { args: split.argsStr, linkId };+};diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex dcd9588ac7c..ab6655b1204 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -432,10 +432,27 @@ export const mcpAppKeys = {uri: string,{agentId,+ linkId,onThisDevice = false,server,- }: { agentId?: string; onThisDevice?: boolean; server?: string },- ) => ['mcpApp:resource', identifier, uri, agentId ?? null, onThisDevice, server ?? null],+ toolArguments,+ }: {+ agentId?: string;+ linkId?: string;+ onThisDevice?: boolean;+ server?: string;+ toolArguments?: string;+ },+ ) => [+ 'mcpApp:resource',+ identifier,+ uri,+ agentId ?? null,+ onThisDevice,+ server ?? null,+ toolArguments ?? null,+ linkId ?? null,+ ],),};diff --git a/src/services/mcp.deviceRoute.test.ts b/src/services/mcp.deviceRoute.test.tsindex b6109e6ea5c..205692f4a1c 100644--- a/src/services/mcp.deviceRoute.test.ts+++ b/src/services/mcp.deviceRoute.test.ts@@ -286,6 +286,57 @@ describe('invokeMcpToolCall routing for HTTP servers', () => {});});+ // The selector names the account whose token goes out; the server never sees it+ it("sends the selected account's token and strips the selector for a connector holding several", async () => {+ const { lambdaClient } = await import('@/libs/trpc/client');+ environment.isDesktop = true;+ mockGetToolStoreState.mockReturnValue({+ connectors: [+ {+ ...connector,+ links: [+ { id: 'lnk_a', name: 'Alice' },+ { id: 'lnk_b', name: 'Bob' },+ ],+ metadata: { connectVia: 'device' },+ },+ ],+ });+ vi.mocked(lambdaClient.connector.getForEdit.query).mockResolvedValue({+ ...connector,+ credentials: null,+ metadata: { connectVia: 'device' },+ oidcConfig: { clientId: 'cid', issuer: 'https://auth.example.com' },+ tools: [+ { inputSchema: { properties: { dir: {} } }, permission: 'auto', toolName: 'list_files' },+ ],+ } as never);+ vi.mocked(lambdaClient.connector.getLocalCallToken.mutate).mockResolvedValue({+ accessToken: 'bob-access',+ type: 'oauth2',+ } as never);++ await mcpService.invokeMcpToolCall(+ { ...payload, arguments: '{"dir":"/","link_id":"lnk_b"}' } as ChatToolPayload,+ {},+ );++ expect(lambdaClient.connector.getLocalCallToken.mutate).toHaveBeenCalledWith({+ id: 'nas-id',+ linkId: 'lnk_b',+ });+ const sent = superjson.deserialize(mockElectronIpc.mcp.callTool.mock.calls[0][0]);+ expect(sent).toMatchObject({+ args: { dir: '/' },+ http: { auth: { accessToken: 'bob-access', type: 'oauth2' } },+ });+ expect((sent as { args: Record<string, unknown> }).args).not.toHaveProperty('link_id');++ await expect(mcpService.invokeMcpToolCall(payload as ChatToolPayload, {})).rejects.toThrow(+ 'link_id is required',+ );+ });+it('leaves one set to connect through the device to the server on the web', async () => {const { lambdaClient } = await import('@/libs/trpc/client');useConnector({ connectVia: 'device' });diff --git a/src/services/mcp.mcpApp.test.ts b/src/services/mcp.mcpApp.test.tsindex 25f36b7efbd..1e8a56e2503 100644--- a/src/services/mcp.mcpApp.test.ts+++ b/src/services/mcp.mcpApp.test.ts@@ -445,6 +445,22 @@ describe('mcpService MCP App calls for agents', () => {connectorCall.mockResolvedValue({ content: 'ok', success: true });});+ it('resolves the originating account after loading cold agent connector schemas', async () => {+ toolState.ensureConfirmedConnectors.mockImplementationOnce(async () => {+ connectors.set('agt_1:cold', {+ isEnabled: true,+ mcpServerUrl: 'https://mcp.example.com/mcp',+ tools: [{ inputSchema: { properties: { link_id: {} } } }],+ });+ });+ await mcpService.readMcpAppResource('cold', 'ui://app', {+ agentId: 'agt_1',+ server: REMOTE,+ toolArguments: '{"connector_link_id":"lnk_bob","link_id":"business"}',+ });+ expect(connectorRead).toHaveBeenCalledWith(expect.objectContaining({ linkId: 'lnk_bob' }));+ });+it("reads an agent's connector view on the server, which checks the result's server", async () => {connectors.set('agt_1:agent-app', {isEnabled: true,diff --git a/src/services/mcp.ts b/src/services/mcp.tsindex 8f92fc0294a..0c84c770333 100644--- a/src/services/mcp.ts+++ b/src/services/mcp.ts@@ -10,6 +10,7 @@ import {isSyncedMcpToolVisibleTo,type McpServerAddress,} from '@lobechat/const/mcpApp';+import { resolveConnectorLinkParam } from '@lobechat/mecha';import {type ChatToolPayload,type CheckMcpInstallResult,@@ -31,7 +32,10 @@ import { omit } from 'es-toolkit/compat';import { runsOnAnotherDevice } from '@/helpers/mcpDeviceBinding';import { type MCPToolCallResult } from '@/libs/mcp';-import { resolveLocalConnectorHttpParams } from '@/libs/mcp/localConnector';+import {+ resolveLocalConnectorHttpParams,+ takeLocalConnectorAccount,+} from '@/libs/mcp/localConnector';import { renderMcpArgs, renderMcpUrlTemplate } from '@/libs/mcp/urlTemplate';import { getMCPConnectionErrorType } from '@/libs/mcp/utils';import { toolsClient } from '@/libs/trpc/client';@@ -233,6 +237,7 @@ class MCPService {agentId,fromMcpApp,fromEntrypoint,+ linkId,onThisDevice,server,signal,@@ -251,6 +256,7 @@ class MCPService {*/fromMcpApp?: boolean;fromEntrypoint?: boolean;+ linkId?: string;/*** With `fromMcpApp`: the view's result came from this desktop's own MCP* process (it carries this device's id), so its calls run there too;@@ -344,15 +350,16 @@ class MCPService {throw new Error(`Tool '${apiName}' can only be called from its interactive view`);}if (detail.mcpConnectionType !== 'stdio') {+ const account = takeLocalConnectorAccount(connector, detail.tools, args, linkId);const http = await resolveLocalConnectorHttpParams(detail, (id) =>- lambdaClient.connector.getLocalCallToken.mutate({ id }),+ lambdaClient.connector.getLocalCallToken.mutate({ id, linkId: account.linkId }),);if (fromMcpApp && !(await isViewServer(server, { ...http, type: 'http' })))throw new Error(VIEW_SERVER_MOVED);throwIfAborted(signal);const result = await ensureElectronIpc().mcp.callTool(serializeMcpIpcPayload({- args: safeParseJSON(args) ?? {},+ args: safeParseJSON(account.args) ?? {},http,mcpApps,...(fromMcpApp && { fromApp: true }),@@ -427,6 +434,7 @@ class MCPService {return (await lambdaClient.connector.callTool.mutate({agentId,+ linkId,args,// The server checks the view's server against the connector it resolves...(fromMcpApp && { fromApp: true, server }),@@ -609,10 +617,14 @@ class MCPService {uri: string,{agentId,+ linkId,+ toolArguments,onThisDevice = false,server,}: {agentId?: string;+ linkId?: string;+ toolArguments?: string;/*** The result came from this desktop's own MCP process (it carries this* device's id): read the view there, over IPC. Otherwise it came from the@@ -643,6 +655,16 @@ class MCPService {const { connectorSelectors } = await import('@/store/tool/slices/connector/selectors');const resolved = connectorSelectors.connectorByIdentifierForAgent(identifier, agentId)(s);+ // Resolve only after the agent's confirmed list loads: a cold view may+ // otherwise mistake a tool's business link_id for the account selector.+ if (!linkId && toolArguments && resolved) {+ const param = resolveConnectorLinkParam(+ resolved.tools?.map((tool) => tool.inputSchema) ?? [],+ );+ const value = toRecord(safeParseJSON(toolArguments))?.[param];+ if (typeof value === 'string') linkId = value;+ }+// Same test as `invokeMcpToolCall`: only an enabled connector with its own// endpoint and a finished install serves the view. Any other (e.g. the// endpoint-less row a plugin's tools are synced to) leaves it to the plugin.@@ -712,7 +734,7 @@ class MCPService {const detail = await lambdaClient.connector.getForEdit.query({ id: connector.id });if (!detail.isEnabled) return;const http = await resolveLocalConnectorHttpParams(detail, (id) =>- lambdaClient.connector.getLocalCallToken.mutate({ id }),+ lambdaClient.connector.getLocalCallToken.mutate({ id, linkId }),);if (!(await reaches({ ...http, type: 'http' }))) return;return deserializeMcpIpcPayload(@@ -724,6 +746,7 @@ class MCPService {return (await lambdaClient.connector.readUiResource.query({agentId,identifier,+ linkId,server,uri,})) as ReadResourceResult;diff --git a/src/store/tool/slices/connector/action.accounts.test.ts b/src/store/tool/slices/connector/action.accounts.test.tsnew file mode 100644index 00000000000..dcdedf4f532--- /dev/null+++ b/src/store/tool/slices/connector/action.accounts.test.ts@@ -0,0 +1,232 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { cacheScope } from '@/libs/replica';+import { lambdaClient } from '@/libs/trpc/client';+import { ConnectorOAuthError, waitForConnectorOAuth } from '@/utils/connectorOAuth';++import { useToolStore } from '../../store';+import { initialConnectorState } from './initialState';+import { isConnectorLinkNameConflict, supportsMultipleConnectorAccounts } from './types';++const mocks = vi.hoisted(() => ({ wait: vi.fn() }));+vi.mock('@/utils/connectorOAuth', async (original) => ({+ ...(await original<object>()),+ waitForConnectorOAuth: mocks.wait,+}));+vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: {+ connector: {+ list: { query: vi.fn() },+ listAgentBound: { query: vi.fn() },+ listByAgent: { query: vi.fn() },+ oauthResult: { query: vi.fn() },+ startOAuth: {+ mutate: vi.fn().mockResolvedValue({ authorizationUrl: 'https://provider/authorize' }),+ },+ renameLink: { mutate: vi.fn() },+ deleteLink: { mutate: vi.fn() },+ },+ },+}));+const connector = (ids: string[]) =>+ ({ id: 'c1', identifier: 'test', links: ids.map((id) => ({ id, name: id })), tools: [] }) as any;+beforeEach(() => {+ vi.spyOn(cacheScope, 'get').mockReturnValue('accounts-test:personal');+ useToolStore.setState({ ...initialConnectorState });+ vi.mocked(lambdaClient.connector.list.query).mockResolvedValue([connector(['old'])]);+ mocks.wait.mockResolvedValue(undefined);+});+afterEach(() => {+ vi.restoreAllMocks();+ vi.clearAllMocks();+});+describe('connector account store actions', () => {+ it('refetches account summaries after add, detects deduplication and requests a fresh desktop session', async () => {+ await useToolStore.getState().fetchConnectors();+ vi.mocked(lambdaClient.connector.list.query).mockResolvedValue([connector(['old', 'new'])]);+ const popup = { close: vi.fn() } as unknown as Window;+ expect(await useToolStore.getState().connectConnectorAccount('c1', { popup })).toEqual({+ outcome: 'created',+ linkId: 'new',+ });+ expect(waitForConnectorOAuth).toHaveBeenLastCalledWith(+ popup,+ 'c1',+ 'https://provider/authorize',+ undefined,+ true,+ );+ expect(popup.close).toHaveBeenCalled();+ expect(await useToolStore.getState().connectConnectorAccount('c1')).toMatchObject({+ outcome: 'matchedExisting',+ });+ expect(useToolStore.getState().connectors[0].links).toHaveLength(2);+ });+ it('reauthorizes a specific account, refreshes after rename/remove and preserves conflict errors', async () => {+ await useToolStore.getState().fetchConnectors();+ expect(await useToolStore.getState().reauthorizeConnectorAccount('c1', 'old')).toMatchObject({+ outcome: 'reauthorized',+ linkId: 'old',+ });+ expect(lambdaClient.connector.startOAuth.mutate).toHaveBeenLastCalledWith(+ {+ id: 'c1',+ link: { mode: 'reauthorize', linkId: 'old' },+ },+ { signal: undefined },+ );+ const error = { data: { code: 'CONFLICT' } };+ vi.mocked(lambdaClient.connector.renameLink.mutate).mockRejectedValueOnce(error);+ await expect(+ useToolStore.getState().renameConnectorAccount('c1', 'old', 'Duplicate'),+ ).rejects.toBe(error);+ expect(isConnectorLinkNameConflict(error)).toBe(true);+ vi.mocked(lambdaClient.connector.list.query).mockResolvedValue([connector([])]);+ await useToolStore.getState().removeConnectorAccount('c1', 'old');+ expect(useToolStore.getState().connectors[0].links).toEqual([]);+ });+ it('keeps user dismissal reason and closes the popup', async () => {+ const popup = { close: vi.fn() } as unknown as Window;+ mocks.wait.mockRejectedValueOnce(new ConnectorOAuthError('dismissed'));+ await expect(+ useToolStore.getState().connectConnectorAccount('c1', { popup }),+ ).rejects.toMatchObject({ reason: 'dismissed' });+ expect(popup.close).toHaveBeenCalled();+ });+ it("takes the callback's own report without needing the server's record", async () => {+ vi.mocked(lambdaClient.connector.startOAuth.mutate).mockResolvedValueOnce({+ authorizationUrl: 'https://provider/authorize',+ flowId: 'flow-1',+ } as never);+ mocks.wait.mockResolvedValueOnce({ linkId: 'old', outcome: 'matchedExisting' });++ expect(await useToolStore.getState().connectConnectorAccount('c1')).toEqual({+ linkId: 'old',+ outcome: 'matchedExisting',+ });+ expect(lambdaClient.connector.oauthResult.query).not.toHaveBeenCalled();+ });++ // The native window reports success alone; its record may not have been written+ it("falls back to the lists when a successful flow's record is missing", async () => {+ await useToolStore.getState().fetchConnectors();+ vi.mocked(lambdaClient.connector.startOAuth.mutate).mockResolvedValueOnce({+ authorizationUrl: 'https://provider/authorize',+ flowId: 'flow-1',+ } as never);+ vi.mocked(lambdaClient.connector.list.query).mockResolvedValue([connector(['old', 'new'])]);+ vi.mocked(lambdaClient.connector.oauthResult.query).mockRejectedValueOnce({+ data: { code: 'NOT_FOUND' },+ });++ expect(await useToolStore.getState().connectConnectorAccount('c1')).toEqual({+ linkId: 'new',+ outcome: 'created',+ });+ });++ // Providers whose COOP policy severs `window.opener` lose the callback's message+ describe('a window that never reports back', () => {+ const startWithFlow = () =>+ vi.mocked(lambdaClient.connector.startOAuth.mutate).mockResolvedValueOnce({+ authorizationUrl: 'https://provider/authorize',+ flowId: 'flow-1',+ } as never);++ it.each(['dismissed', 'timeout'] as const)(+ 'takes the account the callback stored when the window is %s',+ async (reason) => {+ await useToolStore.getState().fetchConnectors();+ startWithFlow();+ mocks.wait.mockRejectedValueOnce(new ConnectorOAuthError(reason));+ vi.mocked(lambdaClient.connector.list.query).mockResolvedValue([connector(['old', 'new'])]);+ vi.mocked(lambdaClient.connector.oauthResult.query).mockResolvedValueOnce({+ linkId: 'new',+ outcome: 'created',+ });++ expect(await useToolStore.getState().connectConnectorAccount('c1')).toEqual({+ linkId: 'new',+ outcome: 'created',+ });+ expect(lambdaClient.connector.oauthResult.query).toHaveBeenCalledWith({ flowId: 'flow-1' });+ expect(useToolStore.getState().connectors[0].links).toHaveLength(2);+ },+ );++ it('keeps the dismissal when the callback recorded nothing', async () => {+ startWithFlow();+ mocks.wait.mockRejectedValueOnce(new ConnectorOAuthError('dismissed'));+ vi.mocked(lambdaClient.connector.oauthResult.query).mockRejectedValueOnce({+ data: { code: 'NOT_FOUND' },+ });++ await expect(useToolStore.getState().connectConnectorAccount('c1')).rejects.toMatchObject({+ reason: 'dismissed',+ });+ });++ it('never recovers a flow the user cancelled', async () => {+ const controller = new AbortController();+ startWithFlow();+ mocks.wait.mockImplementationOnce(async () => {+ controller.abort();+ throw new ConnectorOAuthError('dismissed');+ });++ await expect(+ useToolStore.getState().connectConnectorAccount('c1', { signal: controller.signal }),+ ).rejects.toMatchObject({ reason: 'dismissed' });+ expect(lambdaClient.connector.oauthResult.query).not.toHaveBeenCalled();+ });+ });+ it('passes a server rejection through with its reason and closes the popup', async () => {+ const popup = { close: vi.fn() } as unknown as Window;+ const rejection = Object.assign(new Error('OAuth server rejected the registration'), {+ data: { code: 'BAD_REQUEST', httpStatus: 400 },+ });+ vi.mocked(lambdaClient.connector.startOAuth.mutate).mockRejectedValueOnce(rejection);+ await expect(useToolStore.getState().connectConnectorAccount('c1', { popup })).rejects.toBe(+ rejection,+ );+ expect(popup.close).toHaveBeenCalled();+ });+ it('limits multiple accounts to custom HTTP OAuth connectors', () => {+ expect(+ supportsMultipleConnectorAccounts({+ authKind: 'oauth2',+ sourceType: 'custom',+ mcpConnectionType: 'http',+ }),+ ).toBe(true);+ expect(+ supportsMultipleConnectorAccounts({+ authKind: 'bearer',+ sourceType: 'custom',+ mcpConnectionType: 'http',+ }),+ ).toBe(false);+ });+ it('reads the exact server outcome after native completion instead of guessing from the target', async () => {+ vi.mocked(lambdaClient.connector.startOAuth.mutate).mockResolvedValueOnce({+ authorizationUrl: 'https://provider/authorize',+ flowId: 'flow',+ });+ vi.mocked(lambdaClient.connector.oauthResult.query).mockResolvedValueOnce({+ linkId: 'other-existing',+ outcome: 'matchedExisting',+ });+ expect(await useToolStore.getState().reauthorizeConnectorAccount('c1', 'old')).toEqual({+ linkId: 'other-existing',+ outcome: 'matchedExisting',+ });+ });+ it('treats a pre-aborted flow as dismissal before starting OAuth', async () => {+ const abort = new AbortController();+ abort.abort();+ await expect(+ useToolStore.getState().connectConnectorAccount('c1', { signal: abort.signal }),+ ).rejects.toMatchObject({ reason: 'dismissed' });+ expect(lambdaClient.connector.startOAuth.mutate).not.toHaveBeenCalled();+ });+});diff --git a/src/store/tool/slices/connector/action.ts b/src/store/tool/slices/connector/action.tsindex f748f211e49..c7d79cd8eff 100644--- a/src/store/tool/slices/connector/action.ts+++ b/src/store/tool/slices/connector/action.ts@@ -21,6 +21,7 @@ import { lambdaClient } from '@/libs/trpc/client';import { discoverService } from '@/services/discover';import { type LocalMcpTool, mcpService } from '@/services/mcp';import type { StoreSetter } from '@/store/types';+import { ConnectorOAuthError, waitForConnectorOAuth } from '@/utils/connectorOAuth';import type { ToolStore } from '../../store';import { buildCloudMcpManifest, cloudManifestTools } from '../mcpStore/cloudManifest';@@ -34,7 +35,12 @@ import {withoutConnectorSecrets,} from './projection';import { connectorSelectors } from './selectors';-import type { AgentBoundConnector, ConnectorWithTools } from './types';+import type {+ AgentBoundConnector,+ ConnectorAccountFlowOptions,+ ConnectorAccountFlowResult,+ ConnectorWithTools,+} from './types';type Setter = StoreSetter<ToolStore>;@@ -418,6 +424,115 @@ export class ConnectorActionImpl {}};+ /** Connect an additional account and refresh all connector lists after authorization. */+ connectConnectorAccount = (+ connectorId: string,+ options?: ConnectorAccountFlowOptions,+ ): Promise<ConnectorAccountFlowResult> =>+ this.#authorizeAccount(connectorId, { mode: 'add' }, options);++ /** Reauthorize the selected account and return the actual server-resolved outcome. */+ reauthorizeConnectorAccount = (+ connectorId: string,+ linkId: string,+ options?: ConnectorAccountFlowOptions,+ ): Promise<ConnectorAccountFlowResult> =>+ this.#authorizeAccount(connectorId, { mode: 'reauthorize', linkId }, options);++ #authorizeAccount = async (+ connectorId: string,+ link: { mode: 'add' } | { mode: 'reauthorize'; linkId: string },+ options: ConnectorAccountFlowOptions = {},+ ): Promise<ConnectorAccountFlowResult> => {+ const linksOf = () =>+ [+ ...(this.#get().connectors ?? []),+ ...(this.#get().agentBoundConnectors ?? []),+ ...Object.values(this.#get().agentConnectors ?? {}).flat(),+ ].find((c) => c.id === connectorId)?.links ?? [];+ const before = linksOf();+ let flowId: string | undefined;+ try {+ options.signal?.throwIfAborted();+ const started = await lambdaClient.connector.startOAuth.mutate(+ {+ id: connectorId,+ link,+ },+ { signal: options.signal },+ );+ flowId = started.flowId;+ const reported = await waitForConnectorOAuth(+ options.popup,+ connectorId,+ started.authorizationUrl,+ options.signal,+ link.mode === 'add',+ );+ await this.#refreshConnectorLists();+ // The callback's own report, else the server's record of the flow (the+ // native window reports success alone), else the lists' difference: the+ // record is a fallback whose absence never fails a stored authorization+ if (reported) return reported;+ const recorded = flowId+ ? await lambdaClient.connector.oauthResult.query({ flowId }).catch(() => undefined)+ : undefined;+ if (recorded) return recorded;+ const created = linksOf().find((item) => !before.some((old) => old.id === item.id));+ return created+ ? { outcome: 'created', linkId: created.id }+ : {+ outcome: link.mode === 'add' ? 'matchedExisting' : 'reauthorized',+ linkId: link.mode === 'reauthorize' ? link.linkId : undefined,+ };+ } catch (error) {+ if (options.signal?.aborted) throw new ConnectorOAuthError('dismissed');+ // Providers whose COOP policy severs `window.opener` lose the callback's+ // message: the window then reads as closed or never reporting back,+ // although the callback stored the account. The server recorded how the+ // flow ended, so ask it before calling the authorization lost.+ const recovered = await this.#recoverAccountAuthorization(error, flowId);+ if (recovered) return recovered;+ // Server rejections (a 403, an OAuth server that refuses registration)+ // carry the reason the caller shows; only the window flow is an OAuth error.+ throw error;+ } finally {+ options.popup?.close();+ }+ };++ #recoverAccountAuthorization = async (+ error: unknown,+ flowId: string | undefined,+ ): Promise<ConnectorAccountFlowResult | undefined> => {+ if (!flowId || !(error instanceof ConnectorOAuthError)) return;+ if (error.reason !== 'dismissed' && error.reason !== 'timeout') return;+ let result: ConnectorAccountFlowResult;+ try {+ result = await lambdaClient.connector.oauthResult.query({ flowId });+ } catch {+ return; // no completion recorded: the authorization did not finish+ }+ await this.#refreshConnectorLists();+ return result;+ };++ /** Rename an account and refresh every loaded connector list. */+ renameConnectorAccount = async (+ connectorId: string,+ linkId: string,+ name: string,+ ): Promise<void> => {+ await lambdaClient.connector.renameLink.mutate({ id: connectorId, linkId, name });+ await this.#refreshConnectorLists();+ };++ /** Remove an account and refresh its connector, including last-account disconnection. */+ removeConnectorAccount = async (connectorId: string, linkId: string): Promise<void> => {+ await lambdaClient.connector.deleteLink.mutate({ id: connectorId, linkId });+ await this.#refreshConnectorLists();+ };+/*** Begin the OAuth authorization-code flow for a custom connector and return* the authorize URL for the caller to open in a popup. Resolves the clientdiff --git a/src/store/tool/slices/connector/projection.ts b/src/store/tool/slices/connector/projection.tsindex 04c169ebcb7..61b4ef4d24e 100644--- a/src/store/tool/slices/connector/projection.ts+++ b/src/store/tool/slices/connector/projection.ts@@ -21,7 +21,7 @@ export const connectorsResource = defineReplica<key: () => CONNECTOR_LIST_KEY,name: 'connectors',storage: 'indexedDB',- version: 1,+ version: 2,});/**@@ -37,7 +37,7 @@ export const agentBoundConnectorsResource = defineReplica<key: () => CONNECTOR_LIST_KEY,name: 'agentBoundConnectors',storage: 'indexedDB',- version: 1,+ version: 2,});/**@@ -48,7 +48,7 @@ export const agentConnectorsResource = defineReplica<{ agentId: string }, Conneckey: ({ agentId }) => agentId,name: 'agentConnectors',storage: 'indexedDB',- version: 1,+ version: 2,});/** Connectors are addressed by `id` across the tool store. */diff --git a/src/store/tool/slices/connector/selectors.runtime.test.ts b/src/store/tool/slices/connector/selectors.runtime.test.tsindex 5c85ac40f86..6d512257f94 100644--- a/src/store/tool/slices/connector/selectors.runtime.test.ts+++ b/src/store/tool/slices/connector/selectors.runtime.test.ts@@ -184,3 +184,53 @@ describe('connectorSelectors.connectorByIdentifierForAgent', () => {).toBe('c1');});});++describe('connector link names across replica pools', () => {+ // Every legacy connector's account is `lnk_default`: a name must come from the+ // connector the call runs on, not the first one holding that id+ it('names a shared account id after the connector a tool call runs on', () => {+ const legacy = (id: string, identifier: string, name: string, agentId?: string) =>+ connector({ agentId, id, identifier, links: [{ id: 'lnk_default', name } as any] });+ const state = {+ connectors: [legacy('a', 'work-mail', 'Work'), legacy('b', 'home-mail', 'Personal')],+ agentConnectors: { agt_x: [legacy('c', 'home-mail', 'Agent copy', 'agt_x')] },+ } as unknown as ToolStore;++ expect(connectorSelectors.connectorLinkNameForTool('home-mail', 'lnk_default')(state)).toBe(+ 'Personal',+ );+ expect(connectorSelectors.connectorLinkNameForTool('work-mail', 'lnk_default')(state)).toBe(+ 'Work',+ );+ // An agent's own copy wins, as it does when the call resolves its connector+ expect(+ connectorSelectors.connectorLinkNameForTool('home-mail', 'lnk_default', 'agt_x')(state),+ ).toBe('Agent copy');+ expect(+ connectorSelectors.connectorLinkNameForTool('unknown', 'lnk_default')(state),+ ).toBeUndefined();+ });++ it('resolves base, aggregate and per-agent links and preserves unknown IDs', () => {+ const make = (id: string) => connector({ id, links: [{ id: `lnk_${id}`, name: id } as any] });+ const state = {+ connectors: [make('base')],+ agentBoundConnectors: [make('aggregate')],+ agentConnectors: { agent: [make('agent')] },+ } as unknown as ToolStore;+ for (const name of ['base', 'aggregate', 'agent'])+ expect(connectorSelectors.connectorLinkName(name, `lnk_${name}`)(state)).toBe(name);+ expect(connectorSelectors.connectorLinkName('base', 'missing')(state)).toBeUndefined();+ expect(connectorSelectors.connectorLinkName('agent', 'lnk_base')(state)).toBeUndefined();+ expect(+ buildClientConnectorManifests([+ connector({+ links: [+ { id: 'a', name: 'Alice' },+ { id: 'b', name: 'Bob' },+ ] as any,+ }),+ ])[0].api[0].parameters.required,+ ).toContain('link_id');+ });+});diff --git a/src/store/tool/slices/connector/selectors.ts b/src/store/tool/slices/connector/selectors.tsindex ce020255bbb..3ad4ff133f8 100644--- a/src/store/tool/slices/connector/selectors.ts+++ b/src/store/tool/slices/connector/selectors.ts@@ -207,6 +207,31 @@ const agentOverriddenIdentifiers =};export const connectorSelectors = {+ /**+ * An account's name on one connector. Account ids are unique per connector+ * only (every legacy connector's account is `lnk_default`), so the lookup+ * is always scoped to the connector that owns the account.+ */+ connectorLinkName:+ (connectorId: string, linkId: string) =>+ (s: ToolStore): string | undefined => {+ const pools = [+ ...(s.connectors ?? []),+ ...(s.agentBoundConnectors ?? []),+ ...Object.values(s.agentConnectors ?? {}).flat(),+ ];+ return pools+ .find((connector) => connector.id === connectorId)+ ?.links?.find((link) => link.id === linkId)?.name;+ },+ /** An account's name on the connector a tool call runs on, resolved as the call is. */+ connectorLinkNameForTool:+ (identifier: string, linkId: string, agentId?: string) =>+ (s: ToolStore): string | undefined =>+ connectorByIdentifierForAgent(+ identifier,+ agentId,+ )(s)?.links?.find((link) => link.id === linkId)?.name,agentBoundConnectors,agentConnectors,agentOverriddenIdentifiers,diff --git a/src/store/tool/slices/connector/types.ts b/src/store/tool/slices/connector/types.tsindex aab1ea1ca07..56e26a125cc 100644--- a/src/store/tool/slices/connector/types.ts+++ b/src/store/tool/slices/connector/types.ts@@ -1,3 +1,5 @@+import type { ConnectorAuthKind, ConnectorLinkProfile, ConnectorLinkStatus } from '@lobechat/types';+import type { ConnectorToolPermission } from '@/database/schemas';export interface ConnectorTool {@@ -16,6 +18,7 @@ export interface ConnectorTool {export interface ConnectorWithTools {/** Set when this connector is fully owned by an agent (Copy / Connect-new). */agentId?: string | null;+ authKind?: ConnectorAuthKind;/*** Attribution — avatar of the member who authorized this connector (the* Composio account linker when present, else the row creator). Server-resolved@@ -28,6 +31,7 @@ export interface ConnectorWithTools {id: string;identifier: string;isEnabled: boolean;+ links?: ConnectorLinkSummary[];mcpConnectionType: string | null;mcpServerUrl: string | null;metadata: Record<string, unknown> | null;@@ -39,6 +43,40 @@ export interface ConnectorWithTools {userId?: string | null;}+export interface ConnectorLinkSummary {+ authorizedByAvatar: string | null;+ authorizedByName: string | null;+ createdAt: string;+ id: string;+ name: string;+ profile: ConnectorLinkProfile | null;+ status: ConnectorLinkStatus;+}++export interface ConnectorAccountFlowOptions {+ popup?: Window | null;+ signal?: AbortSignal;+}+export interface ConnectorAccountFlowResult {+ linkId?: string;+ outcome: 'created' | 'reauthorized' | 'matchedExisting';+}++export const supportsMultipleConnectorAccounts = (+ connector: Pick<ConnectorWithTools, 'authKind' | 'mcpConnectionType' | 'sourceType'>,+): boolean =>+ connector.authKind === 'oauth2' &&+ connector.sourceType === 'custom' &&+ connector.mcpConnectionType === 'http';++export const isConnectorLinkNameConflict = (error: unknown): boolean => {+ const candidate = error as {+ data?: { code?: string };+ shape?: { data?: { code?: string } };+ } | null;+ return candidate?.data?.code === 'CONFLICT' || candidate?.shape?.data?.code === 'CONFLICT';+};+/*** An agent-owned connector as returned by `connector.listAgentBound`, enriched* with the owning agent's display info for the unified settings attributiondiff --git a/src/store/tool/slices/plugin/action.ts b/src/store/tool/slices/plugin/action.tsindex b3e137d062c..66db603eb1e 100644--- a/src/store/tool/slices/plugin/action.ts+++ b/src/store/tool/slices/plugin/action.ts@@ -218,22 +218,44 @@ export class PluginActionImpl {/*** The `ui://` resource (HTML view) an MCP App tool result renders with, read* from `server`, the one the tool ran on, as `agentId`'s runs resolve it, and- * where it ran (`onThisDevice`). The HTML is only the view's: it stays in this- * request's cache, not in the store.+ * where it ran (`onThisDevice`). `toolArguments` carry the account the tool+ * ran as when its connector holds several. The HTML is only the view's: it+ * stays in this request's cache, not in the store.*/useFetchMcpAppResource = (identifier: string,resourceUri: string,{agentId,+ linkId,onThisDevice = false,server,- }: { agentId?: string; onThisDevice?: boolean; server?: string },+ toolArguments,+ }: {+ agentId?: string;+ /** The account the view acts as, when its arguments cannot name one. */+ linkId?: string;+ onThisDevice?: boolean;+ server?: string;+ toolArguments?: string;+ },): SWRResponse<ReadResourceResult | undefined> =>useClientDataSWR(- mcpAppKeys.resource(identifier, resourceUri, { agentId, onThisDevice, server }),+ mcpAppKeys.resource(identifier, resourceUri, {+ agentId,+ linkId,+ onThisDevice,+ server,+ toolArguments,+ }),() =>- mcpService.readMcpAppResource(identifier, resourceUri, { agentId, onThisDevice, server }),+ mcpService.readMcpAppResource(identifier, resourceUri, {+ agentId,+ linkId,+ onThisDevice,+ server,+ toolArguments,+ }),{ revalidateOnFocus: false, revalidateOnReconnect: false },);diff --git a/src/utils/connectorOAuth.test.ts b/src/utils/connectorOAuth.test.tsindex fbb4c613da3..0a7ac4f0e95 100644--- a/src/utils/connectorOAuth.test.ts+++ b/src/utils/connectorOAuth.test.ts@@ -132,6 +132,18 @@ describe('connector OAuth popup', () => {expect(vi.getTimerCount()).toBe(0);});+ it('resolves with the account the callback reports storing', async () => {+ const result = waitForConnectorOAuth(popup, 'connector-1', authorizationUrl);+ send(popup, 'https://server.example', {+ connectorId: 'connector-1',+ linkId: 'lnk_b',+ outcome: 'matchedExisting',+ success: true,+ type: 'lobe-connector-oauth',+ });+ await expect(result).resolves.toEqual({ linkId: 'lnk_b', outcome: 'matchedExisting' });+ });+it('reports navigation failure and cleans up without accepting a later callback', async () => {Object.defineProperty(popup.location, 'href', {set: () => {diff --git a/src/utils/connectorOAuth.ts b/src/utils/connectorOAuth.tsindex c21c3b013a3..27313588f8b 100644--- a/src/utils/connectorOAuth.ts+++ b/src/utils/connectorOAuth.ts@@ -9,19 +9,39 @@ export class ConnectorOAuthError extends Error {}}+/** The account a callback reports it stored, and how. */+export interface ConnectorOAuthOutcome {+ linkId: string;+ outcome: 'created' | 'matchedExisting' | 'reauthorized';+}++const OUTCOMES = new Set<string>(['created', 'matchedExisting', 'reauthorized']);+const reportedOutcome = (data: {+ linkId?: unknown;+ outcome?: unknown;+}): ConnectorOAuthOutcome | undefined =>+ typeof data.linkId === 'string' && typeof data.outcome === 'string' && OUTCOMES.has(data.outcome)+ ? { linkId: data.linkId, outcome: data.outcome as ConnectorOAuthOutcome['outcome'] }+ : undefined;+/** Must be called synchronously from the click, before validation or network IO. */export const openConnectorOAuthPopup = () =>isDesktop? undefined: window.open('about:blank', 'lobe-connector-oauth', 'width=600,height=720');-/** Navigate and wait for the server callback, not messages from the provider. */+/**+ * Navigate and wait for the server callback, not messages from the provider.+ * Resolves with the account the callback reports, when its message carries+ * one (the native window reports success alone).+ */export const waitForConnectorOAuth = async (popup: Window | null | undefined,connectorId: string,authorizationUrl: string,signal?: AbortSignal,-): Promise<void> => {+ freshSession?: boolean,+): Promise<ConnectorOAuthOutcome | undefined> => {signal?.throwIfAborted();if (isDesktop) {// Native ownership survives provider COOP headers that sever window.opener.@@ -34,7 +54,12 @@ export const waitForConnectorOAuth = async (};signal?.addEventListener('abort', onAbort, { once: true });try {- const result = await oauth.authorize({ authorizationUrl, connectorId, requestId });+ const result = await oauth.authorize({+ authorizationUrl,+ connectorId,+ requestId,+ freshSession,+ });if (signal?.aborted) throw new ConnectorOAuthError('dismissed');if (result !== 'success') throw new ConnectorOAuthError(result);} finally {@@ -49,14 +74,14 @@ export const waitForConnectorOAuth = async (const callbackOrigin = redirectUri ? new URL(redirectUri).origin : window.location.origin;return new Promise((resolve, reject) => {- const finish = (error?: ConnectorOAuthError) => {+ const finish = (error?: ConnectorOAuthError, outcome?: ConnectorOAuthOutcome) => {signal?.removeEventListener('abort', onAbort);window.removeEventListener('message', onMessage);clearInterval(timer);clearTimeout(timeout);if (!popup.closed) popup.close();if (error) reject(error);- else resolve();+ else resolve(outcome);};const onMessage = (event: MessageEvent) => {@@ -65,7 +90,8 @@ export const waitForConnectorOAuth = async (if (!data || data.type !== 'lobe-connector-oauth') return;// Early callback failures (e.g. access_denied) have no connector ID.if (data.connectorId && data.connectorId !== connectorId) return;- if (data.success === true && data.connectorId === connectorId) finish();+ if (data.success === true && data.connectorId === connectorId)+ finish(undefined, reportedOutcome(data));else if (data.success === false) finish(new ConnectorOAuthError('failed'));};const onAbort = () => finish(new ConnectorOAuthError('dismissed'));diff --git a/src/utils/connectorOAuthCreate.ts b/src/utils/connectorOAuthCreate.tsindex e57db828325..cd883a4db75 100644--- a/src/utils/connectorOAuthCreate.ts+++ b/src/utils/connectorOAuthCreate.ts@@ -6,11 +6,12 @@ export interface OAuthCreateDeps<TPayload> {/** Re-read the connector from the server and report whether it is connected. */isConnectorConnected: (id: string) => Promise<boolean>;startConnectorOAuth: (id: string) => Promise<string>;+ /** Settles when the callback completes; what it reports is not needed here. */waitForConnectorOAuth: (popup: Window | null | undefined,connectorId: string,authorizationUrl: string,- ) => Promise<void>;+ ) => Promise<unknown>;}/**