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): reconcile providers through revise (#18269)

Neko1e9e435a2854
diff --git a/apps/server/src/routers/lambda/user.ts b/apps/server/src/routers/lambda/user.ts
index e6e436af24e..3a56f10eb5c 100644
--- a/apps/server/src/routers/lambda/user.ts
+++ b/apps/server/src/routers/lambda/user.ts
@@ -125,7 +125,7 @@ const confirmOnboardingUnderstandingInputSchema = z
.strict() satisfies z.ZodType<ConfirmOnboardingUnderstandingInput>;
const reviseOnboardingUnderstandingInputSchema = z
.object({
- expectedFeedbackRevision: z.number().int().nonnegative().max(MAX_COLLECTION_COUNT),
+ expectedFeedbackRevision: z.number().int().nonnegative().max(MAX_COLLECTION_COUNT).optional(),
feedback: z.string().trim().min(1).max(MAX_UNDERSTANDING_FEEDBACK_LENGTH).optional(),
providerIds: z
.array(
diff --git a/apps/server/src/services/understanding/providers/gmail.test.ts b/apps/server/src/services/understanding/providers/gmail.test.ts
new file mode 100644
index 00000000000..d2068c9ecb6
--- /dev/null
+++ b/apps/server/src/services/understanding/providers/gmail.test.ts
@@ -0,0 +1,58 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { gmailUnderstandingProvider } from './gmail';
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('gmailUnderstandingProvider', () => {
+ /** @example A Gmail account without read scopes is skipped before evidence searches run. */
+ it('persists a non-retryable diagnostic when Gmail read permission is missing', async () => {
+ // ROOT CAUSE:
+ //
+ // Connector availability only proves that an OAuth account exists. A user can finish Gmail
+ // OAuth without granting read access, which previously caused every profile search to fail and
+ // obscured the actionable permission problem behind a generic collection failure.
+ //
+ // We fixed this by checking the owned account scopes before issuing any Gmail search request.
+ const searchMessages = vi.fn();
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
+
+ const result = await gmailUnderstandingProvider.collect({
+ connectorData: {
+ getGmailClient: vi.fn(async () => ({
+ getAccount: vi.fn(async () => ({
+ externalAccountId: 'gmail-account',
+ scopes: ['openid', 'email'],
+ })),
+ searchMessages,
+ })),
+ } as never,
+ userId: 'user-id',
+ });
+
+ expect(searchMessages).not.toHaveBeenCalled();
+ expect(warning).toHaveBeenCalledWith(
+ '[understanding:gmail] skipped because Gmail read permission is missing',
+ );
+ expect(result).toEqual({
+ context: '',
+ diagnostics: {
+ errors: [
+ {
+ code: 'GMAIL_READ_PERMISSION_REQUIRED',
+ message: 'Gmail read permission is required to collect Understanding evidence',
+ operation: 'permission',
+ provider: 'gmail',
+ retryable: false,
+ },
+ ],
+ evidenceCount: 0,
+ failedCount: 1,
+ succeededCount: 0,
+ },
+ sourceCount: 0,
+ });
+ });
+});
diff --git a/apps/server/src/services/understanding/providers/gmail.ts b/apps/server/src/services/understanding/providers/gmail.ts
index 983d70bd7f0..a5f9babc80b 100644
--- a/apps/server/src/services/understanding/providers/gmail.ts
+++ b/apps/server/src/services/understanding/providers/gmail.ts
@@ -18,6 +18,13 @@ 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 evidencePriority = ({ labels }: GmailMessage) => {
const normalized = new Set(labels.map((label) => label.toUpperCase()));
if (normalized.has('CATEGORY_PROMOTIONS')) return 2;
@@ -78,6 +85,28 @@ export const gmailUnderstandingProvider: UnderstandingProvider = {
id: 'gmail',
collect: async ({ connectorData }) => {
const client = await connectorData.getGmailClient();
+ const account = await client.getAccount();
+ if (!hasGmailReadPermission(account.scopes)) {
+ console.warn('[understanding:gmail] skipped because Gmail read permission is missing');
+ return {
+ context: '',
+ diagnostics: {
+ errors: [
+ {
+ code: 'GMAIL_READ_PERMISSION_REQUIRED',
+ message: 'Gmail read permission is required to collect Understanding evidence',
+ operation: 'permission',
+ provider: 'gmail',
+ retryable: false,
+ },
+ ],
+ evidenceCount: 0,
+ failedCount: 1,
+ succeededCount: 0,
+ },
+ sourceCount: 0,
+ };
+ }
const settled = await Promise.allSettled(
GMAIL_PROFILE_SEARCHES.map(({ query }) => client.searchMessages({ query })),
);
diff --git a/apps/server/src/services/understanding/service.test.ts b/apps/server/src/services/understanding/service.test.ts
index e25dac7b1eb..0a971140555 100644
--- a/apps/server/src/services/understanding/service.test.ts
+++ b/apps/server/src/services/understanding/service.test.ts
@@ -173,7 +173,12 @@ const createHarness = (initialSession?: OnboardingUnderstandingSession) => {
),
},
};
- return session;
+ return {
+ attempts: providerIds
+ .filter((providerId) => session!.sources[providerId]?.status === 'pending')
+ .map((id) => ({ id, revision: 1 })),
+ session,
+ };
},
),
failProvider: vi.fn(async () => session!),
@@ -495,6 +500,52 @@ describe('UnderstandingService', () => {
);
});
+ /** @example Reconciliation dispatches only GitHub after Gmail fails for missing permission. */
+ it('dispatches only provider attempts selected by atomic reconciliation', async () => {
+ // ROOT CAUSE:
+ //
+ // Retrying a failed Understanding session operated only on its original provider manifest, so
+ // a GitHub connection added after navigating backward was never dispatched. Retrying each failed
+ // source independently also repeated non-retryable Gmail permission failures.
+ //
+ // We fixed this by letting the repository return the exact running revisions to dispatch.
+ const gmail = {
+ ...providerState('failed', 1),
+ errors: [
+ {
+ code: 'GMAIL_READ_PERMISSION_REQUIRED',
+ message: 'Gmail read permission is required',
+ operation: 'permission',
+ provider: 'gmail',
+ retryable: false,
+ },
+ ],
+ failedCount: 1,
+ };
+ const next = createSession({ github: providerState('running', 1), gmail });
+ const harness = createHarness(createSession({ gmail }));
+ harness.repository.extend.mockImplementationOnce(async () => {
+ harness.setSession(next);
+ return { attempts: [{ id: 'github', revision: 1 }], session: next };
+ });
+
+ await expect(
+ harness.service.revise({
+ providerIds: ['gmail', 'github'],
+ responseLanguage: 'zh-CN',
+ sessionId: 'session-1',
+ topicId: 'topic-1',
+ }),
+ ).resolves.toMatchObject({
+ sources: { github: { status: 'running' }, gmail: { status: 'failed' } },
+ });
+
+ expect(mockTriggerProviders).toHaveBeenCalledWith(
+ expect.objectContaining({ providers: [{ id: 'github', revision: 1 }] }),
+ expect.any(Object),
+ );
+ });
+
/**
* @example
* expect(result.sources.gmail.status).toBe('failed');
diff --git a/apps/server/src/services/understanding/service.ts b/apps/server/src/services/understanding/service.ts
index 9ba03bae9b2..231d5108730 100644
--- a/apps/server/src/services/understanding/service.ts
+++ b/apps/server/src/services/understanding/service.ts
@@ -339,26 +339,25 @@ export class UnderstandingService {
const { OnboardingUnderstandingWorkflow } =
await import('@/server/workflows/onboardingUnderstanding');
OnboardingUnderstandingWorkflow.assertAvailable();
- const current = await this.activeSession(input.topicId, input.sessionId);
+ await this.activeSession(input.topicId, input.sessionId);
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 providerIds = requestedProviderIds.filter((providerId) =>
+ availableProviderIds.has(providerId),
);
- const next = await this.dependencies.repository.extend({
- expectedFeedbackRevision: input.expectedFeedbackRevision,
- feedback: input.feedback,
- providerIds,
- sessionId: input.sessionId,
- topicId: input.topicId,
- });
- const addedProviders = providerIds
- .filter((providerId) => !current.sources[providerId])
- .map((id) => ({ id, revision: 1 }));
+ const { attempts: providerAttempts, session: next } = await this.dependencies.repository.extend(
+ {
+ expectedFeedbackRevision: input.expectedFeedbackRevision,
+ feedback: input.feedback,
+ providerIds,
+ sessionId: input.sessionId,
+ topicId: input.topicId,
+ },
+ );
const completedProviders = Object.entries(next.sources).filter(
([, state]) => state.status === 'completed',
);
@@ -398,23 +397,37 @@ export class UnderstandingService {
)),
})),
);
- const providerAttempts = [...addedProviders, ...recollectedProviders].sort((left, right) =>
+ const attempts = [...providerAttempts, ...recollectedProviders].sort((left, right) =>
left.id.localeCompare(right.id),
);
- if (providerAttempts.length > 0) {
- await OnboardingUnderstandingWorkflow.triggerProviders(
- {
- providers: providerAttempts,
- responseLanguage: input.responseLanguage,
- sessionId: input.sessionId,
- startedAt: Date.now(),
- topicId: input.topicId,
- userId: this.dependencies.userId,
- },
- {
- workflowRunId: `onboarding-understanding-extend-${input.sessionId}-${next.feedback?.revision ?? 0}-${providerAttempts.map(({ id, revision }) => `${id}-${revision}`).join('-')}`,
- },
- );
+ if (attempts.length > 0) {
+ try {
+ await OnboardingUnderstandingWorkflow.triggerProviders(
+ {
+ providers: attempts,
+ responseLanguage: input.responseLanguage,
+ sessionId: input.sessionId,
+ startedAt: Date.now(),
+ topicId: input.topicId,
+ userId: this.dependencies.userId,
+ },
+ {
+ workflowRunId: `onboarding-understanding-extend-${input.sessionId}-${next.feedback?.revision ?? 0}-${attempts.map(({ id, revision }) => `${id}-${revision}`).join('-')}`,
+ },
+ );
+ } catch (triggerError) {
+ await Promise.allSettled(
+ attempts.map(({ id, revision }) =>
+ this.failProvider({
+ providerId: id,
+ revision,
+ sessionId: input.sessionId,
+ topicId: input.topicId,
+ }),
+ ),
+ );
+ throw triggerError;
+ }
}
const sourceFingerprint = getUnderstandingSourceFingerprint(availableSession);
@@ -479,6 +492,7 @@ export class UnderstandingService {
if (state.status !== 'failed') {
throw new UnderstandingPreconditionError('source_not_retryable');
}
+ if (!state.errors.some(({ retryable }) => retryable)) return this.get(input.topicId);
const availableProviderIds = await this.dependencies.connectorData.listAvailableProviderIds([
input.providerId,
]);
diff --git a/packages/database/src/repositories/onboardingUnderstanding/repository.test.ts b/packages/database/src/repositories/onboardingUnderstanding/repository.test.ts
index 33c2e28afaa..27f0af552c3 100644
--- a/packages/database/src/repositories/onboardingUnderstanding/repository.test.ts
+++ b/packages/database/src/repositories/onboardingUnderstanding/repository.test.ts
@@ -285,11 +285,11 @@ describe('OnboardingUnderstandingRepository', () => {
topicId,
});
- expect(first.sources).toEqual({
+ expect(first.session.sources).toEqual({
github: expect.objectContaining({ revision: 0, status: 'pending' }),
- gmail: expect.objectContaining({ revision: 0, status: 'pending' }),
+ gmail: expect.objectContaining({ revision: 1, status: 'running' }),
});
- expect(second.feedback).toEqual({
+ expect(second.session.feedback).toEqual({
revision: 2,
turns: [
expect.objectContaining({
@@ -313,6 +313,68 @@ describe('OnboardingUnderstandingRepository', () => {
).rejects.toThrow('feedback is no longer active');
});
+ /** @example A newly connected GitHub source runs while a Gmail permission failure stays failed. */
+ it('adds new providers without retrying non-retryable provider failures', async () => {
+ // ROOT CAUSE:
+ //
+ // The original session manifest was immutable during retry. Returning to connector setup and
+ // adding GitHub therefore retried only the existing Gmail failure, while GitHub never entered
+ // the session. Permission failures were also retried even though the OAuth grant had not changed.
+ //
+ // We fixed this with one locked mutation that adds new providers and restarts only failures whose
+ // persisted diagnostics explicitly allow retry.
+ await repository.initialize(topicId, sessionId, ['gmail']);
+ const { revision } = await repository.markProviderRunning(topicId, sessionId, 'gmail');
+ await repository.failProvider({
+ errors: [
+ {
+ code: 'GMAIL_READ_PERMISSION_REQUIRED',
+ message: 'Gmail read permission is required',
+ operation: 'permission',
+ provider: 'gmail',
+ retryable: false,
+ },
+ ],
+ failedCount: 1,
+ providerId: 'gmail',
+ revision,
+ sessionId,
+ succeededCount: 0,
+ topicId,
+ });
+
+ const reconciled = await repository.extend({
+ expectedFeedbackRevision: 0,
+ providerIds: ['gmail', 'github'],
+ sessionId,
+ topicId,
+ });
+
+ expect(reconciled.attempts).toEqual([{ id: 'github', revision: 1 }]);
+ expect(reconciled.session.sources).toMatchObject({
+ github: { errors: [], revision: 1, status: 'running' },
+ gmail: {
+ errors: [expect.objectContaining({ code: 'GMAIL_READ_PERMISSION_REQUIRED' })],
+ revision: 1,
+ status: 'failed',
+ },
+ });
+ });
+
+ /** @example Provider-only revision succeeds without carrying feedback concurrency state. */
+ it('does not require a feedback revision when only providers change', async () => {
+ await repository.initialize(topicId, sessionId, ['github']);
+
+ const revised = await repository.extend({
+ providerIds: ['github', 'gmail'],
+ sessionId,
+ topicId,
+ });
+
+ expect(revised.attempts).toEqual([{ id: 'gmail', revision: 1 }]);
+ expect(revised.session.sources.gmail).toMatchObject({ revision: 1, status: 'running' });
+ });
+
/**
* @example
* expect(stale.published).toBe(false);
diff --git a/packages/database/src/repositories/onboardingUnderstanding/repository.ts b/packages/database/src/repositories/onboardingUnderstanding/repository.ts
index 32a2a9958a7..1429792186d 100644
--- a/packages/database/src/repositories/onboardingUnderstanding/repository.ts
+++ b/packages/database/src/repositories/onboardingUnderstanding/repository.ts
@@ -108,13 +108,18 @@ interface PrepareWritingInput {
}
interface ExtendSessionInput {
- expectedFeedbackRevision: number;
+ expectedFeedbackRevision?: number;
feedback?: string;
providerIds: string[];
sessionId: string;
topicId: string;
}
+interface ExtendSessionResult {
+ attempts: Array<{ id: string; revision: number }>;
+ session: OnboardingUnderstandingSession;
+}
+
interface CommitWritingInput {
assistantMessageId: string;
feedbackRevision: number;
@@ -331,7 +336,7 @@ export class OnboardingUnderstandingRepository {
providerIds,
sessionId,
topicId,
- }: ExtendSessionInput): Promise<OnboardingUnderstandingSession> => {
+ }: ExtendSessionInput): Promise<ExtendSessionResult> => {
providerIds.forEach(assertProviderId);
return this.db.transaction((tx) =>
mutateTopicSession(tx, this.userId, topicId, (persisted) => {
@@ -340,16 +345,44 @@ export class OnboardingUnderstandingRepository {
const trimmedFeedback = feedback?.trim();
const currentFeedback = session.feedback ?? { revision: 0, turns: [] };
- if (currentFeedback.revision !== expectedFeedbackRevision) {
- throw new StaleUnderstandingRevisionError('feedback', expectedFeedbackRevision);
+ if (trimmedFeedback && currentFeedback.revision !== expectedFeedbackRevision) {
+ throw new StaleUnderstandingRevisionError(
+ 'feedback',
+ expectedFeedbackRevision ?? 'missing',
+ );
}
if (trimmedFeedback && currentFeedback.turns.length >= MAX_UNDERSTANDING_FEEDBACK_TURNS) {
throw new UnderstandingPreconditionError('feedback_limit_reached');
}
const sources = { ...session.sources };
- for (const providerId of new Set(providerIds)) {
- sources[providerId] ??= initialProviderState();
+ const attempts: ExtendSessionResult['attempts'] = [];
+ for (const providerId of [...new Set(providerIds)].sort()) {
+ const current = sources[providerId];
+ if (!current) {
+ sources[providerId] = {
+ ...initialProviderState(),
+ revision: 1,
+ status: 'running',
+ };
+ attempts.push({ id: providerId, revision: 1 });
+ continue;
+ }
+ if (current.status !== 'failed' || !current.errors.some(({ retryable }) => retryable)) {
+ continue;
+ }
+
+ const revision = current.revision + 1;
+ sources[providerId] = {
+ ...current,
+ completedAt: undefined,
+ errors: [],
+ failedCount: 0,
+ revision,
+ status: 'running',
+ succeededCount: 0,
+ };
+ attempts.push({ id: providerId, revision });
}
const nextFeedback = trimmedFeedback
? {
@@ -364,12 +397,18 @@ export class OnboardingUnderstandingRepository {
],
}
: currentFeedback;
- const changed =
- trimmedFeedback || Object.keys(sources).length !== Object.keys(session.sources).length;
- if (!changed) return { nextSession: session, result: session, write: false };
+ const changed = Boolean(trimmedFeedback) || attempts.length > 0;
+ if (!changed) {
+ return { nextSession: session, result: { attempts, session }, write: false };
+ }
const nextSession = parseSession({ ...session, feedback: nextFeedback, sources });
- return { nextSession, result: nextSession, write: true };
+ return {
+ clearTaskRecommendations: attempts.length > 0,
+ nextSession,
+ result: { attempts, session: nextSession },
+ write: true,
+ };
}),
);
};
diff --git a/packages/types/src/understanding.ts b/packages/types/src/understanding.ts
index c07ab06ecb4..04db04ce00d 100644
--- a/packages/types/src/understanding.ts
+++ b/packages/types/src/understanding.ts
@@ -279,8 +279,8 @@ export interface StartOnboardingUnderstandingInput extends OnboardingUnderstandi
* Adds direct feedback and newly selected providers to an active Understanding session.
*/
export interface ReviseOnboardingUnderstandingInput extends OnboardingUnderstandingTopicInput {
- /** Feedback revision observed by the caller; prevents duplicate or stale appends. */
- expectedFeedbackRevision: number;
+ /** Feedback revision observed by the caller; required when `feedback` is provided. */
+ expectedFeedbackRevision?: number;
/** Optional direct guidance appended to the cumulative writer prompt. */
feedback?: string;
/** Additive provider identifiers; existing sources are never removed. */