π€― 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
π fix(app,connector-data): support Composio-backed connector data (#17677)
Neko2c16faf6b77c
diff --git a/apps/server/src/routers/lambda/__tests__/user.test.ts b/apps/server/src/routers/lambda/__tests__/user.test.tsindex cd1a7bd33ea..b8fdeee83c5 100644--- a/apps/server/src/routers/lambda/__tests__/user.test.ts+++ b/apps/server/src/routers/lambda/__tests__/user.test.ts@@ -26,6 +26,7 @@ const mockAfterTasks = vi.hoisted((): Promise<void>[] => []);const mockUnderstandingService = vi.hoisted(() => ({confirm: vi.fn(),get: vi.fn(),+ listSourceProviderIds: vi.fn(),revise: vi.fn(),retry: vi.fn(),start: vi.fn(),@@ -108,6 +109,18 @@ describe('userRouter', () => {const scopedCtx = mockCtx;const workspaceCtx = { ...mockCtx, workspaceId: 'workspace-1' };+ it('returns supported apps separately from currently available sources', async () => {+ /** @example Gmail remains connectable while only GitHub is currently usable. */+ mockUnderstandingService.listSourceProviderIds.mockResolvedValueOnce(['github']);++ await expect(+ userRouter.createCaller(scopedCtx).getSupportedUnderstandingProviders(),+ ).resolves.toEqual({+ providerIds: ['github', 'gmail'],+ sourceProviderIds: ['github'],+ });+ });+it('delegates start to the understanding service', async () => {mockUnderstandingService.start.mockResolvedValueOnce(pollingResult);diff --git a/apps/server/src/routers/lambda/user.ts b/apps/server/src/routers/lambda/user.tsindex fda4458288c..dac90f2d0d9 100644--- a/apps/server/src/routers/lambda/user.ts+++ b/apps/server/src/routers/lambda/user.ts@@ -284,9 +284,12 @@ export const userRouter = router({return ctx.understandingService.get(input.topicId);}),- getSupportedUnderstandingProviders: authedProcedure.query(- async (): Promise<{ providerIds: string[] }> => {- return { providerIds: understandingProviders.map((provider) => provider.id) };+ getSupportedUnderstandingProviders: understandingServiceProcedure.query(+ async ({ ctx }): Promise<{ providerIds: string[]; sourceProviderIds: string[] }> => {+ return {+ providerIds: understandingProviders.map((provider) => provider.id),+ sourceProviderIds: await ctx.understandingService.listSourceProviderIds(),+ };},),diff --git a/apps/server/src/routers/tools/composio.test.ts b/apps/server/src/routers/tools/composio.test.tsindex 38bd8404353..1fcabfb7c4e 100644--- a/apps/server/src/routers/tools/composio.test.ts+++ b/apps/server/src/routers/tools/composio.test.ts@@ -5,6 +5,8 @@ import { composioToolsRouter } from './composio';const mocks = vi.hoisted(() => ({connectorQueryByIdentifiers: vi.fn(),+ isComposioNotFound: vi.fn(),+ markComposioUnavailable: vi.fn(),pluginFindById: vi.fn(),processToolCallResult: vi.fn(),toolsExecute: vi.fn(),@@ -14,6 +16,7 @@ vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(async () => ({vi.mock('@/database/models/connector', () => ({ConnectorModel: vi.fn().mockImplementation(() => ({+ markComposioConnectionUnavailable: mocks.markComposioUnavailable,queryByIdentifiers: mocks.connectorQueryByIdentifiers,})),}));@@ -24,6 +27,7 @@ vi.mock('@/database/models/plugin', () => ({vi.mock('@/libs/composio', () => ({getComposioClient: () => ({ tools: { execute: mocks.toolsExecute } }),+ isComposioConnectedAccountNotFoundError: mocks.isComposioNotFound,}));vi.mock('@/server/services/mcp', () => ({@@ -36,6 +40,14 @@ const input = { identifier: 'gmail', toolArgs: { to: '[email protected]' }, toolSlug: 'GMAILbeforeEach(() => {vi.clearAllMocks();mocks.connectorQueryByIdentifiers.mockResolvedValue([]);+ mocks.isComposioNotFound.mockImplementation(+ (error: unknown) =>+ typeof error === 'object' &&+ error !== null &&+ 'code' in error &&+ error.code === 'CONNECTED_ACCOUNT_NOT_FOUND',+ );+ mocks.markComposioUnavailable.mockResolvedValue(false);mocks.pluginFindById.mockResolvedValue(undefined);mocks.toolsExecute.mockResolvedValue({ data: 'ok' });mocks.processToolCallResult.mockResolvedValue({ content: 'ok', success: true });@@ -44,7 +56,7 @@ beforeEach(() => {describe('composioToolsRouter.executeAction', () => {it('resolves connectedAccountId from connector metadata (new path)', async () => {mocks.connectorQueryByIdentifiers.mockResolvedValue([- { metadata: { composio: { connectedAccountId: 'ca-connector' } } },+ { id: 'conn-gmail', metadata: { composio: { connectedAccountId: 'ca-connector' } } },]);await caller().executeAction(input);@@ -56,6 +68,48 @@ describe('composioToolsRouter.executeAction', () => {expect(mocks.pluginFindById).not.toHaveBeenCalled();});+ /**+ * @example+ * expect(connector.status).toBe('error');+ */+ it('delegates a connected-account 404 to ConnectorModel for manual execution', async () => {+ const notFound = Object.assign(new Error('connected account not found'), {+ code: 'CONNECTED_ACCOUNT_NOT_FOUND',+ });+ mocks.connectorQueryByIdentifiers.mockResolvedValue([+ { id: 'conn-gmail', metadata: { composio: { connectedAccountId: 'ca-connector' } } },+ ]);+ mocks.toolsExecute.mockRejectedValue(notFound);+ mocks.markComposioUnavailable.mockResolvedValue(true);++ await expect(caller().executeAction(input)).rejects.toMatchObject({+ message: 'connected account not found',+ });+ expect(mocks.markComposioUnavailable).toHaveBeenCalledWith('conn-gmail', 'ca-connector');+ });++ /**+ * @example+ * expect(connector.status).toBe('connected');+ */+ it('does not disable a connector when manual execution reports a remote resource 404', async () => {+ // ROOT CAUSE:+ //+ // Tool actions can return 404 for the target resource while their connected account is healthy.+ // Only Composio's explicit connected-account-not-found error may update connector health here.+ mocks.connectorQueryByIdentifiers.mockResolvedValue([+ { id: 'conn-gmail', metadata: { composio: { connectedAccountId: 'ca-connector' } } },+ ]);+ mocks.toolsExecute.mockRejectedValue(+ Object.assign(new Error('message not found'), { status: 404 }),+ );++ await expect(caller().executeAction(input)).rejects.toMatchObject({+ message: 'message not found',+ });+ expect(mocks.markComposioUnavailable).not.toHaveBeenCalled();+ });+it('falls back to plugin customParams when no connector projection exists', async () => {mocks.connectorQueryByIdentifiers.mockResolvedValue([]);mocks.pluginFindById.mockResolvedValue({diff --git a/apps/server/src/routers/tools/composio.ts b/apps/server/src/routers/tools/composio.tsindex 19b620747d1..bfff6b846d2 100644--- a/apps/server/src/routers/tools/composio.ts+++ b/apps/server/src/routers/tools/composio.ts@@ -4,7 +4,7 @@ import { z } from 'zod';import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';import { ConnectorModel } from '@/database/models/connector';import { PluginModel } from '@/database/models/plugin';-import { getComposioClient } from '@/libs/composio';+import { getComposioClient, isComposioConnectedAccountNotFoundError } from '@/libs/composio';import { publicProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { MCPService } from '@/server/services/mcp';@@ -65,14 +65,29 @@ export const composioToolsRouter = router({});}- const result = await (ctx.composioClient.tools as any).execute(input.toolSlug, {- arguments: input.toolArgs || {},- connectedAccountId,- // Toolkit version resolves to "latest"; allow manual execution without a- // pinned version (Composio otherwise throws ComposioToolVersionRequiredError).- dangerouslySkipVersionCheck: true,- userId: ownerUserId ?? ctx.userId,- });+ let result: unknown;+ try {+ result = await (ctx.composioClient.tools as any).execute(input.toolSlug, {+ arguments: input.toolArgs || {},+ connectedAccountId,+ // Toolkit version resolves to "latest"; allow manual execution without a+ // pinned version (Composio otherwise throws ComposioToolVersionRequiredError).+ dangerouslySkipVersionCheck: true,+ userId: ownerUserId ?? ctx.userId,+ });+ } catch (error) {+ if (connector?.id && isComposioConnectedAccountNotFoundError(error)) {+ try {+ await ctx.connectorModel.markComposioConnectionUnavailable(+ connector.id,+ connectedAccountId,+ );+ } catch {+ // Preserve the remote execution error if the secondary health write fails.+ }+ }+ throw error;+ }if (!result) {return {diff --git a/apps/server/src/services/composio/index.test.ts b/apps/server/src/services/composio/index.test.tsindex 40857bf34d9..306556d16d4 100644--- a/apps/server/src/services/composio/index.test.ts+++ b/apps/server/src/services/composio/index.test.ts@@ -7,6 +7,8 @@ const mocks = vi.hoisted(() => ({connectorQueryByIdentifiers: vi.fn(),connectorToolQueryAll: vi.fn(),isClientAvailable: vi.fn(),+ isComposioNotFound: vi.fn(),+ markComposioUnavailable: vi.fn(),pluginFindById: vi.fn(),pluginQuery: vi.fn(),toolsExecute: vi.fn(),@@ -19,6 +21,7 @@ vi.mock('@/database/models/connector', () => ({// own connectorAgentScope tests).resolveAll: mocks.connectorQuery,resolveByIdentifiers: mocks.connectorQueryByIdentifiers,+ markComposioConnectionUnavailable: mocks.markComposioUnavailable,})),}));@@ -38,6 +41,7 @@ vi.mock('@/database/models/plugin', () => ({vi.mock('@/libs/composio', () => ({getComposioClient: () => ({ tools: { execute: mocks.toolsExecute } }),isComposioClientAvailable: mocks.isClientAvailable,+ isComposioConnectedAccountNotFoundError: mocks.isComposioNotFound,}));const service = () => new ComposioService({ db: {} as any, userId: 'user-1' });@@ -57,6 +61,14 @@ const activeConnectorRow = (overrides: Record<string, any> = {}) => ({beforeEach(() => {vi.clearAllMocks();mocks.isClientAvailable.mockReturnValue(true);+ mocks.isComposioNotFound.mockImplementation(+ (error: unknown) =>+ typeof error === 'object' &&+ error !== null &&+ 'code' in error &&+ error.code === 'CONNECTED_ACCOUNT_NOT_FOUND',+ );+ mocks.markComposioUnavailable.mockResolvedValue(false);mocks.connectorQuery.mockResolvedValue([]);mocks.connectorQueryByIdentifiers.mockResolvedValue([]);mocks.connectorToolQueryAll.mockResolvedValue([]);@@ -181,6 +193,45 @@ describe('ComposioService.executeComposioTool', () => {expect(mocks.pluginFindById).not.toHaveBeenCalled();});+ /**+ * @example+ * expect(connector.status).toBe('error');+ */+ it('delegates a connected-account 404 to ConnectorModel after tool execution fails', async () => {+ const notFound = Object.assign(new Error('connected account not found'), {+ code: 'CONNECTED_ACCOUNT_NOT_FOUND',+ });+ mocks.connectorQueryByIdentifiers.mockResolvedValue([activeConnectorRow()]);+ mocks.toolsExecute.mockRejectedValue(notFound);+ mocks.markComposioUnavailable.mockResolvedValue(true);++ const result = await service().executeComposioTool(params);++ expect(result.success).toBe(false);+ expect(mocks.markComposioUnavailable).toHaveBeenCalledWith('conn-gmail', 'ca-connector');+ });++ /**+ * @example+ * expect(connector.status).toBe('connected');+ */+ it('does not disable a connector when a tool reports a remote resource 404', async () => {+ // ROOT CAUSE:+ //+ // A generic HTTP 404 can mean the requested email, repository, or other provider resource is+ // missing. Treating every 404 as a missing Composio connected account disabled healthy connectors.+ // We now require Composio's explicit connected-account-not-found classification at this boundary.+ mocks.connectorQueryByIdentifiers.mockResolvedValue([activeConnectorRow()]);+ mocks.toolsExecute.mockRejectedValue(+ Object.assign(new Error('repository not found'), { status: 404 }),+ );++ const result = await service().executeComposioTool(params);++ expect(result.success).toBe(false);+ expect(mocks.markComposioUnavailable).not.toHaveBeenCalled();+ });+it('executes under the account OWNER entity, not the caller (workspace-shared connector)', async () => {// Regression: a workspace member runs a shared agent whose Composio connector// was linked by another user (openomy). buildWorkspaceWhere resolves thatdiff --git a/apps/server/src/services/composio/index.ts b/apps/server/src/services/composio/index.tsindex 16f2df5e058..bdf50ef0817 100644--- a/apps/server/src/services/composio/index.ts+++ b/apps/server/src/services/composio/index.ts@@ -7,7 +7,11 @@ import { ConnectorModel } from '@/database/models/connector';import { ConnectorToolModel } from '@/database/models/connectorTool';import { PluginModel } from '@/database/models/plugin';import type { UserConnectorToolItem } from '@/database/schemas';-import { getComposioClient, isComposioClientAvailable } from '@/libs/composio';+import {+ getComposioClient,+ isComposioClientAvailable,+ isComposioConnectedAccountNotFoundError,+} from '@/libs/composio';import { type ToolExecutionResult } from '@/server/services/toolExecution/types';const log = debug('lobe-server:composio-service');@@ -76,6 +80,8 @@ export class ComposioService {async executeComposioTool(params: ComposioToolExecuteParams): Promise<ToolExecutionResult> {const { identifier, toolSlug, args, agentId } = params;+ let resolvedConnectedAccountId: string | undefined;+ let resolvedConnectorId: string | undefined;log('executeComposioTool: %s/%s with args: %O', identifier, toolSlug, args);@@ -112,6 +118,8 @@ export class ComposioService {}const { connectedAccountId, ownerUserId } = account;+ resolvedConnectedAccountId = connectedAccountId;+ resolvedConnectorId = account.connectorId;log('executeComposioTool: calling Composio API with connectedAccountId=%s, ownerUserId=%s',@@ -158,6 +166,22 @@ export class ComposioService {return { content: resultContent, success: true };} catch (error) {const err = error as Error;+ if (+ resolvedConnectedAccountId &&+ resolvedConnectorId &&+ this.connectorModel &&+ isComposioConnectedAccountNotFoundError(error)+ ) {+ try {+ await this.connectorModel.markComposioConnectionUnavailable(+ resolvedConnectorId,+ resolvedConnectedAccountId,+ );+ } catch (healthError) {+ // Persisting connector health must not replace the original remote tool error.+ log('executeComposioTool: failed to persist connector health: %O', healthError);+ }+ }console.error('ComposioService.executeComposioTool error %s/%s: %O',identifier,@@ -191,13 +215,16 @@ export class ComposioService {private async resolveComposioAccount(identifier: string,agentId?: string,- ): Promise<{ connectedAccountId: string; ownerUserId: string } | undefined> {+ ): Promise<+ { connectedAccountId: string; connectorId?: string; ownerUserId: string } | undefined+ > {if (this.connectorModel) {const [connector] = await this.connectorModel.resolveByIdentifiers([identifier], agentId);const composio = connector?.metadata?.composio;if (composio?.connectedAccountId) {return {connectedAccountId: composio.connectedAccountId,+ connectorId: connector.id,ownerUserId: composio.linkedByUserId ?? connector.userId ?? this.userId!,};}diff --git a/apps/server/src/services/connectorData/index.test.ts b/apps/server/src/services/connectorData/index.test.tsindex c1ba93dc0fa..141c38c0bfa 100644--- a/apps/server/src/services/connectorData/index.test.ts+++ b/apps/server/src/services/connectorData/index.test.ts@@ -5,19 +5,24 @@ import type { LobeChatDatabase } from '@/database/type';import { ConnectorDataService } from './index';const mocks = vi.hoisted(() => ({- createGitHubClient: vi.fn(),+ composioConnectedAccountGet: vi.fn(),+ createGitHubComposioClient: vi.fn(),+ createGitHubOAuthClient: vi.fn(),createGmailClient: vi.fn(),ensureFreshConnectorToken: vi.fn(),findById: vi.fn(),getAccount: vi.fn(),getComposioClient: vi.fn(),initWithEnvKey: vi.fn(),+ isComposioLookupNotFound: vi.fn(),+ markComposioUnavailable: vi.fn(),queryComposioReferences: vi.fn(),queryReferences: vi.fn(),}));vi.mock('@lobechat/connector-data/github', () => ({- createGitHubConnectorClient: mocks.createGitHubClient,+ createGitHubComposioConnectorClient: mocks.createGitHubComposioClient,+ createGitHubOAuthConnectorClient: mocks.createGitHubOAuthClient,}));vi.mock('@lobechat/connector-data/gmail', () => ({@@ -27,12 +32,16 @@ vi.mock('@lobechat/connector-data/gmail', () => ({vi.mock('@/database/models/connector', () => ({ConnectorModel: vi.fn(() => ({findById: mocks.findById,+ markComposioConnectionUnavailable: mocks.markComposioUnavailable,queryComposioReferencesByIdentifiers: mocks.queryComposioReferences,queryReferencesByIdentifiers: mocks.queryReferences,})),}));-vi.mock('@/libs/composio', () => ({ getComposioClient: mocks.getComposioClient }));+vi.mock('@/libs/composio', () => ({+ getComposioClient: mocks.getComposioClient,+ isComposioConnectedAccountLookupNotFoundError: mocks.isComposioLookupNotFound,+}));vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({KeyVaultsGateKeeper: { initWithEnvKey: mocks.initWithEnvKey },}));@@ -56,9 +65,19 @@ const authDb = (describe('ConnectorDataService', () => {beforeEach(() => {vi.clearAllMocks();- mocks.getComposioClient.mockReturnValue({ kind: 'composio' });+ mocks.composioConnectedAccountGet.mockResolvedValue({ status: 'ACTIVE' });+ mocks.getComposioClient.mockReturnValue({+ connectedAccounts: { get: mocks.composioConnectedAccountGet },+ kind: 'composio',+ });mocks.initWithEnvKey.mockResolvedValue({ kind: 'gatekeeper' });- mocks.createGitHubClient.mockReturnValue({ kind: 'github-client' });+ mocks.isComposioLookupNotFound.mockImplementation(+ (error: unknown) =>+ typeof error === 'object' && error !== null && 'status' in error && error.status === 404,+ );+ mocks.createGitHubComposioClient.mockReturnValue({ kind: 'github-composio-client' });+ mocks.createGitHubOAuthClient.mockReturnValue({ kind: 'github-client' });+ mocks.markComposioUnavailable.mockResolvedValue(false);mocks.getAccount.mockResolvedValue({ externalAccountId: 'gmail-account', scopes: [] });mocks.createGmailClient.mockReturnValue({ getAccount: mocks.getAccount, kind: 'gmail-client' });mocks.queryReferences.mockResolvedValue([]);@@ -90,7 +109,7 @@ describe('ConnectorDataService', () => {expect(client).toEqual({ kind: 'github-client' });expect(mocks.findById).toHaveBeenCalledWith('connector-a');expect(mocks.ensureFreshConnectorToken).toHaveBeenCalledOnce();- expect(mocks.createGitHubClient).toHaveBeenCalledWith({ accessToken: 'fresh-token' });+ expect(mocks.createGitHubOAuthClient).toHaveBeenCalledWith({ accessToken: 'fresh-token' });});it('falls back to a personal GitHub auth account without initializing KeyVault', async () => {@@ -101,7 +120,7 @@ describe('ConnectorDataService', () => {expect(client).toEqual({ kind: 'github-client' });expect(mocks.initWithEnvKey).not.toHaveBeenCalled();- expect(mocks.createGitHubClient).toHaveBeenCalledWith({ accessToken: 'account-token' });+ expect(mocks.createGitHubOAuthClient).toHaveBeenCalledWith({ accessToken: 'account-token' });});it('skips an expired refreshed connector and falls back to a valid auth account', async () => {@@ -134,8 +153,31 @@ describe('ConnectorDataService', () => {'user-1',).getGitHubClient();- expect(mocks.createGitHubClient).toHaveBeenCalledOnce();- expect(mocks.createGitHubClient).toHaveBeenCalledWith({ accessToken: 'account-token' });+ expect(mocks.createGitHubOAuthClient).toHaveBeenCalledOnce();+ expect(mocks.createGitHubOAuthClient).toHaveBeenCalledWith({ accessToken: 'account-token' });+ });++ /** @example A failed connector database read rejects instead of selecting a fallback account. */+ it('propagates GitHub connector lookup failures', async () => {+ // ROOT CAUSE:+ //+ // A broad catch around connector token resolution also swallowed database failures. Falling back+ // made Understanding persist a source selection based on incomplete availability information.+ // We now reserve fallback for successfully resolved connectors that simply lack usable credentials.+ const databaseError = new Error('database unavailable');+ mocks.queryReferences.mockResolvedValue([+ { id: 'connector-a', isEnabled: true, status: 'connected' },+ ]);+ mocks.findById.mockRejectedValue(databaseError);++ await expect(+ new ConnectorDataService(+ authDb([{ accessToken: 'account-token', id: 'account-a' }]),+ 'user-1',+ ).getGitHubClient(),+ ).rejects.toBe(databaseError);++ expect(mocks.createGitHubOAuthClient).not.toHaveBeenCalled();});it.each([@@ -155,7 +197,7 @@ describe('ConnectorDataService', () => {);await expect(service.getGitHubClient()).rejects.toBeInstanceOf(ConnectorDataError);- expect(mocks.createGitHubClient).not.toHaveBeenCalled();+ expect(mocks.createGitHubOAuthClient).not.toHaveBeenCalled();});it.each([@@ -167,7 +209,94 @@ describe('ConnectorDataService', () => {'user-1',).getGitHubClient();- expect(mocks.createGitHubClient).toHaveBeenCalledWith({ accessToken: 'account-token' });+ expect(mocks.createGitHubOAuthClient).toHaveBeenCalledWith({ accessToken: 'account-token' });+ });++ it('creates GitHub through Composio while preserving the shared connector interface', async () => {+ /** @example An ACTIVE server-resolved Composio account is preferred over OAuth fallback. */+ mocks.queryComposioReferences.mockResolvedValue([+ {+ composio: {+ appSlug: 'github',+ connectedAccountId: 'github-account',+ ownerUserId: 'github-owner',+ status: 'ACTIVE',+ },+ id: 'github-a',+ isEnabled: true,+ status: 'connected',+ },+ ]);++ const client = await new ConnectorDataService(authDb([]), 'user-1').getGitHubClient();++ expect(client).toEqual({ kind: 'github-composio-client' });+ expect(mocks.composioConnectedAccountGet).toHaveBeenCalledWith('github-account');+ expect(mocks.createGitHubComposioClient).toHaveBeenCalledWith({+ composio: expect.objectContaining({ kind: 'composio' }),+ connectedAccountId: 'github-account',+ });+ });++ it('delegates a stale GitHub Composio 404 to ConnectorModel and falls back to OAuth', async () => {+ /** @example A deleted Composio account is persisted as unavailable before fallback. */+ const notFound = Object.assign(new Error('not found'), { status: 404 });+ mocks.queryComposioReferences.mockResolvedValue([+ {+ composio: {+ appSlug: 'github',+ connectedAccountId: 'deleted-account',+ ownerUserId: 'github-owner',+ status: 'ACTIVE',+ },+ id: 'github-stale',+ isEnabled: true,+ status: 'connected',+ },+ ]);+ mocks.composioConnectedAccountGet.mockRejectedValue(notFound);+ mocks.markComposioUnavailable.mockResolvedValue(true);++ const client = await new ConnectorDataService(+ authDb([{ accessToken: 'account-token', id: 'account-a' }]),+ 'user-1',+ ).getGitHubClient();++ expect(client).toEqual({ kind: 'github-client' });+ expect(mocks.markComposioUnavailable).toHaveBeenCalledWith('github-stale', 'deleted-account');+ expect(mocks.createGitHubOAuthClient).toHaveBeenCalledWith({ accessToken: 'account-token' });+ });++ /** @example A remote FAILED account is not returned from a stale ACTIVE projection. */+ it('rejects a GitHub Composio account whose remote status is not ACTIVE', async () => {+ // ROOT CAUSE:+ //+ // The connector projection can remain ACTIVE after the remote account becomes inactive.+ // The lookup response was discarded, so GitHub was advertised until its first proxy call failed.+ //+ // Before: any successful connectedAccounts.get returned a GitHub client.+ // We fixed this by requiring the remote response status to be ACTIVE.+ mocks.queryComposioReferences.mockResolvedValue([+ {+ composio: {+ appSlug: 'github',+ connectedAccountId: 'inactive-account',+ ownerUserId: 'github-owner',+ status: 'ACTIVE',+ },+ id: 'github-inactive',+ isEnabled: true,+ status: 'connected',+ },+ ]);+ mocks.composioConnectedAccountGet.mockResolvedValue({ status: 'EXPIRED' });++ await expect(+ new ConnectorDataService(authDb([]), 'user-1').getGitHubClient(),+ ).rejects.toMatchObject({ code: 'github_authorization_unavailable' });++ expect(mocks.createGitHubComposioClient).not.toHaveBeenCalled();+ expect(mocks.markComposioUnavailable).not.toHaveBeenCalled();});it('creates Gmail from the first active connector and validates account ownership', async () => {@@ -189,10 +318,95 @@ describe('ConnectorDataService', () => {expect(client).toEqual(expect.objectContaining({ kind: 'gmail-client' }));expect(mocks.createGmailClient).toHaveBeenCalledWith({- composio: { kind: 'composio' },+ composio: expect.objectContaining({ kind: 'composio' }),connectedAccountId: 'gmail-account',userId: 'gmail-owner',});expect(mocks.getAccount).toHaveBeenCalledOnce();});++ it('delegates a stale Gmail Composio 404 to ConnectorModel and excludes the client', async () => {+ /** @example A deleted Gmail connection cannot be selected as an Understanding source. */+ const notFound = Object.assign(new Error('not found'), { status: 404 });+ mocks.queryComposioReferences.mockResolvedValue([+ {+ composio: {+ appSlug: 'gmail',+ connectedAccountId: 'deleted-account',+ ownerUserId: 'gmail-owner',+ status: 'ACTIVE',+ },+ id: 'gmail-stale',+ isEnabled: true,+ status: 'connected',+ },+ ]);+ mocks.composioConnectedAccountGet.mockRejectedValue(notFound);+ mocks.markComposioUnavailable.mockResolvedValue(true);++ await expect(+ new ConnectorDataService(authDb([]), 'user-1').getGmailClient(),+ ).rejects.toMatchObject({ code: 'gmail_authorization_unavailable' });++ expect(mocks.markComposioUnavailable).toHaveBeenCalledWith('gmail-stale', 'deleted-account');+ expect(mocks.createGmailClient).not.toHaveBeenCalled();+ });++ /** @example A temporary Composio outage remains retryable by Understanding initialization. */+ it('propagates transient Gmail connected-account lookup failures', async () => {+ // ROOT CAUSE:+ //+ // The Gmail resolver swallowed unknown Composio lookup errors and converted them into permanent+ // authorization unavailability. A transient 5xx could therefore remove Gmail from a new session.+ // We now continue only for confirmed, non-retryable account-unavailable errors.+ const transientError = Object.assign(new Error('temporarily unavailable'), { status: 503 });+ mocks.queryComposioReferences.mockResolvedValue([+ {+ composio: {+ appSlug: 'gmail',+ connectedAccountId: 'gmail-account',+ ownerUserId: 'gmail-owner',+ status: 'ACTIVE',+ },+ id: 'gmail-a',+ isEnabled: true,+ status: 'connected',+ },+ ]);+ mocks.composioConnectedAccountGet.mockRejectedValue(transientError);++ await expect(new ConnectorDataService(authDb([]), 'user-1').getGmailClient()).rejects.toBe(+ transientError,+ );++ expect(mocks.markComposioUnavailable).not.toHaveBeenCalled();+ });++ it('lists only providers whose connector client can currently be resolved', async () => {+ /** @example A stale Gmail connection is excluded while GitHub OAuth remains available. */+ const service = new ConnectorDataService(+ authDb([{ accessToken: 'account-token', id: 'account-a' }]),+ 'user-1',+ );++ await expect(service.listAvailableProviderIds(['github', 'gmail'])).resolves.toEqual([+ 'github',+ ]);+ });++ /** @example A temporary provider failure rejects availability instead of omitting the source. */+ it('propagates transient provider availability failures', async () => {+ // ROOT CAUSE:+ //+ // Availability used to catch every error and report the provider as disconnected.+ // Understanding then persisted a session without the temporarily failing source.+ //+ // Before: a 503 resolved to an empty provider list.+ // We fixed this by filtering only confirmed authorization/account-unavailable errors.+ const transientError = Object.assign(new Error('temporarily unavailable'), { status: 503 });+ const service = new ConnectorDataService(authDb([]), 'user-1');+ vi.spyOn(service, 'getGitHubClient').mockRejectedValue(transientError);++ await expect(service.listAvailableProviderIds(['github'])).rejects.toBe(transientError);+ });});diff --git a/apps/server/src/services/connectorData/index.ts b/apps/server/src/services/connectorData/index.tsindex bda0b3defdf..790b687d390 100644--- a/apps/server/src/services/connectorData/index.ts+++ b/apps/server/src/services/connectorData/index.ts@@ -1,6 +1,9 @@import { ConnectorDataError } from '@lobechat/connector-data';import type { GitHubConnectorClient } from '@lobechat/connector-data/github';-import { createGitHubConnectorClient } from '@lobechat/connector-data/github';+import {+ createGitHubComposioConnectorClient,+ createGitHubOAuthConnectorClient,+} from '@lobechat/connector-data/github';import type { GmailConnectorClient } from '@lobechat/connector-data/gmail';import { createGmailConnectorClient } from '@lobechat/connector-data/gmail';import { and, eq } from 'drizzle-orm';@@ -8,7 +11,7 @@ import { and, eq } from 'drizzle-orm';import { ConnectorModel } from '@/database/models/connector';import { account } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';-import { getComposioClient } from '@/libs/composio';+import { getComposioClient, isComposioConnectedAccountLookupNotFoundError } from '@/libs/composio';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';import { ensureFreshConnectorToken } from '@/server/services/connector/tokens';@@ -22,13 +25,54 @@ const unavailable = (provider: 'github' | 'gmail') =>retryable: false,});+const isConfirmedProviderUnavailableError = (error: unknown, provider: 'github' | 'gmail') =>+ error instanceof ConnectorDataError &&+ error.provider === provider &&+ !error.retryable &&+ (error.code === `${provider}_authorization_unavailable` ||+ error.code === `${provider}_account_unavailable`);+const isActiveReference = (reference: { isEnabled: boolean; status: string }) =>reference.isEnabled && reference.status === 'connected';+const isActiveComposioReference = (+ reference: {+ composio?: {+ appSlug: string;+ connectedAccountId: string;+ ownerUserId: string;+ status: string;+ };+ isEnabled: boolean;+ status: string;+ },+ provider: 'github' | 'gmail',+) =>+ isActiveReference(reference) &&+ reference.composio?.appSlug.slice(0, 32).toLowerCase() === provider &&+ reference.composio.status.slice(0, 32).toUpperCase() === 'ACTIVE' &&+ reference.composio.connectedAccountId.length > 0 &&+ reference.composio.connectedAccountId.length <= 512 &&+ reference.composio.ownerUserId.length > 0 &&+ reference.composio.ownerUserId.length <= 512;+const isTokenUsable = (expiresAt: Date | number | null | undefined) =>expiresAt == null ||(expiresAt instanceof Date ? expiresAt.getTime() : expiresAt) > Date.now() + TOKEN_EXPIRY_SKEW_MS;+/**+ * Resolves authenticated connector-data clients for one user and workspace scope.+ *+ * Use when:+ * - A server workflow needs provider data without handling credential storage+ * - Provider availability must reflect persisted connector health+ *+ * Expects:+ * - The database and user scope come from an authenticated server context+ *+ * Returns:+ * - Provider clients backed by Composio, connector OAuth, or supported account fallback+ */export class ConnectorDataService {constructor(private readonly db: LobeChatDatabase,@@ -36,39 +80,89 @@ export class ConnectorDataService {private readonly workspaceId?: string,) {}+ /**+ * Lists provider identifiers with a connector client that can be resolved now.+ *+ * Use when:+ * - A workflow must exclude disconnected or remotely deleted sources before initialization+ *+ * Expects:+ * - Provider identifiers supported by Connector Data+ *+ * Returns:+ * - Available identifiers in the caller's original order+ */+ listAvailableProviderIds = async (providerIds: readonly string[]): Promise<string[]> => {+ const availability = await Promise.all(+ providerIds.map(async (providerId) => {+ const provider = providerId === 'github' || providerId === 'gmail' ? providerId : undefined;+ if (!provider) return;++ try {+ if (provider === 'github') await this.getGitHubClient();+ else await this.getGmailClient();+ return provider;+ } catch (error) {+ if (isConfirmedProviderUnavailableError(error, provider)) return;+ throw error;+ }+ }),+ );+ return availability.filter(+ (providerId): providerId is 'github' | 'gmail' => providerId !== undefined,+ );+ };+getGitHubClient = async (): Promise<GitHubConnectorClient> => {const referenceModel = new ConnectorModel(this.db, this.userId, this.workspaceId);++ const composioReferences = (+ await referenceModel.queryComposioReferencesByIdentifiers(['github'])+ )+ .filter((reference) => isActiveComposioReference(reference, 'github'))+ .toSorted((left, right) => left.id.localeCompare(right.id));+ for (const reference of composioReferences) {+ const metadata = reference.composio;+ if (!metadata) continue;+ try {+ const composio = getComposioClient();+ const connectedAccount = await composio.connectedAccounts.get(metadata.connectedAccountId);+ if (connectedAccount.status !== 'ACTIVE') continue;+ return createGitHubComposioConnectorClient({+ composio,+ connectedAccountId: metadata.connectedAccountId,+ });+ } catch (error) {+ if (!isComposioConnectedAccountLookupNotFoundError(error)) throw error;+ await referenceModel.markComposioConnectionUnavailable(+ reference.id,+ metadata.connectedAccountId,+ );+ }+ }+const references = (await referenceModel.queryReferencesByIdentifiers(['github'])).filter(isActiveReference).toSorted((left, right) => left.id.localeCompare(right.id));if (references.length > 0) {- try {- const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();- const connectorModel = new ConnectorModel(- this.db,- this.userId,- this.workspaceId,- gateKeeper,- );- for (const reference of references) {- const connector = await connectorModel.findById(reference.id);- if (!connector || connector.identifier !== 'github' || !isActiveReference(connector)) {- continue;- }- const fresh = await ensureFreshConnectorToken(connector, connectorModel);- const credentials = fresh.credentials;- if (- credentials?.type === 'oauth2' &&- typeof credentials.accessToken === 'string' &&- credentials.accessToken.length > 0 &&- isTokenUsable(credentials.expiresAt ?? fresh.tokenExpiresAt)- ) {- return createGitHubConnectorClient({ accessToken: credentials.accessToken });- }+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();+ const connectorModel = new ConnectorModel(this.db, this.userId, this.workspaceId, gateKeeper);+ for (const reference of references) {+ const connector = await connectorModel.findById(reference.id);+ if (!connector || connector.identifier !== 'github' || !isActiveReference(connector)) {+ continue;+ }+ const fresh = await ensureFreshConnectorToken(connector, connectorModel);+ const credentials = fresh.credentials;+ if (+ credentials?.type === 'oauth2' &&+ typeof credentials.accessToken === 'string' &&+ credentials.accessToken.length > 0 &&+ isTokenUsable(credentials.expiresAt ?? fresh.tokenExpiresAt)+ ) {+ return createGitHubOAuthConnectorClient({ accessToken: credentials.accessToken });}- } catch {- // A connector that cannot be decrypted is unusable; personal OAuth remains a valid fallback.}}@@ -89,7 +183,7 @@ export class ConnectorDataService {isTokenUsable(accessTokenExpiresAt),);if (authAccount?.accessToken) {- return createGitHubConnectorClient({ accessToken: authAccount.accessToken });+ return createGitHubOAuthConnectorClient({ accessToken: authAccount.accessToken });}throw unavailable('github');};@@ -97,31 +191,39 @@ export class ConnectorDataService {getGmailClient = async (): Promise<GmailConnectorClient> => {const connectorModel = new ConnectorModel(this.db, this.userId, this.workspaceId);const references = (await connectorModel.queryComposioReferencesByIdentifiers(['gmail']))- .filter(- (reference) =>- isActiveReference(reference) &&- reference.composio?.appSlug.slice(0, 32).toLowerCase() === 'gmail' &&- reference.composio.status.slice(0, 32).toUpperCase() === 'ACTIVE' &&- reference.composio.connectedAccountId.length > 0 &&- reference.composio.connectedAccountId.length <= 512 &&- reference.composio.ownerUserId.length > 0 &&- reference.composio.ownerUserId.length <= 512,- )+ .filter((reference) => isActiveComposioReference(reference, 'gmail')).toSorted((left, right) => left.id.localeCompare(right.id));for (const reference of references) {const composio = reference.composio;if (!composio) continue;try {+ const composioClient = getComposioClient();+ await composioClient.connectedAccounts.get(composio.connectedAccountId);const client = createGmailConnectorClient({- composio: getComposioClient(),+ composio: composioClient,connectedAccountId: composio.connectedAccountId,userId: composio.ownerUserId,});await client.getAccount();return client;} catch (error) {- if (error instanceof ConnectorDataError && error.retryable) throw error;+ if (isComposioConnectedAccountLookupNotFoundError(error)) {+ await connectorModel.markComposioConnectionUnavailable(+ reference.id,+ composio.connectedAccountId,+ );+ continue;+ }+ if (+ error instanceof ConnectorDataError &&+ error.provider === 'gmail' &&+ error.code === 'gmail_account_unavailable' &&+ !error.retryable+ ) {+ continue;+ }+ throw error;}}throw unavailable('gmail');diff --git a/apps/server/src/services/understanding/service.test.ts b/apps/server/src/services/understanding/service.test.tsindex 3b2341a16f3..0ef4b6eb304 100644--- a/apps/server/src/services/understanding/service.test.ts+++ b/apps/server/src/services/understanding/service.test.ts@@ -248,8 +248,13 @@ const createHarness = (initialSession?: OnboardingUnderstandingSession) => {})),findLatestAssistantMessageByThread: vi.fn(async () => latestAssistant),};+ const listAvailableProviderIds = vi.fn(async (providerIds: readonly string[]) => [+ ...providerIds,+ ]);const dependencies: UnderstandingServiceDependencies = {- connectorData: {} as UnderstandingServiceDependencies['connectorData'],+ connectorData: {+ listAvailableProviderIds,+ } as unknown as UnderstandingServiceDependencies['connectorData'],generator: {generateObject:generateObject as UnderstandingServiceDependencies['generator']['generateObject'],@@ -271,6 +276,7 @@ const createHarness = (initialSession?: OnboardingUnderstandingSession) => {dependencies,githubCollect,generateObject,+ listAvailableProviderIds,messages,repository,service: new UnderstandingService(dependencies),@@ -409,6 +415,46 @@ describe('UnderstandingService', () => {);});+ /**+ * @example+ * expect(result.sources.gmail).toBeUndefined();+ */+ it('excludes providers whose connector client is unavailable before initialization', async () => {+ const harness = createHarness();+ harness.listAvailableProviderIds.mockResolvedValueOnce(['github']);++ await expect(harness.service.start('topic-1', 'zh-CN')).resolves.toMatchObject({+ sources: { github: { status: 'pending' } },+ });++ expect(harness.repository.initialize).toHaveBeenCalledWith('topic-1', 'session-new', [+ 'github',+ ]);+ expect(mockTriggerProviders).toHaveBeenCalledWith(+ expect.objectContaining({ providers: [{ id: 'github', revision: 1 }] }),+ expect.any(Object),+ );+ });++ /** @example A temporary availability failure leaves no persisted Understanding session. */+ it('does not initialize a session when provider availability fails transiently', async () => {+ // ROOT CAUSE:+ //+ // Persisting after a transient availability failure creates an incomplete immutable session.+ // Later starts return that existing session and never retry provider initialization.+ //+ // Before: transient errors were converted into an unavailable provider list downstream.+ // We fixed this by propagating the error before repository initialization.+ const harness = createHarness();+ const transientError = new Error('database temporarily unavailable');+ harness.listAvailableProviderIds.mockRejectedValueOnce(transientError);++ await expect(harness.service.start('topic-1', 'zh-CN')).rejects.toBe(transientError);++ expect(harness.repository.initialize).not.toHaveBeenCalled();+ expect(mockTriggerProviders).not.toHaveBeenCalled();+ });+/*** @example* expect(result.sources.gmail).toBeUndefined();@@ -430,6 +476,27 @@ describe('UnderstandingService', () => {);});+ /**+ * @example+ * expect(result.sources.gmail.status).toBe('failed');+ */+ it('does not retry a failed provider whose connector is no longer available', async () => {+ const harness = createHarness(createSession({ gmail: providerState('failed', 1) }));+ harness.listAvailableProviderIds.mockResolvedValueOnce([]);++ await expect(+ harness.service.retry({+ providerId: 'gmail',+ responseLanguage: 'zh-CN',+ sessionId: 'session-1',+ topicId: 'topic-1',+ }),+ ).resolves.toMatchObject({ sources: { gmail: { status: 'failed' } } });++ expect(harness.repository.markProviderRunning).not.toHaveBeenCalled();+ expect(mockTriggerProviders).not.toHaveBeenCalled();+ });+it('stores one exact provider revision and returns its completion fingerprint', async () => {const harness = createHarness(createSession({ github: providerState('pending', 0), gmail: providerState('running', 1) }),diff --git a/apps/server/src/services/understanding/service.ts b/apps/server/src/services/understanding/service.tsindex 098682b38f2..3d4c977361d 100644--- a/apps/server/src/services/understanding/service.ts+++ b/apps/server/src/services/understanding/service.ts@@ -218,6 +218,24 @@ const storedProposal = (metadata: unknown) => {export class UnderstandingService {constructor(private readonly dependencies: UnderstandingServiceDependencies) {}+ /**+ * Lists Understanding providers backed by a currently resolvable connector client.+ *+ * Use when:+ * - The onboarding UI needs to distinguish supported apps from usable data sources+ * - Session initialization must exclude disconnected or remotely deleted connectors+ *+ * Expects:+ * - The service dependencies are scoped to the authenticated user+ *+ * Returns:+ * - Available provider identifiers in deterministic provider-map order+ */+ listSourceProviderIds = async (): Promise<string[]> =>+ this.dependencies.connectorData.listAvailableProviderIds([+ ...this.dependencies.providers.keys(),+ ]);+private initialize = async (topicId: string,selectedProviderIds?: string[],@@ -225,12 +243,16 @@ export class UnderstandingService {await this.dependencies.topic.assertActiveOnboardingTopic(topicId);const current = await this.dependencies.repository.get(topicId);if (current) return current;- const providerIds = selectedProviderIds+ const requestedProviderIds = selectedProviderIds? [...new Set(selectedProviderIds)].sort(): [...this.dependencies.providers.keys()].sort();- if (providerIds.some((providerId) => !this.dependencies.providers.has(providerId))) {+ if (requestedProviderIds.some((providerId) => !this.dependencies.providers.has(providerId))) {throw new UnderstandingResourceNotFoundError('session');}+ const availableProviderIds = new Set(await this.listSourceProviderIds());+ const providerIds = requestedProviderIds.filter((providerId) =>+ availableProviderIds.has(providerId),+ );return this.dependencies.repository.initialize(topicId, this.dependencies.ids(), providerIds);};@@ -269,10 +291,14 @@ export class UnderstandingService {await import('@/server/workflows/onboardingUnderstanding');OnboardingUnderstandingWorkflow.assertAvailable();const current = await this.activeSession(input.topicId, input.sessionId);- const providerIds = [...new Set(input.providerIds)].sort();- if (providerIds.some((providerId) => !this.dependencies.providers.has(providerId))) {+ const requestedProviderIds = [...new Set(input.providerIds)].sort();+ if (requestedProviderIds.some((providerId) => !this.dependencies.providers.has(providerId))) {throw new UnderstandingResourceNotFoundError('session');}+ const availableProviderIds = new Set(await this.listSourceProviderIds());+ const providerIds = requestedProviderIds.filter(+ (providerId) => current.sources[providerId] || availableProviderIds.has(providerId),+ );const next = await this.dependencies.repository.extend({expectedFeedbackRevision: input.expectedFeedbackRevision,@@ -402,6 +428,10 @@ export class UnderstandingService {if (state.status !== 'failed') {throw new UnderstandingPreconditionError('source_not_retryable');}+ const availableProviderIds = await this.dependencies.connectorData.listAvailableProviderIds([+ input.providerId,+ ]);+ if (!availableProviderIds.includes(input.providerId)) return this.get(input.topicId);const { revision } = await this.dependencies.repository.markProviderRunning(input.topicId,input.sessionId,diff --git a/packages/connector-data/src/github/client-composio.test.ts b/packages/connector-data/src/github/client-composio.test.tsnew file mode 100644index 00000000000..295dc639367--- /dev/null+++ b/packages/connector-data/src/github/client-composio.test.ts@@ -0,0 +1,112 @@+import { describe, expect, it, vi } from 'vitest';++import {+ createGitHubComposioConnectorClient,+ createGitHubComposioTransport,+ type GitHubComposioProxyRequest,+} from './client-composio';++const createProxy = () =>+ vi.fn(async (input: GitHubComposioProxyRequest): Promise<unknown> => {+ if (input.endpoint === '/user') {+ return { data: { id: 98_765, login: 'octocat' }, status: 200 };+ }+ if (input.endpoint === '/user/orgs') {+ return {+ data: [{ description: 'Making AI accessible.', login: 'lobehub' }],+ status: 200,+ };+ }+ if (input.endpoint === '/repos/lobehub/lobehub/contributors') {+ return { data: [{ contributions: 12, login: 'octocat' }], status: 200 };+ }+ if (input.endpoint === '/graphql') {+ const body = input.body as { query?: string };+ if (body.query?.includes('ConnectorDataGitHubProfile')) {+ return {+ data: {+ data: {+ viewer: {+ bio: 'Building tools.',+ company: '@lobehub',+ location: 'Shanghai',+ login: 'octocat',+ name: 'Octocat',+ pronouns: 'they/them',+ websiteUrl: 'https://lobehub.com',+ },+ },+ },+ status: 200,+ };+ }+ return { data: { data: { viewer: { login: 'octocat' } } }, status: 200 };+ }+ throw new Error(`Unexpected endpoint: ${input.endpoint}`);+ });++describe('createGitHubComposioTransport', () => {+ /**+ * @example+ * Composio injects OAuth credentials while the adapter preserves the existing+ * GitHub transport response shapes.+ */+ it('maps authenticated REST and GraphQL proxy responses into the shared transport', async () => {+ const proxyExecute = createProxy();+ const transport = createGitHubComposioTransport({+ composio: { tools: { proxyExecute } },+ connectedAccountId: 'ca-github',+ });++ /** @example `/user` becomes the minimal authenticated-user identity. */+ await expect(transport.getAuthenticatedUser()).resolves.toEqual({+ id: 98_765,+ login: 'octocat',+ });+ /** @example `/user/orgs` retains the organization fields consumed by the loader. */+ await expect(transport.listUserOrganizations({ perPage: 20 })).resolves.toEqual([+ { description: 'Making AI accessible.', login: 'lobehub' },+ ]);+ /** @example Repository path segments and pagination are proxied without credentials. */+ await expect(+ transport.listRepositoryContributors({+ owner: 'lobehub',+ perPage: 5,+ repository: 'lobehub',+ }),+ ).resolves.toEqual([{ contributions: 12, login: 'octocat' }]);+ /** @example GraphQL unwraps the GitHub response envelope for existing Zod schemas. */+ await expect(+ transport.request({ operation: 'Test', query: 'query { viewer { login } }', variables: {} }),+ ).resolves.toEqual({ viewer: { login: 'octocat' } });+ /** @example Every request is scoped to the server-resolved connected account. */+ expect(+ proxyExecute.mock.calls.every(([input]) => input.connectedAccountId === 'ca-github'),+ ).toBe(true);+ });+});++describe('createGitHubComposioConnectorClient', () => {+ /**+ * @example+ * Callers receive the same `GitHubConnectorClient` profile contract as native OAuth.+ */+ it('composes the Composio adapter behind the shared client interface', async () => {+ const client = createGitHubComposioConnectorClient({+ composio: { tools: { proxyExecute: createProxy() } },+ connectedAccountId: 'ca-github',+ });++ /** @example The normalized profile contract is independent of the auth provider. */+ await expect(client.getUserProfile()).resolves.toEqual({+ bio: 'Building tools.',+ company: '@lobehub',+ externalAccountId: '98765',+ location: 'Shanghai',+ login: 'octocat',+ name: 'Octocat',+ pronouns: 'they/them',+ websiteUrl: 'https://lobehub.com',+ });+ });+});diff --git a/packages/connector-data/src/github/client-composio.ts b/packages/connector-data/src/github/client-composio.tsnew file mode 100644index 00000000000..9026c0ef5f2--- /dev/null+++ b/packages/connector-data/src/github/client-composio.ts@@ -0,0 +1,175 @@+import { toRecord } from '@lobechat/utils/object';++import { createRecoverableMemo } from '../memo';+import { createGitHubConnectorClient, type GitHubConnectorClient } from './client';+import type { GitHubConnectorTransport } from './graphql/client';++/** A query or header parameter accepted by Composio proxy execution. */+export interface GitHubComposioProxyParameter {+ /** Where Composio should add the parameter. */+ in: 'header' | 'query';+ /** HTTP parameter name. */+ name: string;+ /** HTTP parameter value. */+ value: number | string;+}++/** Request shape used to proxy an authenticated GitHub API call through Composio. */+export interface GitHubComposioProxyRequest {+ /** Optional JSON request body. */+ body?: unknown;+ /** Server-resolved Composio connected account identifier. */+ connectedAccountId: string;+ /** Relative GitHub API endpoint. */+ endpoint: string;+ /** HTTP method supported by Composio proxy execution. */+ method: 'DELETE' | 'GET' | 'PATCH' | 'POST' | 'PUT';+ /** Optional query and header parameters. */+ parameters?: GitHubComposioProxyParameter[];+}++/** Minimal Composio tools interface required by the GitHub adapter. */+export interface GitHubComposioTools {+ /** Proxies one authenticated GitHub HTTP request. */+ proxyExecute: (input: GitHubComposioProxyRequest) => Promise<unknown>;+}++/** Minimal Composio client interface required by the GitHub adapter. */+export interface GitHubComposioClient {+ /** Composio tool execution surface. */+ tools: GitHubComposioTools;+}++/** Configuration shared by the Composio transport and connector factories. */+export interface CreateGitHubComposioConnectorClientOptions {+ /** Composio SDK client or compatible test adapter. */+ composio: GitHubComposioClient;+ /** Connected account resolved from the authenticated user's connector row. */+ connectedAccountId: string;+}++interface ComposioProxyResponse {+ data: unknown;+ status: number;+}++const parseProxyResponse = (value: unknown): ComposioProxyResponse => {+ if (typeof value !== 'object' || value === null) {+ throw new Error('GitHub Composio proxy response is invalid');+ }++ const response = value as { data?: unknown; status?: unknown };+ if (typeof response.status !== 'number' || !Number.isFinite(response.status)) {+ throw new Error('GitHub Composio proxy status is invalid');+ }+ if (response.status < 200 || response.status >= 300) {+ throw Object.assign(new Error('GitHub Composio proxy request failed'), {+ status: response.status,+ });+ }++ return { data: response.data, status: response.status };+};++/**+ * Creates a GitHub transport that keeps OAuth credentials inside Composio.+ *+ * Use when:+ * - A connector stores only a Composio connected-account identifier+ * - Existing GitHub loaders should run unchanged across REST and GraphQL+ *+ * Expects:+ * - The connected account belongs to the authenticated connector scope+ * - Composio resolves relative endpoints against GitHub's API base URL+ *+ * Returns:+ * - A transport compatible with the native OAuth GitHub connector+ */+export const createGitHubComposioTransport = ({+ composio,+ connectedAccountId,+}: CreateGitHubComposioConnectorClientOptions): GitHubConnectorTransport => {+ const proxy = async (+ input: Omit<GitHubComposioProxyRequest, 'connectedAccountId'>,+ ): Promise<unknown> => {+ // Composio injects the remote OAuth credential. The adapter sends only a+ // server-resolved account ID and never receives or logs the credential.+ const response = await composio.tools.proxyExecute({ ...input, connectedAccountId });+ return parseProxyResponse(response).data;+ };+ const getAuthenticatedUser = createRecoverableMemo(async () => {+ const user = toRecord(await proxy({ endpoint: '/user', method: 'GET' }));+ const id = user?.id;+ const login = user?.login;+ if ((typeof id !== 'number' && typeof id !== 'string') || typeof login !== 'string') {+ throw new Error('GitHub Composio authenticated user response is invalid');+ }+ return { id, login };+ });++ return {+ getAuthenticatedUser,+ listRepositoryContributors: async ({ owner, perPage, repository }) => {+ const data = await proxy({+ endpoint: `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repository)}/contributors`,+ method: 'GET',+ parameters: [{ in: 'query', name: 'per_page', value: perPage }],+ });+ if (!Array.isArray(data)) {+ throw new Error('GitHub Composio contributor response is invalid');+ }+ return data.map((item) => {+ const record = toRecord(item);+ return {+ contributions:+ typeof record?.contributions === 'number' ? record.contributions : undefined,+ login: typeof record?.login === 'string' ? record.login : null,+ };+ });+ },+ listUserOrganizations: async ({ perPage }) => {+ const data = await proxy({+ endpoint: '/user/orgs',+ method: 'GET',+ parameters: [{ in: 'query', name: 'per_page', value: perPage }],+ });+ if (!Array.isArray(data)) {+ throw new Error('GitHub Composio organization response is invalid');+ }+ return data.map((item) => {+ const record = toRecord(item);+ return {+ description: typeof record?.description === 'string' ? record.description : null,+ login: typeof record?.login === 'string' ? record.login : null,+ };+ });+ },+ request: async ({ query, variables }) => {+ const envelope = toRecord(+ await proxy({+ body: { query, variables },+ endpoint: '/graphql',+ method: 'POST',+ parameters: [{ in: 'header', name: 'Accept', value: 'application/vnd.github+json' }],+ }),+ );+ if (Array.isArray(envelope?.errors) && envelope.errors.length > 0) {+ throw Object.assign(new Error('GitHub Composio GraphQL request failed'), {+ errors: envelope.errors,+ });+ }+ if (!envelope || !('data' in envelope)) {+ throw new Error('GitHub Composio GraphQL response is invalid');+ }+ return envelope.data;+ },+ };+};++/**+ * Creates the Composio implementation of the shared GitHub connector interface.+ */+export const createGitHubComposioConnectorClient = (+ options: CreateGitHubComposioConnectorClientOptions,+): GitHubConnectorClient =>+ createGitHubConnectorClient({ transport: createGitHubComposioTransport(options) });diff --git a/packages/connector-data/src/github/client-oauth.ts b/packages/connector-data/src/github/client-oauth.tsnew file mode 100644index 00000000000..49904ef823d--- /dev/null+++ b/packages/connector-data/src/github/client-oauth.ts@@ -0,0 +1,18 @@+import { createGitHubConnectorClient, type GitHubConnectorClient } from './client';+import { createOctokitTransport } from './graphql/client';++/**+ * Configuration for a GitHub connector backed by a directly held OAuth token.+ */+export interface CreateGitHubOAuthConnectorClientOptions {+ /** GitHub OAuth access token used only inside the Octokit transport. */+ accessToken: string;+}++/**+ * Creates the native OAuth implementation of the shared GitHub connector interface.+ */+export const createGitHubOAuthConnectorClient = ({+ accessToken,+}: CreateGitHubOAuthConnectorClientOptions): GitHubConnectorClient =>+ createGitHubConnectorClient({ transport: createOctokitTransport(accessToken) });diff --git a/packages/connector-data/src/github/client.test.ts b/packages/connector-data/src/github/client.test.tsindex c9bcf6aaa96..0eb31863e38 100644--- a/packages/connector-data/src/github/client.test.ts+++ b/packages/connector-data/src/github/client.test.ts@@ -1,6 +1,7 @@import { afterEach, describe, expect, it, vi } from 'vitest';import { createGitHubConnectorClient } from './client';+import { createGitHubOAuthConnectorClient } from './client-oauth';import type { GitHubConnectorTransport } from './graphql/client';const profileResult = {@@ -125,7 +126,7 @@ describe('createGitHubConnectorClient', () => {it('returns a normalized authenticated user profile', async () => {const { calls, transport } = createTransport();- const client = createGitHubConnectorClient({ accessToken: 'test-token', transport });+ const client = createGitHubConnectorClient({ transport });await expect(client.getUserProfile()).resolves.toEqual({bio: 'Building tools.',@@ -143,14 +144,13 @@ describe('createGitHubConnectorClient', () => {variables: {},},]);- expect(JSON.stringify(calls)).not.toContain('test-token');});it('lists normalized repository and contribution resources', async () => {vi.useFakeTimers();vi.setSystemTime('2026-07-17T12:34:56.789Z');const { calls, transport } = createTransport();- const client = createGitHubConnectorClient({ accessToken: 'test-token', transport });+ const client = createGitHubConnectorClient({ transport });await expect(client.listPinnedRepositories()).resolves.toEqual([{@@ -211,7 +211,7 @@ describe('createGitHubConnectorClient', () => {it('deduplicates concurrent repository requests', async () => {const { calls, transport } = createTransport();- const client = createGitHubConnectorClient({ accessToken: 'test-token', transport });+ const client = createGitHubConnectorClient({ transport });await Promise.all([client.listPinnedRepositories(), client.listRecentRepositories()]);@@ -234,7 +234,7 @@ describe('createGitHubConnectorClient', () => {listUserOrganizations: async () => [],request,};- const client = createGitHubConnectorClient({ accessToken: 'test-token', transport });+ const client = createGitHubConnectorClient({ transport });const first = client.getUserProfile();const firstRejection = expect(first).rejects.toMatchObject({ retryable: true });@@ -248,7 +248,7 @@ describe('createGitHubConnectorClient', () => {it('normalizes and bounds repository contributors in the loader', async () => {const { listRepositoryContributors, transport } = createTransport();- const client = createGitHubConnectorClient({ accessToken: 'test-token', transport });+ const client = createGitHubConnectorClient({ transport });await expect(client.listRepositoryContributors('lobehub/lobehub')).resolves.toEqual([{ contributionCount: 9, login: 'octocat' },@@ -276,7 +276,7 @@ describe('createGitHubConnectorClient', () => {listUserOrganizations: async () => [],request: vi.fn(),};- const client = createGitHubConnectorClient({ accessToken: 'test-token', transport });+ const client = createGitHubConnectorClient({ transport });const error = await client.listRepositoryContributors(sensitiveRepository)@@ -291,7 +291,7 @@ describe('createGitHubConnectorClient', () => {it('lists normalized organizations', async () => {const { listUserOrganizations, transport } = createTransport();- const client = createGitHubConnectorClient({ accessToken: 'test-token', transport });+ const client = createGitHubConnectorClient({ transport });await expect(client.listUserOrganizations()).resolves.toEqual([{@@ -306,7 +306,7 @@ describe('createGitHubConnectorClient', () => {it('loads the profile README using the authenticated login', async () => {const { calls, transport } = createTransport();- const client = createGitHubConnectorClient({ accessToken: 'test-token', transport });+ const client = createGitHubConnectorClient({ transport });await expect(client.getUserProfileReadme()).resolves.toBe('# Octocat\nBuild useful tools.');expect(calls).toContainEqual({@@ -331,7 +331,7 @@ describe('createGitHubConnectorClient', () => {});});vi.stubGlobal('fetch', fetch);- const client = createGitHubConnectorClient({ accessToken: 'production-token' });+ const client = createGitHubOAuthConnectorClient({ accessToken: 'production-token' });await expect(client.getUserProfile()).resolves.toMatchObject({externalAccountId: '1',@@ -374,7 +374,7 @@ describe('createGitHubConnectorClient', () => {return new Response(null, { status: 404 });});vi.stubGlobal('fetch', fetch);- const client = createGitHubConnectorClient({ accessToken: 'production-token' });+ const client = createGitHubOAuthConnectorClient({ accessToken: 'production-token' });await expect(client.listUserOrganizations()).resolves.toEqual([{ description: 'Making AI accessible.', login: 'lobehub' },diff --git a/packages/connector-data/src/github/client.ts b/packages/connector-data/src/github/client.tsindex 8f6cff56bf6..fd36e2263d5 100644--- a/packages/connector-data/src/github/client.ts+++ b/packages/connector-data/src/github/client.ts@@ -1,6 +1,6 @@import { createRecoverableMemo } from '../memo';import type { GitHubConnectorTransport } from './graphql/client';-import { createGitHubGraphQLClient, createOctokitTransport } from './graphql/client';+import { createGitHubGraphQLClient } from './graphql/client';import {loadContributions,loadOrganizations,@@ -31,15 +31,25 @@ export interface GitHubConnectorClient {}export interface CreateGitHubConnectorClientOptions {- accessToken: string;- /** @internal Tests and custom protocol adapters only. */- transport?: GitHubConnectorTransport;+ /** Authentication and protocol adapter used by the shared GitHub data loaders. */+ transport: GitHubConnectorTransport;}-export const createGitHubConnectorClient = ({- accessToken,- transport = createOctokitTransport(accessToken),-}: CreateGitHubConnectorClientOptions): GitHubConnectorClient => {+/**+ * Creates a GitHub connector from a required transport adapter.+ *+ * Use when:+ * - A provider adapter supplies the shared REST and GraphQL transport contract+ *+ * Expects:+ * - A fully initialized transport; authentication is handled by the provider adapter+ *+ * Returns:+ * - The stable domain-level GitHub connector interface+ */+export function createGitHubConnectorClient({+ transport,+}: CreateGitHubConnectorClientOptions): GitHubConnectorClient {const graphqlClient = createGitHubGraphQLClient(transport);const getProfileBundle = createRecoverableMemo(() => loadProfileBundle(graphqlClient));const getRepositories = createRecoverableMemo(() => loadRepositories(graphqlClient));@@ -57,4 +67,4 @@ export const createGitHubConnectorClient = ({listRepositoryContributors: (repository) => loadRepositoryContributors(transport, repository),listUserOrganizations: () => loadOrganizations(transport),};-};+}diff --git a/packages/connector-data/src/github/index.ts b/packages/connector-data/src/github/index.tsindex e42a3160262..fe158aa0f9a 100644--- a/packages/connector-data/src/github/index.ts+++ b/packages/connector-data/src/github/index.ts@@ -1,3 +1,5 @@export * from './client';+export * from './client-composio';+export * from './client-oauth';export * from './formatter';export * from './types';diff --git a/packages/database/src/models/__tests__/connector.test.ts b/packages/database/src/models/__tests__/connector.test.tsindex c19a04ac624..03a179e7df0 100644--- a/packages/database/src/models/__tests__/connector.test.ts+++ b/packages/database/src/models/__tests__/connector.test.ts@@ -485,6 +485,86 @@ describe('ConnectorModel', () => {});});+ describe('markComposioConnectionUnavailable', () => {+ /**+ * @example+ * A provider boundary confirms a deleted Composio account and transitions the connector+ * from ACTIVE/connected to FAILED/error without disabling the user's toggle.+ */+ it('marks a Composio connector unavailable when the remote account no longer exists', async () => {+ const model = new ConnectorModel(serverDB, userId);+ const created = await model.create({+ identifier: 'gmail',+ isEnabled: true,+ metadata: {+ composio: {+ appSlug: 'gmail',+ authConfigId: 'auth-config',+ connectedAccountId: 'ca-deleted',+ linkedByUserId: userId,+ status: 'ACTIVE',+ },+ description: 'preserved metadata',+ },+ name: 'Gmail',+ sourceType: 'marketplace',+ status: 'connected',+ });+ const handled = await model.markComposioConnectionUnavailable(created.id, 'ca-deleted');++ const found = await model.findById(created.id);+ /** @example A scoped state transition returns true once it is persisted. */+ expect(handled).toBe(true);+ /** @example The connector is excluded from active source resolution. */+ expect(found?.status).toBe('error');+ /** @example Remote health does not overwrite the user's enabled preference. */+ expect(found?.isEnabled).toBe(true);+ /** @example Composio-specific health is projected into metadata for runtime readers. */+ expect(found?.metadata?.composio?.status).toBe('FAILED');+ /** @example Unrelated metadata survives the health transition. */+ expect(found?.metadata?.description).toBe('preserved metadata');+ });++ /**+ * @example+ * A request for the replaced account cannot mark the newly connected account unavailable.+ */+ it('does not mark a replacement Composio account from a stale failure', async () => {+ // ROOT CAUSE:+ //+ // Reconnect updates the existing connector row with a new connectedAccountId.+ // An in-flight failure for the previous account used to update that row by ID alone.+ //+ // Before: the replacement account became FAILED/error.+ // We fixed this by matching the failed connectedAccountId in the health UPDATE.+ const model = new ConnectorModel(serverDB, userId);+ const created = await model.create({+ identifier: 'github',+ isEnabled: true,+ metadata: {+ composio: {+ appSlug: 'github',+ authConfigId: 'auth-config',+ connectedAccountId: 'ca-current',+ linkedByUserId: userId,+ status: 'ACTIVE',+ },+ },+ name: 'GitHub',+ sourceType: 'marketplace',+ status: 'connected',+ });++ const handled = await model.markComposioConnectionUnavailable(created.id, 'ca-previous');+ const found = await model.findById(created.id);++ expect(handled).toBe(false);+ expect(found?.status).toBe('connected');+ expect(found?.metadata?.composio?.connectedAccountId).toBe('ca-current');+ expect(found?.metadata?.composio?.status).toBe('ACTIVE');+ });+ });+describe('delete', () => {it('deletes a connector owned by the user', async () => {const model = new ConnectorModel(serverDB, userId);diff --git a/packages/database/src/models/connector.ts b/packages/database/src/models/connector.tsindex 2978f10e33d..33920f6b622 100644--- a/packages/database/src/models/connector.ts+++ b/packages/database/src/models/connector.ts@@ -1,12 +1,7 @@import { and, eq, inArray, isNotNull, isNull, or, sql } from 'drizzle-orm';-import type {- ConnectorCredentials,- ConnectorStatus,- NewUserConnector,- UserConnectorItem,-} from '../schemas';-import { userConnectors, userConnectorTools } from '../schemas';+import type { ConnectorCredentials, NewUserConnector, UserConnectorItem } from '../schemas';+import { ConnectorStatus, userConnectors, userConnectorTools } from '../schemas';import type { LobeChatDatabase } from '../type';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';@@ -409,6 +404,55 @@ export class ConnectorModel {.set({ status, updatedAt: new Date() }).where(and(eq(userConnectors.id, id), this.ownership()));};++ /**+ * Persists a terminal Composio connection-not-found health failure.+ *+ * Use when:+ * - A provider boundary has confirmed that the remote connection no longer exists+ *+ * Expects:+ * - `id` belongs to this model's user/workspace scope+ * - `connectedAccountId` identifies the remote account that produced the failure+ * - The caller has already normalized provider-specific error semantics+ *+ * Returns:+ * - `true` when a scoped Composio connector was transitioned to FAILED/error+ * - `false` for missing rows or non-Composio connectors+ */+ markComposioConnectionUnavailable = async (+ id: string,+ connectedAccountId: string,+ ): Promise<boolean> => {+ const [connector] = await this.db+ .select({ metadata: userConnectors.metadata })+ .from(userConnectors)+ .where(and(eq(userConnectors.id, id), this.ownership()))+ .limit(1);+ const composio = connector?.metadata?.composio;+ if (!connector || !composio) return false;++ const updated = await this.db+ .update(userConnectors)+ .set({+ metadata: {+ ...connector.metadata,+ composio: { ...composio, status: 'FAILED' },+ },+ status: ConnectorStatus.error,+ updatedAt: new Date(),+ })+ .where(+ and(+ eq(userConnectors.id, id),+ this.ownership(),+ sql`${userConnectors.metadata}->'composio'->>'connectedAccountId' = ${connectedAccountId}`,+ ),+ )+ .returning({ id: userConnectors.id });++ return updated.length > 0;+ };}// ββ Private helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdiff --git a/src/libs/composio/index.test.ts b/src/libs/composio/index.test.tsnew file mode 100644index 00000000000..68cae920b76--- /dev/null+++ b/src/libs/composio/index.test.ts@@ -0,0 +1,43 @@+import { ComposioConnectedAccountNotFoundError, ComposioToolExecutionError } from '@composio/core';+import { describe, expect, it } from 'vitest';++import {+ isComposioConnectedAccountLookupNotFoundError,+ isComposioConnectedAccountNotFoundError,+} from './index';++describe('isComposioConnectedAccountNotFoundError', () => {+ /** @example A normalized SDK error is recognized by its concrete class. */+ it('recognizes the Composio connected-account error class', () => {+ expect(+ isComposioConnectedAccountNotFoundError(new ComposioConnectedAccountNotFoundError()),+ ).toBe(true);+ });++ /** @example A raw tool HTTP 404 is not sufficient proof that the account is missing. */+ it('does not classify a direct HTTP 404 outside an account lookup', () => {+ // ROOT CAUSE:+ //+ // A valid tool can return HTTP 404 for a missing provider resource.+ // Treating every direct 404 as an account failure disables a healthy connector.+ //+ // Before: the shared predicate returned true for any direct status 404.+ // We fixed this by reserving raw HTTP matching for the account lookup boundary.+ expect(isComposioConnectedAccountNotFoundError({ status: 404 })).toBe(false);+ });++ /** @example connectedAccounts.get may expose the generated client's HTTP status directly. */+ it('recognizes a direct HTTP 404 at the connected-account lookup boundary', () => {+ expect(isComposioConnectedAccountLookupNotFoundError({ status: 404 })).toBe(true);+ });++ /** @example Unrelated wrapped errors are not recursively interpreted by this boundary. */+ it('does not classify unrelated or causally nested errors', () => {+ expect(isComposioConnectedAccountNotFoundError({ status: 500 })).toBe(false);+ expect(+ isComposioConnectedAccountNotFoundError(+ new ComposioToolExecutionError('tool failed', { cause: { status: 404 } }),+ ),+ ).toBe(false);+ });+});diff --git a/src/libs/composio/index.ts b/src/libs/composio/index.tsindex eaebd5474ef..32d1862eccf 100644--- a/src/libs/composio/index.ts+++ b/src/libs/composio/index.ts@@ -1,9 +1,54 @@-import { Composio } from '@composio/core';+import {+ Composio,+ ComposioConnectedAccountNotFoundError,+ ConnectedAccountErrorCodes,+} from '@composio/core';+import { toRecord } from '@lobechat/utils/object';import { getServerComposioApiKey } from '@/config/composio';let composioClientInstance: { apiKey: string; client: Composio } | undefined;+/**+ * Identifies an explicit Composio connected-account-not-found error.+ *+ * Use when:+ * - `tools.execute` emits the normalized Composio error class or code+ *+ * Expects:+ * - The SDK has already classified the failure as a missing connected account+ *+ * Returns:+ * - `true` only for the concrete connected-account error, code, or stable name+ */+export const isComposioConnectedAccountNotFoundError = (error: unknown): boolean => {+ if (error instanceof ComposioConnectedAccountNotFoundError) return true;++ const record = toRecord(error);+ if (!record) return false;+ if (record.code === ConnectedAccountErrorCodes.CONNECTED_ACCOUNT_NOT_FOUND) return true;+ return record.name === 'ComposioConnectedAccountNotFoundError';+};++/**+ * Identifies a missing account at the dedicated connected-account lookup boundary.+ *+ * Use when:+ * - `connectedAccounts.get` may expose the generated API client's raw HTTP 404+ *+ * Expects:+ * - The attempted HTTP operation only retrieves a known connected-account ID+ *+ * Returns:+ * - `true` for an explicit connected-account error or a direct lookup HTTP 404+ */+export const isComposioConnectedAccountLookupNotFoundError = (error: unknown): boolean => {+ if (isComposioConnectedAccountNotFoundError(error)) return true;++ const record = toRecord(error);+ return record?.status === 404 || record?.statusCode === 404;+};+export const getComposioClient = (): Composio => {const apiKey = getServerComposioApiKey();