🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(onboarding): stream understanding generation progress (#18105)
Neko2ac91164b1c6
diff --git a/apps/server/src/routers/lambda/__tests__/user.test.ts b/apps/server/src/routers/lambda/__tests__/user.test.tsindex 9f65d9d3242..f1ad724dee0 100644--- a/apps/server/src/routers/lambda/__tests__/user.test.ts+++ b/apps/server/src/routers/lambda/__tests__/user.test.ts@@ -6,6 +6,7 @@ import {UnderstandingSessionNotFoundError,} from '@lobechat/database';import { Plans } from '@lobechat/types';+import { isTrackedEnvelope } from '@trpc/server';import { beforeEach, describe, expect, it, vi } from 'vitest';import {@@ -37,6 +38,8 @@ const mockUnderstandingService = vi.hoisted(() => ({start: vi.fn(),}));const mockCreateUnderstandingService = vi.hoisted(() => vi.fn());+const mockTaskRecommendationService = vi.hoisted(() => ({ get: vi.fn() }));+const mockCreateTaskRecommendationService = vi.hoisted(() => vi.fn());// Mock modulesvi.mock('@/server/utils/scheduleAfterResponse', () => ({@@ -80,6 +83,14 @@ vi.mock('@/server/services/user');vi.mock('@/server/services/understanding/service', () => ({createUnderstandingService: mockCreateUnderstandingService,}));+vi.mock('@/server/services/taskRecommendation/service', () => {+ class TaskRecommendationNotFoundError extends Error {}++ return {+ createTaskRecommendationService: mockCreateTaskRecommendationService,+ TaskRecommendationNotFoundError,+ };+});vi.mock('@/server/workflows/onboardingUnderstanding', () => {class UnderstandingWorkflowUnavailableError extends Error {}@@ -103,10 +114,13 @@ describe('userRouter', () => {vi.clearAllMocks();for (const method of Object.values(mockUnderstandingService)) method.mockReset();mockCreateUnderstandingService.mockReset();+ mockTaskRecommendationService.get.mockReset();+ mockCreateTaskRecommendationService.mockReset();vi.mocked(getReferralStatus).mockResolvedValue(undefined);vi.mocked(getSubscriptionPlan).mockResolvedValue(Plans.Free);vi.mocked(onUserActivityForBusiness).mockResolvedValue(undefined);mockCreateUnderstandingService.mockResolvedValue(mockUnderstandingService);+ mockCreateTaskRecommendationService.mockResolvedValue(mockTaskRecommendationService);});describe('onboarding understanding', () => {@@ -219,6 +233,216 @@ describe('userRouter', () => {expect(mockUnderstandingService.retry).not.toHaveBeenCalled();});+ /** @example A completed session emits one tracked event and closes the SSE stream. */+ it('streams persisted progress without exposing generated onboarding content', async () => {+ mockUnderstandingService.get.mockResolvedValueOnce({+ id: 'session-1',+ sources: {+ github: {+ errors: [],+ failedCount: 0,+ revision: 1,+ status: 'completed',+ succeededCount: 2,+ },+ },+ status: 'completed',+ writing: {+ resultMessageId: 'message-1',+ sourceFingerprint: 'github@1',+ status: 'completed',+ updatedAt: '2026-08-09T00:00:00.000Z',+ },+ });+ mockTaskRecommendationService.get.mockResolvedValueOnce(undefined);++ const stream = await userRouter+ .createCaller(scopedCtx)+ .watchOnboardingGenerationProgress({ topicId: 'topic-1' });+ const iterator = stream[Symbol.asyncIterator]();+ const first = await iterator.next();++ expect(first.done).toBe(false);+ if (first.done) throw new Error('Expected the progress stream to emit its initial state');+ expect(isTrackedEnvelope(first.value)).toBe(true);+ if (!isTrackedEnvelope(first.value)) throw new Error('Expected a tracked progress event');+ expect(first.value[0]).toContain('session-1');+ expect(first.value[1]).toEqual({+ phase: 'completed',+ sessionId: 'session-1',+ steps: {+ collectSources: 'completed',+ detailedPersona: 'pending',+ taskRecommendations: 'pending',+ understanding: 'completed',+ },+ });+ await expect(iterator.next()).resolves.toMatchObject({ done: true });+ });++ /** @example An initialized session without a connected provider is still collecting sources. */+ it('keeps an empty pending session in the collecting-sources phase', async () => {+ mockUnderstandingService.get.mockResolvedValueOnce({+ id: 'session-1',+ sources: {},+ status: 'pending',+ });+ mockTaskRecommendationService.get.mockResolvedValueOnce(undefined);++ const stream = await userRouter+ .createCaller(scopedCtx)+ .watchOnboardingGenerationProgress({ topicId: 'topic-1' });+ const iterator = stream[Symbol.asyncIterator]();+ const first = await iterator.next();++ expect(first.done).toBe(false);+ if (first.done) throw new Error('Expected the pending progress event');+ expect(isTrackedEnvelope(first.value)).toBe(true);+ if (!isTrackedEnvelope(first.value)) throw new Error('Expected a tracked progress event');+ expect(first.value[1]).toEqual({+ phase: 'collecting-sources',+ sessionId: 'session-1',+ steps: {+ collectSources: 'pending',+ detailedPersona: 'pending',+ taskRecommendations: 'pending',+ understanding: 'pending',+ },+ });+ await iterator.return?.();+ });++ /** @example A completed source waits for the downstream writer instead of ending the stream. */+ it('keeps the durable downstream scheduling window active after the last source completes', async () => {+ mockUnderstandingService.get.mockResolvedValueOnce({+ id: 'session-1',+ sources: {+ github: {+ errors: [],+ failedCount: 0,+ revision: 1,+ status: 'completed',+ succeededCount: 2,+ },+ },+ status: 'processing',+ });+ mockTaskRecommendationService.get.mockResolvedValueOnce(undefined);++ const stream = await userRouter+ .createCaller(scopedCtx)+ .watchOnboardingGenerationProgress({ topicId: 'topic-1' });+ const iterator = stream[Symbol.asyncIterator]();+ const first = await iterator.next();++ expect(first.done).toBe(false);+ if (first.done || !isTrackedEnvelope(first.value)) {+ throw new Error('Expected a tracked progress event during downstream scheduling');+ }+ expect(first.value[1]).toMatchObject({+ phase: 'generating-understanding',+ steps: { understanding: 'pending' },+ });+ await iterator.return?.();+ });++ /** @example The UI can distinguish each active generation stage without receiving content. */+ it('projects writing, detailed-persona, and task-recommendation stages', async () => {+ const cases = [+ {+ expectedPhase: 'generating-understanding',+ taskRecommendations: undefined,+ writing: { status: 'running' as const, updatedAt: '2026-08-09T00:00:00.000Z' },+ },+ {+ expectedPhase: 'generating-detailed-persona',+ taskRecommendations: undefined,+ writing: {+ detailed: { status: 'running' as const, updatedAt: '2026-08-09T00:00:00.000Z' },+ status: 'completed' as const,+ updatedAt: '2026-08-09T00:00:00.000Z',+ },+ },+ {+ expectedPhase: 'recommending-tasks',+ taskRecommendations: { status: 'processing' as const },+ writing: { status: 'completed' as const, updatedAt: '2026-08-09T00:00:00.000Z' },+ },+ ];++ for (const { expectedPhase, taskRecommendations, writing } of cases) {+ mockUnderstandingService.get.mockResolvedValueOnce({+ id: 'session-1',+ sources: {+ github: {+ errors: [],+ failedCount: 0,+ revision: 1,+ status: 'completed',+ succeededCount: 2,+ },+ },+ status: 'processing',+ writing,+ });+ mockTaskRecommendationService.get.mockResolvedValueOnce(taskRecommendations);++ const stream = await userRouter+ .createCaller(scopedCtx)+ .watchOnboardingGenerationProgress({ topicId: 'topic-1' });+ const iterator = stream[Symbol.asyncIterator]();+ const first = await iterator.next();++ expect(first.done).toBe(false);+ if (first.done || !isTrackedEnvelope(first.value)) {+ throw new Error('Expected a tracked active progress event');+ }+ expect(first.value[1]).toMatchObject({ phase: expectedPhase });+ await iterator.return?.();+ }+ });++ /** @example A reconnect cursor suppresses a duplicate terminal progress event. */+ it('deduplicates a persisted terminal event after reconnecting with its tracked cursor', async () => {+ const understanding = {+ id: 'session-1',+ sources: {+ github: {+ errors: [],+ failedCount: 0,+ revision: 1,+ status: 'completed' as const,+ succeededCount: 2,+ },+ },+ status: 'completed' as const,+ writing: {+ resultMessageId: 'message-1',+ sourceFingerprint: 'github@1',+ status: 'completed' as const,+ updatedAt: '2026-08-09T00:00:00.000Z',+ },+ };+ mockUnderstandingService.get.mockResolvedValue(understanding);+ mockTaskRecommendationService.get.mockResolvedValue(undefined);++ const firstStream = await userRouter+ .createCaller(scopedCtx)+ .watchOnboardingGenerationProgress({ topicId: 'topic-1' });+ const first = await firstStream[Symbol.asyncIterator]().next();+ if (first.done) throw new Error('Expected the initial progress event');+ expect(isTrackedEnvelope(first.value)).toBe(true);+ if (!isTrackedEnvelope(first.value)) throw new Error('Expected a tracked progress event');++ const resumedStream = await userRouter+ .createCaller(scopedCtx)+ .watchOnboardingGenerationProgress({ lastEventId: first.value[0], topicId: 'topic-1' });++ await expect(resumedStream[Symbol.asyncIterator]().next()).resolves.toMatchObject({+ done: true,+ });+ });+it('delegates retry for only the requested provider', async () => {mockUnderstandingService.retry.mockResolvedValueOnce(pollingResult);diff --git a/apps/server/src/routers/lambda/user.ts b/apps/server/src/routers/lambda/user.tsindex 1a71f63a727..6b26459cfe7 100644--- a/apps/server/src/routers/lambda/user.ts+++ b/apps/server/src/routers/lambda/user.ts@@ -32,7 +32,7 @@ import {UserSettingsSchema,} from '@lobechat/types';import { errorCauseFrom } from '@lobechat/utils';-import { TRPCError } from '@trpc/server';+import { tracked, TRPCError } from '@trpc/server';import { v4 as uuidv4 } from 'uuid';import { z } from 'zod';@@ -57,7 +57,15 @@ import {import { AgentDocumentsService } from '@/server/services/agentDocuments';import { FileService } from '@/server/services/file';import { OnboardingService } from '@/server/services/onboarding';-import { createTaskRecommendationService } from '@/server/services/taskRecommendation/service';+import {+ onboardingProgressEventId,+ projectOnboardingGenerationProgress,+ subscribeToOnboardingGenerationProgress,+} from '@/server/services/onboardingProgress';+import {+ createTaskRecommendationService,+ TaskRecommendationNotFoundError,+} from '@/server/services/taskRecommendation/service';import { understandingProviders } from '@/server/services/understanding/providers';import { createUnderstandingService } from '@/server/services/understanding/service';import { after } from '@/server/utils/scheduleAfterResponse';@@ -142,6 +150,14 @@ const reviseOnboardingUnderstandingInputSchema = zconst onboardingTaskRecommendationTopicInputSchema = z.object({ topicId: understandingIdSchema }).strict() satisfies z.ZodType<OnboardingTaskRecommendationTopicInput>;+const onboardingGenerationProgressInputSchema = z+ .object({+ // tRPC injects this tracked cursor into reconnection inputs. It is intentionally not trusted+ // as application state; polling remains the durable source of truth.+ lastEventId: z.string().trim().min(1).max(4096).optional(),+ topicId: understandingIdSchema,+ })+ .strict();const createOnboardingTasksInputSchema = z.object({recommendationIds: z.array(z.string().trim().min(1).max(128)).max(48),@@ -237,6 +253,35 @@ const taskRecommendationServiceProcedure = personalOnboardingProcedure.use(return result;},);+const onboardingGenerationProgressProcedure = personalOnboardingProcedure.use(+ async ({ ctx, next }) => {+ const [understandingService, taskRecommendationService] = await Promise.all([+ createUnderstandingService({ db: ctx.serverDB, userId: ctx.userId }),+ createTaskRecommendationService({ db: ctx.serverDB, userId: ctx.userId }),+ ]);+ const result = await next({ ctx: { taskRecommendationService, understandingService } });+ if (!result.ok) {+ throw mapUnderstandingTRPCError(errorCauseFrom(result.error) ?? result.error);+ }+ return result;+ },+);++const INITIAL_PROGRESS_RECOVERY_DELAY = 3_000;+const MAX_PROGRESS_RECOVERY_DELAY = 30_000;++const waitForProgressRecovery = (delay: number, signal: AbortSignal | undefined) =>+ new Promise<void>((resolve) => {+ const timer = setTimeout(resolve, delay);+ signal?.addEventListener(+ 'abort',+ () => {+ clearTimeout(timer);+ resolve();+ },+ { once: true },+ );+ });export const userRouter = router({getUserActivitySummary: userProcedure.query(async ({ ctx }) => {@@ -274,6 +319,83 @@ export const userRouter = router({return ctx.taskRecommendationService.get(input.topicId);}),+ watchOnboardingGenerationProgress: onboardingGenerationProgressProcedure+ .input(onboardingGenerationProgressInputSchema)+ .subscription(async function* ({ ctx, input, signal }) {+ let lastEventId = input.lastEventId;+ const readPersistedProgress = async () => {+ const understanding = await ctx.understandingService.get(input.topicId);+ const taskRecommendations = await ctx.taskRecommendationService+ .get(input.topicId)+ .catch((error: unknown) => {+ if (error instanceof TaskRecommendationNotFoundError) return undefined;+ throw error;+ });+ const eventId = onboardingProgressEventId(understanding, taskRecommendations);+ const progress = projectOnboardingGenerationProgress(understanding, taskRecommendations);+ return { eventId, progress };+ };++ const initial = await readPersistedProgress();+ if (initial.eventId !== lastEventId) {+ lastEventId = initial.eventId;+ yield tracked(initial.eventId, initial.progress);+ }+ if (+ initial.progress.phase === 'completed' ||+ initial.progress.phase === 'failed' ||+ initial.progress.phase === 'partial'+ ) {+ return;+ }++ const subscription = await subscribeToOnboardingGenerationProgress(input.topicId);+ if (subscription) {+ try {+ while (!signal?.aborted) {+ const notification = await subscription.next(signal);+ if (!notification) return;++ if (notification.eventId !== lastEventId) {+ lastEventId = notification.eventId;+ yield tracked(notification.eventId, notification.progress);+ }+ if (+ notification.progress.phase === 'completed' ||+ notification.progress.phase === 'failed' ||+ notification.progress.phase === 'partial'+ ) {+ return;+ }+ }+ } finally {+ await subscription.unsubscribe();+ }+ return;+ }++ let recoveryDelay = INITIAL_PROGRESS_RECOVERY_DELAY;+ while (!signal?.aborted) {+ await waitForProgressRecovery(recoveryDelay, signal);+ if (signal?.aborted) return;++ const { eventId, progress } = await readPersistedProgress();+ if (eventId !== lastEventId) {+ lastEventId = eventId;+ yield tracked(eventId, progress);+ }++ if (+ progress.phase === 'completed' ||+ progress.phase === 'failed' ||+ progress.phase === 'partial'+ ) {+ return;+ }+ recoveryDelay = Math.min(recoveryDelay * 2, MAX_PROGRESS_RECOVERY_DELAY);+ }+ }),+getSupportedUnderstandingProviders: understandingServiceProcedure.query(async ({ ctx }): Promise<{ providerIds: string[]; sourceProviderIds: string[] }> => {return {diff --git a/apps/server/src/services/onboardingProgress/index.ts b/apps/server/src/services/onboardingProgress/index.tsnew file mode 100644index 00000000000..b685b5d85c0--- /dev/null+++ b/apps/server/src/services/onboardingProgress/index.ts@@ -0,0 +1,256 @@+import type {+ OnboardingGenerationProgressEvent,+ OnboardingTaskRecommendationPollingResult,+ OnboardingUnderstandingPollingResult,+} from '@lobechat/types';++import { getServerDB } from '@/database/server';+import { getRedisConfig } from '@/envs/redis';+import { isRedisEnabled } from '@/libs/redis';+import {+ createTaskRecommendationService,+ TaskRecommendationNotFoundError,+} from '@/server/services/taskRecommendation/service';+import { createUnderstandingService } from '@/server/services/understanding/service';++const PROGRESS_CHANNEL_PREFIX = 'onboarding-generation-progress';++interface ProgressEnvelope {+ eventId: string;+ progress: OnboardingGenerationProgressEvent;+}++interface ProgressSubscription {+ next: (signal?: AbortSignal) => Promise<ProgressEnvelope | undefined>;+ unsubscribe: () => Promise<void>;+}++const toProgressStatus = (+ status: 'completed' | 'failed' | 'partial' | 'pending' | 'processing' | 'running' | undefined,+): OnboardingGenerationProgressEvent['steps']['collectSources'] => {+ if (status === 'processing') return 'running';+ if (status === 'partial') return 'completed';+ return status ?? 'pending';+};++/**+ * Projects persisted onboarding workflow state into a content-free progress event.+ *+ * The session-level processing state covers the durable scheduling window after the+ * final source completes and before a downstream workflow has written its own state.+ */+export const projectOnboardingGenerationProgress = (+ understanding: OnboardingUnderstandingPollingResult,+ taskRecommendations: OnboardingTaskRecommendationPollingResult | undefined,+): OnboardingGenerationProgressEvent => {+ const sourceStatuses = Object.values(understanding.sources).map((source) => source.status);+ const collectSources: OnboardingGenerationProgressEvent['steps']['collectSources'] =+ sourceStatuses.some((status) => status === 'pending' || status === 'running')+ ? 'running'+ : sourceStatuses.length > 0 && sourceStatuses.every((status) => status === 'failed')+ ? 'failed'+ : sourceStatuses.length > 0+ ? 'completed'+ : 'pending';+ const understandingStatus = toProgressStatus(understanding.writing?.status);+ const detailedPersona = toProgressStatus(understanding.writing?.detailed?.status);+ const taskRecommendationsStatus = toProgressStatus(taskRecommendations?.status);+ const steps = {+ collectSources,+ detailedPersona,+ taskRecommendations: taskRecommendationsStatus,+ understanding: understandingStatus,+ };++ if (understanding.status === 'failed') {+ return { phase: 'failed', sessionId: understanding.id, steps };+ }+ if (understanding.status === 'partial') {+ return { phase: 'partial', sessionId: understanding.id, steps };+ }+ if (taskRecommendations?.status === 'failed' || taskRecommendations?.status === 'partial') {+ return { phase: 'partial', sessionId: understanding.id, steps };+ }+ if (collectSources === 'pending' || collectSources === 'running') {+ return { phase: 'collecting-sources', sessionId: understanding.id, steps };+ }+ if (understandingStatus === 'running') {+ return { phase: 'generating-understanding', sessionId: understanding.id, steps };+ }+ if (detailedPersona === 'running') {+ return { phase: 'generating-detailed-persona', sessionId: understanding.id, steps };+ }+ if (taskRecommendationsStatus === 'running') {+ return { phase: 'recommending-tasks', sessionId: understanding.id, steps };+ }+ if (understanding.status === 'processing') {+ return { phase: 'generating-understanding', sessionId: understanding.id, steps };+ }+ return { phase: 'completed', sessionId: understanding.id, steps };+};++/** Builds a stable opaque ID from persisted state for SSE reconnection deduplication. */+export const onboardingProgressEventId = (+ understanding: OnboardingUnderstandingPollingResult,+ taskRecommendations: OnboardingTaskRecommendationPollingResult | undefined,+) =>+ [+ understanding.id,+ understanding.generationRevision ?? 0,+ ...Object.entries(understanding.sources)+ .toSorted(([left], [right]) => left.localeCompare(right))+ .map(([providerId, source]) =>+ [providerId, source.revision, source.status, source.completedAt ?? ''].join(':'),+ ),+ understanding.writing?.status ?? '',+ understanding.writing?.updatedAt ?? '',+ understanding.writing?.detailed?.status ?? '',+ understanding.writing?.detailed?.updatedAt ?? '',+ taskRecommendations?.status ?? '',+ taskRecommendations?.updatedAt ?? '',+ ].join('|');++const progressChannel = (prefix: string, topicId: string) =>+ `${prefix}:${PROGRESS_CHANNEL_PREFIX}:${topicId}`;++const isProgressEnvelope = (value: unknown): value is ProgressEnvelope => {+ if (!value || typeof value !== 'object') return false;+ const envelope = value as Record<string, unknown>;+ return typeof envelope.eventId === 'string' && Boolean(envelope.progress);+};++const createRedisClient = async () => {+ const config = getRedisConfig();+ if (!isRedisEnabled(config)) return;++ const Redis = (await import('ioredis')).default;+ return new Redis(config.url, {+ commandTimeout: 10_000,+ connectTimeout: 10_000,+ db: config.database,+ lazyConnect: true,+ maxRetriesPerRequest: 2,+ password: config.password,+ tls: config.tls ? {} : undefined,+ username: config.username,+ });+};++/**+ * Publishes one durable progress snapshot after an onboarding workflow state transition.+ *+ * Redis delivery is intentionally best-effort: polling remains the recovery path when Redis is+ * disabled or a Pub/Sub message is missed.+ */+export const publishOnboardingGenerationProgress = async (userId: string, topicId: string) => {+ const config = getRedisConfig();+ if (!isRedisEnabled(config)) return;++ let redis: Awaited<ReturnType<typeof createRedisClient>>;+ try {+ redis = await createRedisClient();+ if (!redis) return;+ await redis.connect();++ const db = await getServerDB();+ const [understandingService, taskRecommendationService] = await Promise.all([+ createUnderstandingService({ db, userId }),+ createTaskRecommendationService({ db, userId }),+ ]);+ const understanding = await understandingService.get(topicId);+ const taskRecommendations = await taskRecommendationService+ .get(topicId)+ .catch((error: unknown) => {+ if (error instanceof TaskRecommendationNotFoundError) return undefined;+ throw error;+ });+ const progress = projectOnboardingGenerationProgress(understanding, taskRecommendations);+ const eventId = onboardingProgressEventId(understanding, taskRecommendations);++ await redis.publish(+ progressChannel(config.prefix, topicId),+ JSON.stringify({ eventId, progress }),+ );+ } catch (error) {+ // NOTICE:+ // Progress notifications are an acceleration path and must never fail the durable workflow.+ // The client polls persisted state after missed Redis events or unavailable Redis.+ console.error('[onboardingProgress] Failed to publish workflow progress', error);+ } finally {+ if (redis) await redis.quit().catch(() => undefined);+ }+};++/**+ * Bridges a Redis Pub/Sub channel into an awaitable subscription for one authenticated topic.+ *+ * The returned subscription is undefined when Redis is intentionally unavailable; callers then+ * use the bounded polling recovery path rather than keeping a database polling loop per SSE client.+ */+export const subscribeToOnboardingGenerationProgress = async (+ topicId: string,+): Promise<ProgressSubscription | undefined> => {+ const config = getRedisConfig();+ if (!isRedisEnabled(config)) return;++ const redis = await createRedisClient();+ if (!redis) return;+ const channel = progressChannel(config.prefix, topicId);+ const queued: ProgressEnvelope[] = [];+ let resolveNext: ((value: ProgressEnvelope | undefined) => void) | undefined;++ const onMessage = (receivedChannel: string, message: string) => {+ if (receivedChannel !== channel) return;+ try {+ const parsed: unknown = JSON.parse(message);+ if (!isProgressEnvelope(parsed)) return;+ if (resolveNext) {+ const resolve = resolveNext;+ resolveNext = undefined;+ resolve(parsed);+ } else {+ queued.push(parsed);+ }+ } catch {+ // Redis channels are an internal boundary; ignore malformed best-effort notifications.+ }+ };++ try {+ await redis.connect();+ redis.on('message', onMessage);+ await redis.subscribe(channel);+ } catch (error) {+ await redis.quit().catch(() => undefined);+ console.error('[onboardingProgress] Failed to subscribe to workflow progress', error);+ return;+ }++ return {+ next: (signal) => {+ const pending = queued.shift();+ if (pending) return Promise.resolve(pending);+ if (signal?.aborted) return Promise.resolve(undefined);++ return new Promise((resolve) => {+ const onAbort = () => {+ signal?.removeEventListener('abort', onAbort);+ if (resolveNext === resolve) resolveNext = undefined;+ resolve(undefined);+ };+ resolveNext = (event) => {+ signal?.removeEventListener('abort', onAbort);+ resolve(event);+ };+ signal?.addEventListener('abort', onAbort, { once: true });+ });+ },+ unsubscribe: async () => {+ resolveNext?.(undefined);+ resolveNext = undefined;+ redis.removeListener('message', onMessage);+ await redis.unsubscribe(channel).catch(() => undefined);+ await redis.quit().catch(() => undefined);+ },+ };+};diff --git a/apps/server/src/workflows/onboardingTaskRecommendation/process.ts b/apps/server/src/workflows/onboardingTaskRecommendation/process.tsindex c93fad139a0..6660d1f20a7 100644--- a/apps/server/src/workflows/onboardingTaskRecommendation/process.ts+++ b/apps/server/src/workflows/onboardingTaskRecommendation/process.ts@@ -2,6 +2,7 @@ import { errorNameFrom } from '@lobechat/utils';import type { PublicServeOptions, WorkflowContext } from '@upstash/workflow';import { getServerDB } from '@/database/server';+import { publishOnboardingGenerationProgress } from '@/server/services/onboardingProgress';import {createTaskRecommendationService,type TaskRecommendationProviderResult,@@ -49,6 +50,7 @@ export const processOnboardingTaskRecommendations = async (const plan = await context.run('session:begin', () =>service.begin(payload.topicId, payload.sessionId, payload.sourceFingerprint),);+ await publishOnboardingGenerationProgress(payload.userId, payload.topicId);if (!plan.ready) return service.get(payload.topicId);const results = await Promise.all(@@ -77,9 +79,11 @@ export const processOnboardingTaskRecommendations = async (),),);- return context.run('session:commit', () =>+ const session = await context.run('session:commit', () =>service.commit(payload.topicId, payload.sessionId, results),);+ await publishOnboardingGenerationProgress(payload.userId, payload.topicId);+ return session;};/** Terminalizes a recommendation session after workflow-level retries are exhausted. */@@ -89,7 +93,9 @@ export const failOnboardingTaskRecommendations = async () => {const payload = ProcessOnboardingTaskRecommendationPayloadSchema.parse(input);const service = await (dependencies.createService ?? createService)(payload.userId);- return service.fail(payload.topicId, payload.sessionId);+ const failed = await service.fail(payload.topicId, payload.sessionId);+ if (failed) await publishOnboardingGenerationProgress(payload.userId, payload.topicId);+ return failed;};/** Upstash parser and failure callback for the recommendation workflow endpoint. */diff --git a/apps/server/src/workflows/onboardingUnderstanding/processCollected.ts b/apps/server/src/workflows/onboardingUnderstanding/processCollected.tsindex d0e5fac7cc4..844ccb72759 100644--- a/apps/server/src/workflows/onboardingUnderstanding/processCollected.ts+++ b/apps/server/src/workflows/onboardingUnderstanding/processCollected.ts@@ -9,6 +9,7 @@ import {import type { PublicServeOptions, WorkflowContext } from '@upstash/workflow';import { getServerDB } from '@/database/server';+import { publishOnboardingGenerationProgress } from '@/server/services/onboardingProgress';import {createUnderstandingService,type UnderstandingService,@@ -67,6 +68,7 @@ export const processCollectedUnderstanding = async (throw error;}});+ await publishOnboardingGenerationProgress(payload.userId, payload.topicId);const triggerDetailedPersona = dependencies.triggerDetailedPersona;if (result.published && triggerDetailedPersona) {await context.run('collected:trigger-detailed-persona', () =>@@ -105,8 +107,11 @@ export const failRunningUnderstandingWriting = async (sourceFingerprint: payload.sourceFingerprint,topicId: payload.topicId,});+ if (detailedFailed)+ await publishOnboardingGenerationProgress(payload.userId, payload.topicId);return { failed: Boolean(detailedFailed) };}+ await publishOnboardingGenerationProgress(payload.userId, payload.topicId);} catch (error) {if (isStaleSession(error)) return { failed: false as const };throw error;diff --git a/apps/server/src/workflows/onboardingUnderstanding/processDetailedPersona.ts b/apps/server/src/workflows/onboardingUnderstanding/processDetailedPersona.tsindex 55594e2eaba..eef0a6d0090 100644--- a/apps/server/src/workflows/onboardingUnderstanding/processDetailedPersona.ts+++ b/apps/server/src/workflows/onboardingUnderstanding/processDetailedPersona.ts@@ -7,6 +7,7 @@ import {import type { PublicServeOptions, WorkflowContext } from '@upstash/workflow';import { getServerDB } from '@/database/server';+import { publishOnboardingGenerationProgress } from '@/server/services/onboardingProgress';import {createUnderstandingService,type UnderstandingService,@@ -64,7 +65,7 @@ export const processDetailedUnderstandingPersona = async () => {const payload = ProcessCollectedUnderstandingPayloadSchema.parse(context.requestPayload);const service = await (dependencies.createService ?? createService)(payload.userId);- return context.run('detailed-persona:process', async () => {+ const result = await context.run('detailed-persona:process', async () => {try {return await service.processDetailedPersona({expectedSourceFingerprint: payload.sourceFingerprint,@@ -79,6 +80,8 @@ export const processDetailedUnderstandingPersona = async (throw error;}});+ await publishOnboardingGenerationProgress(payload.userId, payload.topicId);+ return result;};/**@@ -105,6 +108,7 @@ export const failRunningDetailedUnderstandingPersona = async (sourceFingerprint: payload.sourceFingerprint,topicId: payload.topicId,});+ if (failed) await publishOnboardingGenerationProgress(payload.userId, payload.topicId);return { failed: Boolean(failed) };} catch (error) {if (isStaleSession(error)) return { failed: false };diff --git a/apps/server/src/workflows/onboardingUnderstanding/processProviders.ts b/apps/server/src/workflows/onboardingUnderstanding/processProviders.tsindex 986b1e83ea2..53ab2b8ee68 100644--- a/apps/server/src/workflows/onboardingUnderstanding/processProviders.ts+++ b/apps/server/src/workflows/onboardingUnderstanding/processProviders.ts@@ -8,6 +8,7 @@ import {import type { InvokableWorkflow, PublicServeOptions, WorkflowContext } from '@upstash/workflow';import { getServerDB } from '@/database/server';+import { publishOnboardingGenerationProgress } from '@/server/services/onboardingProgress';import {createUnderstandingService,type UnderstandingService,@@ -90,6 +91,7 @@ export const processUnderstandingProviders = async (topicId: payload.topicId,}),);+ await publishOnboardingGenerationProgress(payload.userId, payload.topicId);if (result.status === 'completed' && result.revision === revision) {const body = {responseLanguage: payload.responseLanguage,@@ -169,7 +171,10 @@ export const failRunningUnderstandingProviders = async (sessionId: payload.sessionId,topicId: payload.topicId,});- if (failed) failedProviderIds.push(providerId);+ if (failed) {+ failedProviderIds.push(providerId);+ await publishOnboardingGenerationProgress(payload.userId, payload.topicId);+ }} catch (error) {if (!isTerminalizedSession(error)) throw error;}diff --git a/packages/trpc/src/client/lambda.ts b/packages/trpc/src/client/lambda.tsindex 112ebbcfe04..00e9babf506 100644--- a/packages/trpc/src/client/lambda.ts+++ b/packages/trpc/src/client/lambda.ts@@ -1,6 +1,12 @@import { isRemoteServerNetworkError } from '@lobechat/types';import { type TRPCLink } from '@trpc/client';-import { createTRPCClient, httpBatchLink, httpLink, splitLink } from '@trpc/client';+import {+ createTRPCClient,+ httpBatchLink,+ httpLink,+ httpSubscriptionLink,+ splitLink,+} from '@trpc/client';import { createTRPCReact } from '@trpc/react-query';import { observable } from '@trpc/server/observable';import debug from 'debug';@@ -170,9 +176,15 @@ const SKIP_BATCH_PROCEDURES = new Set([...initialLoadProcedures, ...slowProcedur// 3. splitLink to conditionally disable batchingconst customSplitLink = splitLink({- condition: (op) => SKIP_BATCH_PROCEDURES.has(op.path),- false: httpBatchLink({ ...linkOptions, maxURLLength: 2083 }),- true: httpLink(linkOptions),+ condition: (op) => op.type === 'subscription',+ false: splitLink({+ condition: (op) => SKIP_BATCH_PROCEDURES.has(op.path),+ false: httpBatchLink({ ...linkOptions, maxURLLength: 2083 }),+ true: httpLink(linkOptions),+ }),+ // EventSource sends the same-origin session cookie. Subscription event payloads are progress+ // hints only; all durable onboarding state is still read via the authenticated polling calls.+ true: httpSubscriptionLink({ transformer: superjson, url: linkOptions.url }),});// 4. assembly links@@ -204,9 +216,13 @@ export const createWorkspaceLambdaClient = (workspaceId: string) => {links: [errorHandlingLink,splitLink({- condition: (op) => SKIP_BATCH_PROCEDURES.has(op.path),- false: httpBatchLink({ ...scopedLinkOptions, maxURLLength: 2083 }),- true: httpLink(scopedLinkOptions),+ condition: (op) => op.type === 'subscription',+ false: splitLink({+ condition: (op) => SKIP_BATCH_PROCEDURES.has(op.path),+ false: httpBatchLink({ ...scopedLinkOptions, maxURLLength: 2083 }),+ true: httpLink(scopedLinkOptions),+ }),+ true: httpSubscriptionLink({ transformer: superjson, url: scopedLinkOptions.url }),}),],});diff --git a/packages/types/src/understanding.ts b/packages/types/src/understanding.tsindex 2d6a61118b0..c07ab06ecb4 100644--- a/packages/types/src/understanding.ts+++ b/packages/types/src/understanding.ts@@ -228,6 +228,39 @@ export interface OnboardingUnderstandingPollingResult {writing?: UnderstandingWritingState;}+/** A durable-workflow stage exposed as a progress-only SSE signal. */+export type OnboardingGenerationProgressPhase =+ | 'collecting-sources'+ | 'generating-understanding'+ | 'generating-detailed-persona'+ | 'recommending-tasks'+ | 'completed'+ | 'partial'+ | 'failed';++/** Progress state for one durable onboarding generation step. */+export type OnboardingGenerationProgressStepStatus = 'pending' | 'running' | 'completed' | 'failed';++/**+ * Progress-only event emitted by the onboarding generation SSE subscription.+ *+ * The event intentionally carries no generated content. Clients must refresh the polling+ * endpoints after receiving it because persisted polling state remains authoritative.+ */+export interface OnboardingGenerationProgressEvent {+ /** Coarse workflow phase for lightweight progress feedback. */+ phase: OnboardingGenerationProgressPhase;+ /** Current session that owns the persisted Understanding state. */+ sessionId: string;+ /** Per-step states; phases may overlap while independent durable work is running. */+ steps: {+ collectSources: OnboardingGenerationProgressStepStatus;+ detailedPersona: OnboardingGenerationProgressStepStatus;+ taskRecommendations: OnboardingGenerationProgressStepStatus;+ understanding: OnboardingGenerationProgressStepStatus;+ };+}+export interface OnboardingUnderstandingTopicInput {topicId: string;}