🤯 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(onboarding): stabilize understanding workflow replay (#18204)
Neko3b57a07e3cc1
diff --git a/apps/server/src/services/understanding/service.test.ts b/apps/server/src/services/understanding/service.test.tsindex cfe04999f48..e25dac7b1eb 100644--- a/apps/server/src/services/understanding/service.test.ts+++ b/apps/server/src/services/understanding/service.test.ts@@ -178,19 +178,23 @@ const createHarness = (initialSession?: OnboardingUnderstandingSession) => {),failProvider: vi.fn(async () => session!),failDetailedWriting: vi.fn(async () => session!),- failWriting: vi.fn(async ({ error, sourceFingerprint }) => {- session = {- ...session!,- writing: {- error,- resultMessageId: session?.writing?.resultMessageId,- sourceFingerprint,- status: 'failed',- updatedAt: '2026-07-20T00:00:00.000Z',- },- };- return session;- }),+ failWriting: vi.fn(+ async ({ error, feedbackRevision, generationRevision, sourceFingerprint }) => {+ session = {+ ...session!,+ writing: {+ error,+ feedbackRevision,+ generationRevision,+ resultMessageId: session?.writing?.resultMessageId,+ sourceFingerprint,+ status: 'failed',+ updatedAt: '2026-07-20T00:00:00.000Z',+ },+ };+ return session;+ },+ ),get: vi.fn(async () => session),initialize: vi.fn(async (_topicId: string, sessionId: string, providerIds: string[]) => {session = {@@ -744,7 +748,8 @@ describe('UnderstandingService', () => {expect(harness.generateObject).not.toHaveBeenCalled();});- it('ignores a writing failure before a generation is prepared', async () => {+ /** @example A workflow failure after collection creates a terminal writing state. */+ it('records a writing failure before a generation is prepared', async () => {const harness = createHarness(createSession({ github: providerState('completed', 1) }));await expect(@@ -753,9 +758,22 @@ describe('UnderstandingService', () => {sourceFingerprint: 'github@1',topicId: 'topic-1',}),- ).resolves.toBeUndefined();+ ).resolves.toMatchObject({+ writing: {+ feedbackRevision: 0,+ generationRevision: 0,+ sourceFingerprint: 'github@1',+ status: 'failed',+ },+ });expect(harness.repository.prepareWriting).not.toHaveBeenCalled();- expect(harness.repository.failWriting).not.toHaveBeenCalled();+ expect(harness.repository.failWriting).toHaveBeenCalledWith(+ expect.objectContaining({+ feedbackRevision: 0,+ generationRevision: 0,+ sourceFingerprint: 'github@1',+ }),+ );});it.each([diff --git a/apps/server/src/services/understanding/service.ts b/apps/server/src/services/understanding/service.tsindex 1f49d379120..9ba03bae9b2 100644--- a/apps/server/src/services/understanding/service.ts+++ b/apps/server/src/services/understanding/service.ts@@ -844,7 +844,7 @@ export class UnderstandingService {}) => {try {const current = await this.activeSession(topicId, sessionId);- if (!current.writing || current.writing.sourceFingerprint !== sourceFingerprint) return;+ if (current.writing && current.writing.sourceFingerprint !== sourceFingerprint) return;const session = await this.dependencies.repository.failWriting({error: canonicalCollectionError('understanding',@@ -852,8 +852,8 @@ export class UnderstandingService {'UNDERSTANDING_WRITING_FAILED',true,),- feedbackRevision: current.writing.feedbackRevision ?? 0,- generationRevision: current.writing.generationRevision ?? 0,+ feedbackRevision: current.writing?.feedbackRevision ?? current.feedback?.revision ?? 0,+ generationRevision: current.writing?.generationRevision ?? current.generationRevision ?? 0,sessionId,sourceFingerprint,topicId,diff --git a/apps/server/src/workflows/onboardingUnderstanding/processProviders.test.ts b/apps/server/src/workflows/onboardingUnderstanding/processProviders.test.tsindex 099e4c414fe..e13be455a62 100644--- a/apps/server/src/workflows/onboardingUnderstanding/processProviders.test.ts+++ b/apps/server/src/workflows/onboardingUnderstanding/processProviders.test.ts@@ -18,6 +18,16 @@ const errors = vi.hoisted(() => {});vi.mock('@lobechat/database', () => ({+ getUnderstandingSourceFingerprint: ({+ sources,+ }: {+ sources: Record<string, { revision: number; status: string }>;+ }) =>+ Object.entries(sources)+ .filter(([, source]) => source.status === 'completed')+ .sort(([left], [right]) => left.localeCompare(right))+ .map(([providerId, source]) => `${providerId}@${source.revision}`)+ .join(','),StaleUnderstandingSessionError: errors.DomainError,UnderstandingResourceNotFoundError: errors.DomainError,UnderstandingSessionNotFoundError: errors.DomainError,@@ -71,7 +81,18 @@ const completed = (providerId: string, sourceFingerprint: string, revision = 1)});describe('processUnderstandingProviders', () => {- it('runs one durable operation per provider concurrently and invokes each completed fingerprint immediately', async () => {+ /**+ * @example A faster GitHub provider cannot create downstream steps before a slower Gmail provider.+ */+ it('separates concurrent provider collection from deterministic downstream scheduling', async () => {+ // ROOT CAUSE:+ //+ // If one provider completed before another, its async map callback immediately created writing+ // and recommendation steps. Upstash then persisted a parallel group whose membership depended on+ // completion timing, so replay could expect GitHub steps while receiving Twitter steps.+ //+ // Before: provider callbacks mixed collection and downstream workflow steps.+ // After: all collection steps settle before a sorted downstream step sequence is created.let releaseGmail!: () => void;const gmailGate = new Promise<void>((resolve) => (releaseGmail = resolve));const service = {@@ -88,16 +109,9 @@ describe('processUnderstandingProviders', () => {triggerTaskRecommendations,});- await vi.waitFor(() => expect(invocations).toHaveLength(1));- await vi.waitFor(() => expect(triggerTaskRecommendations).toHaveBeenCalledTimes(1));- expect(invocations[0].settings.body).toEqual({- responseLanguage: 'zh-CN',- sessionId: 'session-1',- sourceFingerprint: 'github@1',- startedAt: 1000,- topicId: 'topic-1',- userId: 'user-1',- });+ await vi.waitFor(() => expect(service.processProvider).toHaveBeenCalledTimes(2));+ expect(invocations).toHaveLength(0);+ expect(triggerTaskRecommendations).not.toHaveBeenCalled();releaseGmail();await running;@@ -114,6 +128,10 @@ describe('processUnderstandingProviders', () => {topicId: 'topic-1',});expect(invocations).toHaveLength(2);+ expect(invocations.map(({ settings }) => settings.body.sourceFingerprint)).toEqual([+ 'github@1',+ 'github@1,gmail@1',+ ]);expect(invocations[0].settings.flowControl).toEqual({key: 'onboarding-understanding.writing.session-1',parallelism: 1,@@ -277,6 +295,19 @@ describe('failRunningUnderstandingProviders', () => {failProvider: vi.fn(async ({ revision }: { revision: number }) =>revision === 8 ? {} : undefined,),+ failWriting: vi.fn(),+ get: vi.fn(async () => ({+ id: 'session-1',+ sources: {+ github: {+ errors: [],+ failedCount: 1,+ revision: 8,+ status: 'failed',+ succeededCount: 0,+ },+ },+ })),};const current = {...payload,@@ -308,4 +339,58 @@ describe('failRunningUnderstandingProviders', () => {topicId: 'topic-1',});});++ /** @example A provider workflow crash after collection projects the session as failed. */+ it('marks writing failed when all providers completed but downstream scheduling did not start', async () => {+ // ROOT CAUSE:+ //+ // The failure callback previously terminalized only running providers. If every provider had+ // already completed but downstream step replay failed, no state changed and polling remained+ // `processing` forever because the session had no writing state.+ //+ // We fixed this by creating a failed writing state for the completed source fingerprint.+ const service = {+ failProvider: vi.fn(async () => undefined),+ failWriting: vi.fn(async () => ({})),+ get: vi.fn(async () => ({+ generationRevision: 0,+ id: 'session-1',+ sources: {+ github: {+ completedAt: '2026-08-11T21:04:08.922Z',+ errors: [],+ failedCount: 0,+ revision: 1,+ status: 'completed',+ succeededCount: 10,+ },+ twitter: {+ completedAt: '2026-08-11T21:04:03.458Z',+ errors: [],+ failedCount: 0,+ revision: 1,+ status: 'completed',+ succeededCount: 3,+ },+ },+ })),+ };++ await failRunningUnderstandingProviders(+ {+ ...payload,+ providers: [+ { id: 'github', revision: 1 },+ { id: 'twitter', revision: 1 },+ ],+ },+ { createService: async () => service as never },+ );++ expect(service.failWriting).toHaveBeenCalledWith({+ sessionId: 'session-1',+ sourceFingerprint: 'github@1,twitter@1',+ topicId: 'topic-1',+ });+ });});diff --git a/apps/server/src/workflows/onboardingUnderstanding/processProviders.ts b/apps/server/src/workflows/onboardingUnderstanding/processProviders.tsindex 35adeaab264..59defbfbc0b 100644--- a/apps/server/src/workflows/onboardingUnderstanding/processProviders.ts+++ b/apps/server/src/workflows/onboardingUnderstanding/processProviders.ts@@ -1,6 +1,7 @@import { createHash } from 'node:crypto';import {+ getUnderstandingSourceFingerprint,StaleUnderstandingSessionError,UnderstandingResourceNotFoundError,UnderstandingSessionNotFoundError,@@ -29,7 +30,10 @@ import {ProcessUnderstandingProvidersPayloadSchema,} from './types';-type ProviderService = Pick<UnderstandingService, 'failProvider' | 'processProvider'>;+type ProviderService = Pick<+ UnderstandingService,+ 'failProvider' | 'failWriting' | 'get' | 'processProvider'+>;type ProviderWorkflowContext = Pick<WorkflowContext<ProcessUnderstandingProvidersPayload>,@@ -115,17 +119,31 @@ export const processUnderstandingProviders = async (async () => {const service = await (dependencies.createService ?? createService)(payload.userId);- const providers = await Promise.all(- payload.providers.map(async ({ id: providerId, revision }) => {- const result = await runStep(context, `provider:${providerId}:${revision}:process`, () =>+ // NOTICE:+ // Upstash batches workflow steps created in the same microtask into one parallel step group.+ // Creating downstream steps inside provider callbacks made that group depend on which provider+ // finished first, so replay expected GitHub steps while receiving Twitter steps (or vice versa).+ // Source/context: `@upstash/[email protected]/index.js:2058-2083` and `:2278-2315`.+ // Keep collection and downstream scheduling as separate, deterministically ordered stages until+ // Upstash supports dynamic parallel branches with independently replayable child step graphs.+ const providerResults = await Promise.all(+ payload.providers.map(async ({ id: providerId, revision }) => ({+ providerId,+ result: await runStep(context, `provider:${providerId}:${revision}:process`, () =>service.processProvider({providerId,revision,sessionId: payload.sessionId,topicId: payload.topicId,}),- );- await observeOnboardingUnderstandingOperation(+ ),+ revision,+ })),+ );++ await Promise.all(+ providerResults.map(({ providerId }) =>+ observeOnboardingUnderstandingOperation({operation: 'progress.publish',providerId,@@ -133,82 +151,100 @@ export const processUnderstandingProviders = async (topicId: payload.topicId,},() => publishOnboardingGenerationProgress(payload.userId, payload.topicId),- );- if (result.status === 'completed' && result.revision === revision) {- const body = {- responseLanguage: payload.responseLanguage,- sessionId: payload.sessionId,- sourceFingerprint: result.sourceFingerprint,- ...(payload.startedAt === undefined ? {} : { startedAt: payload.startedAt }),- topicId: payload.topicId,- userId: payload.userId,- };- const downstreamTasks: Promise<unknown>[] = [- context.invoke(`provider:${providerId}:write:${result.revision}`, {- body,- // Serialize writers for this session. The repository's fingerprint CAS then prevents a- // delayed failure callback for an older invocation from terminalizing newer writing.+ ),+ ),+ );++ for (const { providerId, result, revision } of providerResults) {+ if (result.status !== 'completed' || result.revision !== revision) continue;++ const body = {+ responseLanguage: payload.responseLanguage,+ sessionId: payload.sessionId,+ sourceFingerprint: result.sourceFingerprint,+ ...(payload.startedAt === undefined ? {} : { startedAt: payload.startedAt }),+ topicId: payload.topicId,+ userId: payload.userId,+ };+ await context.invoke(`provider:${providerId}:write:${result.revision}`, {+ body,+ // Serialize writers for this session. The repository's fingerprint CAS then prevents a+ // delayed failure callback for an older invocation from terminalizing newer writing.+ flowControl: {+ key: getUnderstandingWritingFlowControlKey(payload.sessionId),+ parallelism: 1,+ },+ headers: getOnboardingUnderstandingTraceHeaders(),+ workflow: dependencies.processCollectedWorkflow,+ workflowRunId: collectedWorkflowRunId(payload.sessionId, result.sourceFingerprint),+ });+ if (payload.triggerTaskRecommendations !== false) {+ await runStep(context, `provider:${providerId}:recommend:${result.revision}`, () =>+ // NOTICE:+ // Cross-route workflow fan-out must use an absolute QStash trigger.+ // context.invoke only replaces the current URL's final path segment, which sent this+ // child to `/api/workflows/onboarding/understanding/process` and returned 404.+ // Source/context: `router-hono/workflows/memory-user-memory/workflows/processUserTopics.ts:193`.+ // Remove when Upstash context.invoke supports absolute cross-route workflow URLs.+ dependencies.triggerTaskRecommendations(+ {+ responseLanguage: payload.responseLanguage,+ sessionId: payload.sessionId,+ sourceFingerprint: result.sourceFingerprint,+ topicId: payload.topicId,+ userId: payload.userId,+ },+ {+ // Every completed provider may race to schedule a fingerprint-specific run. The+ // session-scoped flow-control key makes the first accepted fingerprint immutable.flowControl: {- key: getUnderstandingWritingFlowControlKey(payload.sessionId),+ key: getTaskRecommendationFlowControlKey(payload.sessionId),parallelism: 1,},- headers: getOnboardingUnderstandingTraceHeaders(),- workflow: dependencies.processCollectedWorkflow,- workflowRunId: collectedWorkflowRunId(payload.sessionId, result.sourceFingerprint),- }),- ];- if (payload.triggerTaskRecommendations !== false) {- downstreamTasks.push(- runStep(context, `provider:${providerId}:recommend:${result.revision}`, () =>- // NOTICE:- // Cross-route workflow fan-out must use an absolute QStash trigger.- // context.invoke only replaces the current URL's final path segment, which sent this- // child to `/api/workflows/onboarding/understanding/process` and returned 404.- // Source/context: `router-hono/workflows/memory-user-memory/workflows/processUserTopics.ts:193`.- // Remove when Upstash context.invoke supports absolute cross-route workflow URLs.- dependencies.triggerTaskRecommendations(- {- responseLanguage: payload.responseLanguage,- sessionId: payload.sessionId,- sourceFingerprint: result.sourceFingerprint,- topicId: payload.topicId,- userId: payload.userId,- },- {- // Every completed provider may race to schedule a fingerprint-specific run. The- // session-scoped flow-control key makes the first accepted fingerprint immutable.- flowControl: {- key: getTaskRecommendationFlowControlKey(payload.sessionId),- parallelism: 1,- },- workflowRunId: taskRecommendationWorkflowRunId(- payload.sessionId,- result.sourceFingerprint,- ),- },- ),+ workflowRunId: taskRecommendationWorkflowRunId(+ payload.sessionId,+ result.sourceFingerprint,),- );- }- await Promise.all(downstreamTasks);- }-- return {- failedCount: result.failedCount,- providerId,- revision: result.revision,- sourceCount: result.sourceCount,- status: result.status,- succeededCount: result.succeededCount,- };- }),- );+ },+ ),+ );+ }+ }++ const providers = providerResults.map(({ providerId, result }) => ({+ failedCount: result.failedCount,+ providerId,+ revision: result.revision,+ sourceCount: result.sourceCount,+ status: result.status,+ succeededCount: result.succeededCount,+ }));return { providers };},);};+/**+ * Terminalizes provider-workflow state after Upstash exhausts delivery retries.+ *+ * Use when:+ * - Registering the failure callback for the provider collection workflow+ * - Preventing completed-source sessions from remaining in processing without a writer+ *+ * Expects:+ * - The payload identifies the exact provider revisions owned by the failed workflow run+ *+ * Returns:+ * - Provider identifiers transitioned from running to failed+ *+ * Call stack:+ *+ * processProvidersWorkflowOptions.failureFunction+ * -> {@link failRunningUnderstandingProviders}+ * -> UnderstandingService.failProvider+ * -> UnderstandingService.failWriting+ */export const failRunningUnderstandingProviders = async (input: unknown,dependencies: ProviderFailureDependencies = {},@@ -236,9 +272,52 @@ export const failRunningUnderstandingProviders = async (}),);+ try {+ const current = await service.get(payload.topicId);+ const hasActiveProvider = Object.values(current.sources).some(+ ({ status }) => status === 'pending' || status === 'running',+ );+ if (!hasActiveProvider && !current.writing) {+ const sourceFingerprint = getUnderstandingSourceFingerprint({+ feedback: current.feedback ?? { revision: 0, turns: [] },+ generationRevision: current.generationRevision ?? 0,+ id: current.id,+ sources: current.sources,+ });+ if (sourceFingerprint) {+ await service.failWriting({+ sessionId: payload.sessionId,+ sourceFingerprint,+ topicId: payload.topicId,+ });+ await publishOnboardingGenerationProgress(payload.userId, payload.topicId);+ }+ }+ } catch (error) {+ if (!isTerminalizedSession(error)) throw error;+ }+return { failedProviderIds: failedProviderIds.sort() };};+/**+ * Supplies validation and terminal failure handling for the provider workflow route.+ *+ * Use when:+ * - Registering the provider handler with Upstash Workflow+ *+ * Expects:+ * - JSON payloads matching the provider workflow schema+ *+ * Returns:+ * - Public workflow serve options with revision-scoped failure compensation+ *+ * Call stack:+ *+ * workflow route+ * -> processProvidersWorkflowOptions.failureFunction+ * -> {@link failRunningUnderstandingProviders}+ */export const processProvidersWorkflowOptions = {failureFunction: async ({context: { requestPayload },diff --git a/packages/database/src/repositories/onboardingUnderstanding/repository.test.ts b/packages/database/src/repositories/onboardingUnderstanding/repository.test.tsindex 716662299aa..33c2e28afaa 100644--- a/packages/database/src/repositories/onboardingUnderstanding/repository.test.ts+++ b/packages/database/src/repositories/onboardingUnderstanding/repository.test.ts@@ -187,6 +187,41 @@ describe('OnboardingUnderstandingRepository', () => {repository = new OnboardingUnderstandingRepository(db, userId);});+ /** @example A provider workflow failure after collection creates terminal writing state. */+ it('records writing failure before a generation is prepared', async () => {+ // ROOT CAUSE:+ //+ // A provider workflow can fail after all sources complete but before prepareWriting runs. The+ // repository previously required an existing writing revision, so its failure callback became a+ // no-op and the session projected as `processing` forever.+ //+ // We fixed this by allowing the current completed fingerprint to initialize failed writing state.+ await repository.initialize(topicId, sessionId, ['github']);+ await completeProvider('github', 3);++ const failed = await repository.failWriting({+ error: {+ code: 'UNDERSTANDING_WRITING_FAILED',+ message: 'understanding writing failed',+ operation: 'writing',+ provider: 'understanding',+ retryable: true,+ },+ feedbackRevision: 0,+ generationRevision: 0,+ sessionId,+ sourceFingerprint: 'github@1',+ topicId,+ });++ expect(failed.writing).toMatchObject({+ feedbackRevision: 0,+ generationRevision: 0,+ sourceFingerprint: 'github@1',+ status: 'failed',+ });+ });+/** @example A fresh onboarding run cannot inherit completed starter-task recommendations. */it('removes Understanding and task recommendations together on reset', async () => {const taskRecommendations: OnboardingTaskRecommendationSession = {diff --git a/packages/database/src/repositories/onboardingUnderstanding/repository.ts b/packages/database/src/repositories/onboardingUnderstanding/repository.tsindex 449c46c2827..32a2a9958a7 100644--- a/packages/database/src/repositories/onboardingUnderstanding/repository.ts+++ b/packages/database/src/repositories/onboardingUnderstanding/repository.ts@@ -676,12 +676,13 @@ export class OnboardingUnderstandingRepository {this.db.transaction((tx) =>mutateTopicSession(tx, this.userId, topicId, (persisted) => {const session = requireSession(topicId, sessionId, persisted);+ const writing = session.writing;if (getUnderstandingSourceFingerprint(session) !== sourceFingerprint ||- session.writing?.feedbackRevision !== feedbackRevision ||- session.writing?.generationRevision !== generationRevision ||- (session.writing?.sourceFingerprint === sourceFingerprint &&- session.writing.status !== 'running')+ (writing &&+ (writing.feedbackRevision !== feedbackRevision ||+ writing.generationRevision !== generationRevision ||+ (writing.sourceFingerprint === sourceFingerprint && writing.status !== 'running')))) {return { nextSession: session, result: session, write: false };}@@ -691,7 +692,7 @@ export class OnboardingUnderstandingRepository {error,feedbackRevision,generationRevision,- resultMessageId: session.writing?.resultMessageId,+ resultMessageId: writing?.resultMessageId,sourceFingerprint,status: 'failed',updatedAt: new Date().toISOString(),