Skip to content

🤯 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.

🐛 fix(onboarding): detect missing Gmail read permission (#18427)

Nekodb1f563a4f66
diff --git a/apps/server/src/routers/lambda/composio.test.ts b/apps/server/src/routers/lambda/composio.test.ts
index 7e6250cef66..72f8179dce5 100644
--- a/apps/server/src/routers/lambda/composio.test.ts
+++ b/apps/server/src/routers/lambda/composio.test.ts
@@ -8,7 +8,9 @@ const mocks = vi.hoisted(() => ({
authConfigsCreate: vi.fn(),
authConfigsList: vi.fn(),
connectedAccountsDelete: vi.fn(),
+ connectedAccountsGet: vi.fn(),
connectedAccountsLink: vi.fn(),
+ connectedAccountsList: vi.fn(),
connectorCreate: vi.fn(),
connectorDelete: vi.fn(),
connectorFindScopedByIdentifier: vi.fn(),
@@ -59,7 +61,12 @@ vi.mock('@/database/models/connectorTool', () => ({
vi.mock('@/libs/composio', () => ({
getComposioClient: () => ({
authConfigs: { create: mocks.authConfigsCreate, list: mocks.authConfigsList },
- connectedAccounts: { delete: mocks.connectedAccountsDelete, link: mocks.connectedAccountsLink },
+ connectedAccounts: {
+ delete: mocks.connectedAccountsDelete,
+ get: mocks.connectedAccountsGet,
+ link: mocks.connectedAccountsLink,
+ list: mocks.connectedAccountsList,
+ },
tools: { getRawComposioTools: mocks.getRawComposioTools },
}),
}));
@@ -73,6 +80,50 @@ beforeEach(() => {
mocks.pluginFindById.mockResolvedValue(undefined);
});
+/** @example OAuth callback polling reports whether Gmail can be read. */
+describe('composioRouter.getConnection', () => {
+ /** @example An ACTIVE Gmail account with read-only scope is marked readable. */
+ it('returns confirmed Gmail read permission', async () => {
+ const account = {
+ data: {
+ email: '[email protected]',
+ scopes: ['https://www.googleapis.com/auth/gmail.readonly'],
+ },
+ id: 'ca-1',
+ status: 'ACTIVE',
+ toolkit: { slug: 'gmail' },
+ };
+ mocks.connectedAccountsGet.mockResolvedValue(account);
+ mocks.connectedAccountsList.mockResolvedValue({ items: [account] });
+
+ await expect(caller().getConnection({ connectedAccountId: 'ca-1' })).resolves.toMatchObject({
+ connectedAccountId: 'ca-1',
+ gmailReadPermission: true,
+ status: 'ACTIVE',
+ });
+ });
+
+ /** @example An ACTIVE Gmail account with identity-only scopes triggers the recovery UI. */
+ it('returns missing Gmail read permission', async () => {
+ const account = {
+ data: {
+ email: '[email protected]',
+ scopes: ['openid', 'https://www.googleapis.com/auth/userinfo.email'],
+ },
+ id: 'ca-1',
+ status: 'ACTIVE',
+ toolkit: { slug: 'gmail' },
+ };
+ mocks.connectedAccountsGet.mockResolvedValue(account);
+ mocks.connectedAccountsList.mockResolvedValue({ items: [account] });
+
+ await expect(caller().getConnection({ connectedAccountId: 'ca-1' })).resolves.toMatchObject({
+ gmailReadPermission: false,
+ status: 'ACTIVE',
+ });
+ });
+});
+
describe('composioRouter.createConnection dual-write', () => {
it('mirrors a pending connection into user_connectors + tools', async () => {
mocks.getServerComposioAuthConfigId.mockReturnValue('ac_env');
diff --git a/apps/server/src/routers/lambda/composio.ts b/apps/server/src/routers/lambda/composio.ts
index ac0e50c7978..7d94f87b697 100644
--- a/apps/server/src/routers/lambda/composio.ts
+++ b/apps/server/src/routers/lambda/composio.ts
@@ -1,3 +1,4 @@
+import { createGmailConnectorClient, hasGmailReadPermission } from '@lobechat/connector-data/gmail';
import type { LobeChatDatabase } from '@lobechat/database';
import { type ToolManifest } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
@@ -395,11 +396,32 @@ export const composioRouter = router({
const account = await (ctx.composioClient.connectedAccounts as any).get(
input.connectedAccountId,
);
+ const appSlug = account?.toolkit?.slug || '';
+ const status = (account?.status || 'PENDING') as string;
+ let gmailReadPermission: boolean | undefined;
+
+ if (appSlug.toLowerCase() === 'gmail' && status === 'ACTIVE') {
+ try {
+ const gmailClient = createGmailConnectorClient({
+ composio: ctx.composioClient,
+ connectedAccountId: input.connectedAccountId,
+ userId: ctx.userId,
+ });
+ const gmailAccount = await gmailClient.getAccount();
+ gmailReadPermission = hasGmailReadPermission(gmailAccount.scopes);
+ } catch (error) {
+ // Permission introspection is advisory: a transient Composio lookup failure must not
+ // downgrade an otherwise active connection or trap the OAuth polling loop.
+ console.warn('[Composio] Failed to inspect Gmail permissions:', error);
+ }
+ }
+
return {
- appSlug: account?.toolkit?.slug || '',
+ appSlug,
connectedAccountId: input.connectedAccountId,
error: undefined as 'AUTH_ERROR' | undefined,
- status: (account?.status || 'PENDING') as string,
+ gmailReadPermission,
+ status,
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
diff --git a/apps/server/src/services/connectorData/index.test.ts b/apps/server/src/services/connectorData/index.test.ts
index a43c196f61b..6437eac1c3a 100644
--- a/apps/server/src/services/connectorData/index.test.ts
+++ b/apps/server/src/services/connectorData/index.test.ts
@@ -31,6 +31,8 @@ vi.mock('@lobechat/connector-data/github', () => ({
vi.mock('@lobechat/connector-data/gmail', () => ({
createGmailConnectorClient: mocks.createGmailClient,
+ hasGmailReadPermission: (scopes: readonly string[]) =>
+ scopes.some((scope) => scope.endsWith('gmail.readonly')),
}));
vi.mock('@lobechat/connector-data/notion', () => ({
@@ -474,6 +476,36 @@ describe('ConnectorDataService', () => {
]);
});
+ /** @example Gmail without message-read scope is omitted from Understanding availability. */
+ it('excludes connected Gmail accounts without read permission', async () => {
+ // ROOT CAUSE:
+ //
+ // Connection availability only checked whether a Gmail client could be created.
+ // Identity-only OAuth grants therefore entered Understanding and failed during collection.
+ // We fixed this by checking the account's granted scopes as part of source availability.
+ mocks.queryComposioReferences.mockResolvedValue([
+ {
+ composio: {
+ appSlug: 'gmail',
+ connectedAccountId: 'gmail-account',
+ ownerUserId: 'gmail-owner',
+ status: 'ACTIVE',
+ },
+ id: 'gmail-a',
+ isEnabled: true,
+ status: 'connected',
+ },
+ ]);
+ mocks.getAccount.mockResolvedValue({
+ externalAccountId: 'gmail-account',
+ scopes: ['openid', 'https://www.googleapis.com/auth/userinfo.email'],
+ });
+
+ await expect(
+ new ConnectorDataService(authDb([]), 'user-1').listAvailableProviderIds(['gmail']),
+ ).resolves.toEqual([]);
+ });
+
/** @example A temporary provider failure rejects availability instead of omitting the source. */
it('propagates transient provider availability failures', async () => {
// ROOT CAUSE:
diff --git a/apps/server/src/services/connectorData/index.ts b/apps/server/src/services/connectorData/index.ts
index 88b265a3f61..406106ebdea 100644
--- a/apps/server/src/services/connectorData/index.ts
+++ b/apps/server/src/services/connectorData/index.ts
@@ -9,7 +9,7 @@ import {
createGitHubOAuthConnectorClient,
} from '@lobechat/connector-data/github';
import type { GmailConnectorClient } from '@lobechat/connector-data/gmail';
-import { createGmailConnectorClient } from '@lobechat/connector-data/gmail';
+import { createGmailConnectorClient, hasGmailReadPermission } from '@lobechat/connector-data/gmail';
import type { NotionConnectorClient } from '@lobechat/connector-data/notion';
import { createNotionConnectorClient } from '@lobechat/connector-data/notion';
import type { TwitterConnectorClient } from '@lobechat/connector-data/twitter';
@@ -117,7 +117,11 @@ export class ConnectorDataService {
if (!isConnectorDataProvider(providerId)) return;
try {
- await this.resolveProviderClient(providerId);
+ const client = await this.resolveProviderClient(providerId);
+ if (providerId === 'gmail') {
+ const account = await (client as GmailConnectorClient).getAccount();
+ if (!hasGmailReadPermission(account.scopes)) return;
+ }
return providerId;
} catch (error) {
if (isConfirmedProviderUnavailableError(error, providerId)) return;
diff --git a/apps/server/src/services/understanding/providers/gmail.ts b/apps/server/src/services/understanding/providers/gmail.ts
index 1682ff01ff2..fbd53e14c7d 100644
--- a/apps/server/src/services/understanding/providers/gmail.ts
+++ b/apps/server/src/services/understanding/providers/gmail.ts
@@ -4,7 +4,7 @@ import {
isConnectorErrorRetryable,
} from '@lobechat/connector-data';
import type { GmailMessage } from '@lobechat/connector-data/gmail';
-import { toGmailMessagesXml } from '@lobechat/connector-data/gmail';
+import { hasGmailReadPermission, toGmailMessagesXml } from '@lobechat/connector-data/gmail';
import type { UnderstandingProvider } from '../types';
@@ -22,13 +22,6 @@ const GMAIL_PROFILE_SEARCHES = [
const MAX_CONTEXT_MESSAGES = 32;
const MAX_CONTEXT_MESSAGES_PER_SENDER_DOMAIN = 6;
-const hasGmailReadPermission = (scopes: readonly string[]) =>
- scopes.some((scope) =>
- ['gmail.modify', 'gmail.readonly', 'mail.google.com/'].some((permission) =>
- scope.endsWith(permission),
- ),
- );
-
const getGmailCollectionErrorCode = (reason: unknown) =>
reason instanceof ConnectorDataError ? reason.code : 'GMAIL_SEARCH_FAILED';
diff --git a/locales/en-US/onboarding.json b/locales/en-US/onboarding.json
index 1f0b23ada0e..7500fb49650 100644
--- a/locales/en-US/onboarding.json
+++ b/locales/en-US/onboarding.json
@@ -44,6 +44,11 @@
"flow.steps.connectApps.connect": "Connect",
"flow.steps.connectApps.connected": "Connected",
"flow.steps.connectApps.description": "Add a few apps to help shape a more personal experience.",
+ "flow.steps.connectApps.gmailPermissionModal.continueAuthorization": "Continue authorization",
+ "flow.steps.connectApps.gmailPermissionModal.description": "Without Gmail read permission, your assistant cannot learn about you from your inbox.",
+ "flow.steps.connectApps.gmailPermissionModal.hint": "This does not affect the rest of onboarding. You can skip for now and continue.",
+ "flow.steps.connectApps.gmailPermissionModal.skipAndContinue": "Skip and continue",
+ "flow.steps.connectApps.gmailPermissionModal.title": "More permission needed",
"flow.steps.connectApps.title": "Begin the shape of you",
"flow.steps.learnYourWorld.analysisFailed": "We could not finish analyzing your connected sources.",
"flow.steps.learnYourWorld.description": "Building your user profile",
diff --git a/locales/zh-CN/onboarding.json b/locales/zh-CN/onboarding.json
index f6006b71740..5cfb8b30a82 100644
--- a/locales/zh-CN/onboarding.json
+++ b/locales/zh-CN/onboarding.json
@@ -44,6 +44,11 @@
"flow.steps.connectApps.connect": "连接",
"flow.steps.connectApps.connected": "已连接",
"flow.steps.connectApps.description": "添加几个应用,帮助我们打造更懂你的体验。",
+ "flow.steps.connectApps.gmailPermissionModal.continueAuthorization": "继续授权",
+ "flow.steps.connectApps.gmailPermissionModal.description": "如果没有授予 Gmail 邮件读取权限,你的助理将无法从邮箱中了解你。",
+ "flow.steps.connectApps.gmailPermissionModal.hint": "这不会影响其他功能,你可以暂时跳过并继续。",
+ "flow.steps.connectApps.gmailPermissionModal.skipAndContinue": "跳过并继续",
+ "flow.steps.connectApps.gmailPermissionModal.title": "需要更多授权",
"flow.steps.connectApps.title": "开始塑造你的样子",
"flow.steps.learnYourWorld.analysisFailed": "未能完成对你已连接来源的分析。",
"flow.steps.learnYourWorld.description": "正在构建你的用户画像",
diff --git a/packages/connector-data/src/gmail/index.ts b/packages/connector-data/src/gmail/index.ts
index e42a3160262..d1c31ec367b 100644
--- a/packages/connector-data/src/gmail/index.ts
+++ b/packages/connector-data/src/gmail/index.ts
@@ -1,3 +1,4 @@
export * from './client';
export * from './formatter';
+export * from './permissions';
export * from './types';
diff --git a/packages/connector-data/src/gmail/permissions.test.ts b/packages/connector-data/src/gmail/permissions.test.ts
new file mode 100644
index 00000000000..da7a404f1e4
--- /dev/null
+++ b/packages/connector-data/src/gmail/permissions.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from 'vitest';
+
+import { hasGmailReadPermission } from './permissions';
+
+/** @example Gmail scope variants are classified before Understanding starts. */
+describe('hasGmailReadPermission', () => {
+ /** @example Read-only, modify, and full mailbox scopes all permit message collection. */
+ it.each([
+ 'https://www.googleapis.com/auth/gmail.readonly',
+ 'https://www.googleapis.com/auth/gmail.modify',
+ 'https://mail.google.com/',
+ ])('accepts %s', (scope) => {
+ expect(hasGmailReadPermission([scope])).toBe(true);
+ });
+
+ /** @example Identity-only and similarly named scopes cannot read Gmail messages. */
+ it('rejects scopes without mailbox read access', () => {
+ expect(
+ hasGmailReadPermission([
+ 'openid',
+ 'https://www.googleapis.com/auth/userinfo.email',
+ 'https://example.com/gmail.readonly',
+ ]),
+ ).toBe(false);
+ });
+});
diff --git a/packages/connector-data/src/gmail/permissions.ts b/packages/connector-data/src/gmail/permissions.ts
new file mode 100644
index 00000000000..854070c6e4d
--- /dev/null
+++ b/packages/connector-data/src/gmail/permissions.ts
@@ -0,0 +1,23 @@
+/**
+ * Reports whether granted Gmail OAuth scopes permit message reads.
+ *
+ * Use when:
+ * - A connector must verify Gmail evidence can be collected before starting work
+ * - An authorization callback must distinguish a connected account from a readable account
+ *
+ * Expects:
+ * - Full OAuth scope URLs or equivalent scope identifiers
+ *
+ * Returns:
+ * - `true` for Gmail read-only, modify, or full-mail access
+ */
+export const hasGmailReadPermission = (scopes: readonly string[]): boolean =>
+ scopes.some((scope) => GMAIL_READ_SCOPES.has(scope.trim()));
+/** Google OAuth scopes that permit reading Gmail message content. */
+const GMAIL_READ_SCOPES = new Set([
+ 'gmail.modify',
+ 'gmail.readonly',
+ 'https://mail.google.com/',
+ 'https://www.googleapis.com/auth/gmail.modify',
+ 'https://www.googleapis.com/auth/gmail.readonly',
+]);
diff --git a/packages/locales/src/default/onboarding.ts b/packages/locales/src/default/onboarding.ts
index 31939187f31..5ab56cc7b94 100644
--- a/packages/locales/src/default/onboarding.ts
+++ b/packages/locales/src/default/onboarding.ts
@@ -65,6 +65,13 @@ export default {
'flow.steps.connectApps.connect': 'Connect',
'flow.steps.connectApps.connected': 'Connected',
'flow.steps.connectApps.description': 'Add a few apps to help shape a more personal experience.',
+ 'flow.steps.connectApps.gmailPermissionModal.continueAuthorization': 'Continue authorization',
+ 'flow.steps.connectApps.gmailPermissionModal.description':
+ 'Without Gmail read permission, your assistant cannot learn about you from your inbox.',
+ 'flow.steps.connectApps.gmailPermissionModal.hint':
+ 'This does not affect the rest of onboarding. You can skip for now and continue.',
+ 'flow.steps.connectApps.gmailPermissionModal.skipAndContinue': 'Skip and continue',
+ 'flow.steps.connectApps.gmailPermissionModal.title': 'More permission needed',
'flow.steps.connectApps.title': 'Begin the shape of you',
'flow.steps.learnYourWorld.analysisFailed':
'We could not finish analyzing your connected sources.',
diff --git a/src/store/tool/slices/composioStore/action.ts b/src/store/tool/slices/composioStore/action.ts
index a82645f5424..9424aa17963 100644
--- a/src/store/tool/slices/composioStore/action.ts
+++ b/src/store/tool/slices/composioStore/action.ts
@@ -208,6 +208,8 @@ export class ComposioStoreActionImpl {
if (serverIndex >= 0) {
draft.composioServers[serverIndex].tools = tools;
draft.composioServers[serverIndex].status = ComposioServerStatus.ACTIVE;
+ draft.composioServers[serverIndex].gmailReadPermission =
+ connectionStatus.gmailReadPermission;
draft.composioServers[serverIndex].redirectUrl = undefined;
draft.composioServers[serverIndex].errorMessage = undefined;
}
diff --git a/src/store/tool/slices/composioStore/types.ts b/src/store/tool/slices/composioStore/types.ts
index a24b7b83cef..53abec44eea 100644
--- a/src/store/tool/slices/composioStore/types.ts
+++ b/src/store/tool/slices/composioStore/types.ts
@@ -22,6 +22,8 @@ export interface ComposioServer {
connectedAccountId: string;
createdAt: number;
errorMessage?: string;
+ /** Whether the active Gmail account granted a scope that permits reading messages. */
+ gmailReadPermission?: boolean;
icon?: string;
identifier: string;
label: string;