🤯 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
♻️ refactor(understanding): split the 1350-line understanding service into cohesive modules (#21146)
Arvin Xub55a4c98adea
diff --git a/apps/server/src/services/understanding/service.ts b/apps/server/src/services/understanding/service.tsdeleted file mode 100644index 15ff55a07d6..00000000000--- a/apps/server/src/services/understanding/service.ts+++ /dev/null@@ -1,1350 +0,0 @@-import { createHash, randomUUID } from 'node:crypto';--import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';-import {- ConnectorDataError,- getConnectorErrorMessage,- isConnectorErrorRetryable,-} from '@lobechat/connector-data';-import { TRACING_SCENARIOS } from '@lobechat/const';-import {- getUnderstandingSourceFingerprint,- OnboardingUnderstandingRepository,- StaleUnderstandingRevisionError,- StaleUnderstandingSessionError,- UnderstandingPreconditionError,- UnderstandingResourceNotFoundError,- UnderstandingSessionNotFoundError,-} from '@lobechat/database';-import {- observeOnboardingUnderstandingOperation,- observeOnboardingUnderstandingProviderCollection,-} from '@lobechat/observability-otel/modules/onboarding-understanding';-import {- chainUnderstandingDetailedPersona,- chainUnderstandingPersona,- UNDERSTANDING_ANALYSIS_JSON_SCHEMA,- UNDERSTANDING_ANALYSIS_PROMPT_VERSION,- UNDERSTANDING_DETAILED_PERSONA_JSON_SCHEMA,- UNDERSTANDING_DETAILED_PERSONA_PROMPT_VERSION,-} from '@lobechat/prompts';-import type {- CollectionDiagnostics,- CollectionError,- ConfirmOnboardingUnderstandingInput,- OnboardingUnderstandingMessageMetadata,- OnboardingUnderstandingPollingResult,- OnboardingUnderstandingSession,- RetryOnboardingUnderstandingProviderInput,- ReviseOnboardingUnderstandingInput,- UnderstandingFeedbackTurn,- UnderstandingPersonaProposal,-} from '@lobechat/types';-import {- MAX_COLLECTION_COUNT,- MAX_COLLECTION_ERRORS,- OnboardingUnderstandingMessageMetadataSchema,- projectOnboardingUnderstandingSessionStatus,- RequestTrigger,- UnderstandingAnalysisSchema,- UnderstandingPersonaProposalSchema,-} from '@lobechat/types';-import { isPlainRecord } from '@lobechat/utils/object';--import { AgentModel } from '@/database/models/agent';-import { MessageModel } from '@/database/models/message';-import { TopicModel } from '@/database/models/topic';-import { UserPersonaModel } from '@/database/models/userMemory/persona';-import type { LobeChatDatabase } from '@/database/type';-import { AiGenerationService } from '@/server/services/aiGeneration';-import { ConnectorDataService } from '@/server/services/connectorData';--import { understandingProviderMap } from './providers';-import type { StoredUnderstandingProviderContext } from './sourceStore';-import { MAX_SOURCE_BRIEF_LENGTH, UnderstandingSourceStore } from './sourceStore';-import type { UnderstandingProvider } from './types';--const BASELINE_MAX_LENGTH = 8_000;-const MAX_AGENT_INPUT_LENGTH = 128_000;--const boundedCount = (value: number) =>- Number.isFinite(value) ? Math.min(MAX_COLLECTION_COUNT, Math.max(0, Math.floor(value))) : 0;--/**- * Bounds provider diagnostic counts without changing their error content.- *- * Use when:- * - Moving provider collection diagnostics across the service boundary- *- * Expects:- * - Providers return serializable CollectionError values- *- * Returns:- * - Bounded counts and error cardinality with original diagnostics preserved- */-const boundProviderDiagnostics = (value: CollectionDiagnostics): CollectionDiagnostics => ({- errors: value.errors.slice(0, MAX_COLLECTION_ERRORS),- evidenceCount: boundedCount(value.evidenceCount),- failedCount: boundedCount(value.failedCount),- succeededCount: boundedCount(value.succeededCount),-});--/**- * Creates one structured collection error while retaining its original message.- *- * Use when:- * - Converting a structured internal or Connector Data error for persistence- *- * Expects:- * - Provider, operation, and code are supplied by trusted internal code- *- * Returns:- * - A collection error containing the supplied message without replacement- */-const createCollectionError = (- provider: string,- operation: string,- code: string,- retryable: boolean,- message = `${provider} ${operation} failed`,-): CollectionError => ({ code, message, operation, provider, retryable });--interface ProviderOperationInput {- providerId: string;- revision: number;- sessionId: string;- topicId: string;-}--interface ProcessCollectedInput {- expectedSourceFingerprint: string;- responseLanguage: string;- sessionId: string;- topicId: string;-}--type UnderstandingRepository = Pick<- OnboardingUnderstandingRepository,- | 'commitWriting'- | 'commitDetailedWriting'- | 'completeProvider'- | 'confirm'- | 'expireProviderContexts'- | 'extend'- | 'failProvider'- | 'failWriting'- | 'failDetailedWriting'- | 'get'- | 'initialize'- | 'markProviderRunning'- | 'prepareWriting'->;--type UnderstandingContexts = Pick<UnderstandingSourceStore, 'get' | 'put'>;--/** Controls optional downstream work started with an Understanding collection run. */-export interface UnderstandingStartOptions {- /**- * Starts task recommendations as soon as the first source completes.- *- * @default true- */- triggerTaskRecommendations?: boolean;-}--export interface UnderstandingServiceDependencies {- connectorData: ConnectorDataService;- generator: Pick<AiGenerationService, 'generateObject'>;- ids: () => string;- messages: {- create: (params: {- agentId: string;- content: string;- model: string;- provider: string;- role: 'assistant';- threadId: string;- topicId: string;- }) => Promise<{ id: string }>;- findById: (id: string) => Promise<{ content?: unknown; metadata?: unknown } | null | undefined>;- findLatestAssistantMessageByThread: (input: {- agentId: string;- threadId: string;- topicId: string;- }) => Promise<- | { content?: unknown; error?: unknown; id: string; role: string; threadId?: string | null }- | null- | undefined- >;- };- persona: {- getLatestPersonaDocument: () => Promise<- { persona?: string | null; tagline?: string | null } | null | undefined- >;- };- providers: ReadonlyMap<string, UnderstandingProvider>;- repository: UnderstandingRepository;- sourceStore: () => UnderstandingContexts;- topic: {- assertActiveOnboardingTopic: (topicId: string) => Promise<void>;- };- userId: string;- writerAgent: () => Promise<{ id: string; model: string; provider: string }>;-}--export class UnderstandingProviderContextUnavailableError extends Error {- constructor() {- super('Current onboarding Understanding provider context is unavailable');- this.name = 'UnderstandingProviderContextUnavailableError';- }-}--const parseStoredAnalysis = (content: unknown) => {- if (typeof content !== 'string') return;- try {- const parsed = UnderstandingAnalysisSchema.safeParse(JSON.parse(content));- return parsed.success ? parsed.data : undefined;- } catch {- return;- }-};--const writingThreadId = (sessionId: string, sourceFingerprint: string, feedbackRevision: number) =>- `thd_${createHash('sha256')- .update(sessionId)- .update('\0')- .update(sourceFingerprint)- .update('\0')- .update(String(feedbackRevision))- .digest('hex')- .slice(0, 24)}`;--const sumDiagnostics = (- session: OnboardingUnderstandingSession,- contexts: StoredUnderstandingProviderContext[],-): CollectionDiagnostics => {- const terminalSources = Object.values(session.sources).filter(- ({ status }) => status === 'completed' || status === 'failed',- );- return boundProviderDiagnostics({- errors: terminalSources.flatMap(({ errors }) => errors).slice(-MAX_COLLECTION_ERRORS),- evidenceCount: contexts.reduce(- (total, { diagnostics }) => total + diagnostics.evidenceCount,- 0,- ),- failedCount: terminalSources.reduce((total, source) => total + source.failedCount, 0),- succeededCount: terminalSources.reduce((total, source) => total + source.succeededCount, 0),- });-};--const buildEphemeralDocument = (- contexts: StoredUnderstandingProviderContext[],- baseline?: { persona?: string | null; tagline?: string | null } | null,-) => {- const baselineContent = [baseline?.tagline, baseline?.persona]- .filter((value): value is string => Boolean(value?.trim()))- .join('\n\n')- .slice(0, BASELINE_MAX_LENGTH);- const baselineSection = baselineContent- ? `<current-persona-baseline>\n${baselineContent}\n</current-persona-baseline>\n\n`- : '';- const delimiters = contexts.map(({ providerId, revision }) => ({- close: '\n</provider-context>',- open: `<provider-context provider="${providerId}" revision="${revision}">\n`,- }));- const structuralLength =- baselineSection.length +- Math.max(0, contexts.length - 1) * 2 +- delimiters.reduce(- (total, delimiter) => total + delimiter.open.length + delimiter.close.length,- 0,- );- if (structuralLength > MAX_AGENT_INPUT_LENGTH) {- throw new UnderstandingProviderContextUnavailableError();- }- let remainingContent = MAX_AGENT_INPUT_LENGTH - structuralLength;- const providerSections = contexts.map(({ context }, index) => {- const remainingProviders = contexts.length - index;- const content = context.slice(0, Math.floor(remainingContent / remainingProviders));- remainingContent -= content.length;- return `${delimiters[index].open}${content}${delimiters[index].close}`;- });- return `${baselineSection}${providerSections.join('\n\n')}`;-};--const storedProposal = (metadata: unknown) => {- if (!isPlainRecord(metadata)) return;- const parsed = OnboardingUnderstandingMessageMetadataSchema.safeParse(- metadata.onboardingUnderstanding,- );- return parsed.success ? parsed.data : undefined;-};--/**- * Normalizes a thrown provider value into the persisted diagnostic shape without replacing its- * original message.- *- * Before:- * - `Error("GraphQL FORBIDDEN at viewer.repository")`- *- * After:- * - `{ provider: "github", operation: "collection", message: "GraphQL FORBIDDEN at viewer.repository" }`- */-const createProviderCollectionError = (providerId: string, error: unknown) => {- const connectorError = error instanceof ConnectorDataError ? error : undefined;- return createCollectionError(- providerId,- connectorError?.operation ?? 'collection',- connectorError?.code ?? 'UNDERSTANDING_PROVIDER_COLLECTION_FAILED',- isConnectorErrorRetryable(error),- getConnectorErrorMessage(error) ?? String(error),- );-};--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[],- ): Promise<OnboardingUnderstandingSession> =>- observeOnboardingUnderstandingOperation({ operation: 'initialize', topicId }, async () => {- await observeOnboardingUnderstandingOperation(- { operation: 'topic.assert-active', topicId },- () => this.dependencies.topic.assertActiveOnboardingTopic(topicId),- );-- const current = await observeOnboardingUnderstandingOperation(- { operation: 'session.read', topicId },- () => this.dependencies.repository.get(topicId),- );- if (current) return current;-- const requestedProviderIds = selectedProviderIds- ? [...new Set(selectedProviderIds)].sort()- : [...this.dependencies.providers.keys()].sort();- if (requestedProviderIds.some((providerId) => !this.dependencies.providers.has(providerId))) {- throw new UnderstandingResourceNotFoundError('session');- }- const availableProviderIds = new Set(- await observeOnboardingUnderstandingOperation(- { operation: 'provider.resolve-available', topicId },- () => this.listSourceProviderIds(),- ),- );- const providerIds = requestedProviderIds.filter((providerId) =>- availableProviderIds.has(providerId),- );- const sessionId = this.dependencies.ids();- return observeOnboardingUnderstandingOperation(- { operation: 'session.persist', sessionId, topicId },- () => this.dependencies.repository.initialize(topicId, sessionId, providerIds),- );- });-- start = async (- topicId: string,- responseLanguage: string,- selectedProviderIds?: string[],- options: UnderstandingStartOptions = {},- ): Promise<OnboardingUnderstandingPollingResult> => {- const startedAt = Date.now();- return observeOnboardingUnderstandingOperation(- { operation: 'session.start', topicId },- async () => {- const { OnboardingUnderstandingWorkflow } =- await import('@/server/workflows/onboardingUnderstanding');- OnboardingUnderstandingWorkflow.assertAvailable();-- const session = await this.initialize(topicId, selectedProviderIds);- const providers = Object.entries(session.sources)- .filter(([, state]) => state.status === 'pending')- .toSorted(([left], [right]) => left.localeCompare(right))- .map(([id, state]) => ({ id, revision: state.revision + 1 }));- if (providers.length > 0) {- await observeOnboardingUnderstandingOperation(- { operation: 'workflow.trigger', sessionId: session.id, topicId },- () =>- OnboardingUnderstandingWorkflow.triggerProviders(- {- providers,- responseLanguage,- sessionId: session.id,- startedAt,- triggerTaskRecommendations: options.triggerTaskRecommendations,- topicId,- userId: this.dependencies.userId,- },- { workflowRunId: `onboarding-understanding-initial-${session.id}` },- ),- );- }- return this.get(topicId);- },- );- };-- revise = async (- input: ReviseOnboardingUnderstandingInput,- ): Promise<OnboardingUnderstandingPollingResult> => {- const { OnboardingUnderstandingWorkflow } =- await import('@/server/workflows/onboardingUnderstanding');- OnboardingUnderstandingWorkflow.assertAvailable();- 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) =>- availableProviderIds.has(providerId),- );-- 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',- );- const sourceStore = completedProviders.length > 0 ? this.dependencies.sourceStore() : undefined;- const storedContexts = sourceStore- ? await Promise.all(- completedProviders.map(([providerId, state]) =>- sourceStore.get({- providerId,- revision: state.revision,- sessionId: input.sessionId,- userId: this.dependencies.userId,- }),- ),- )- : [];- const expiredProviders = completedProviders.flatMap(([providerId, state], index) =>- storedContexts[index] ? [] : [{ providerId, revision: state.revision }],- );- const currentSourceFingerprint = getUnderstandingSourceFingerprint(next);- const availableSession =- expiredProviders.length > 0 && currentSourceFingerprint- ? await this.dependencies.repository.expireProviderContexts({- providers: expiredProviders,- sessionId: input.sessionId,- sourceFingerprint: currentSourceFingerprint,- topicId: input.topicId,- })- : next;- const recollectedProviders = await Promise.all(- expiredProviders.map(async ({ providerId }) => ({- id: providerId,- ...(await this.dependencies.repository.markProviderRunning(- input.topicId,- input.sessionId,- providerId,- )),- })),- );- const attempts = [...providerAttempts, ...recollectedProviders].sort((left, right) =>- left.id.localeCompare(right.id),- );- 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);- if (input.feedback?.trim() && sourceFingerprint) {- await OnboardingUnderstandingWorkflow.triggerWriting(- {- sessionId: input.sessionId,- responseLanguage: input.responseLanguage,- sourceFingerprint,- startedAt: Date.now(),- topicId: input.topicId,- userId: this.dependencies.userId,- },- {- workflowRunId: `onboarding-understanding-feedback-${createHash('sha256')- .update(input.sessionId)- .update('\0')- .update(sourceFingerprint)- .update('\0')- .update(String(next.feedback?.revision ?? 0))- .digest('hex')- .slice(0, 32)}`,- },- );- }-- return this.get(input.topicId);- };-- get = async (topicId: string): Promise<OnboardingUnderstandingPollingResult> => {- await this.dependencies.topic.assertActiveOnboardingTopic(topicId);- const session = await this.dependencies.repository.get(topicId);- if (!session) throw new UnderstandingSessionNotFoundError(topicId);- let proposal: OnboardingUnderstandingMessageMetadata | undefined;- if (session.writing?.resultMessageId) {- const message = await this.dependencies.messages.findById(session.writing.resultMessageId);- proposal = storedProposal(message?.metadata);- }- return {- confirmed: Boolean(session.confirmedAt),- feedback: session.feedback,- generationRevision: session.generationRevision,- id: session.id,- ...(proposal ? { proposal } : {}),- sources: session.sources,- status: projectOnboardingUnderstandingSessionStatus(session),- ...(session.writing ? { writing: session.writing } : {}),- };- };-- retry = async (- input: RetryOnboardingUnderstandingProviderInput,- ): Promise<OnboardingUnderstandingPollingResult> => {- const { OnboardingUnderstandingWorkflow } =- await import('@/server/workflows/onboardingUnderstanding');- OnboardingUnderstandingWorkflow.assertAvailable();- const session = await this.activeSession(input.topicId, input.sessionId);- const state = session.sources[input.providerId];- if (!this.dependencies.providers.has(input.providerId) || !state) {- throw new UnderstandingResourceNotFoundError('session');- }- 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,- ]);- if (!availableProviderIds.includes(input.providerId)) return this.get(input.topicId);- const { revision } = await this.dependencies.repository.markProviderRunning(- input.topicId,- input.sessionId,- input.providerId,- );- try {- await OnboardingUnderstandingWorkflow.triggerProviders(- {- providers: [{ id: input.providerId, revision }],- responseLanguage: input.responseLanguage,- sessionId: input.sessionId,- startedAt: Date.now(),- topicId: input.topicId,- userId: this.dependencies.userId,- },- {- workflowRunId: `onboarding-understanding-retry-${input.sessionId}-${input.providerId}-${revision}`,- },- );- } catch (triggerError) {- try {- await this.failProvider({ ...input, revision });- } catch (compensationError) {- console.error('[understanding:retryCompensation]', {- errorName: compensationError instanceof Error ? compensationError.name : 'UnknownError',- });- }- throw triggerError;- }- return this.get(input.topicId);- };-- processProvider = async (input: ProviderOperationInput) =>- observeOnboardingUnderstandingOperation(- {- operation: 'provider.process',- providerId: input.providerId,- sessionId: input.sessionId,- topicId: input.topicId,- },- async () => {- const operationAttributes = {- providerId: input.providerId,- sessionId: input.sessionId,- topicId: input.topicId,- };- const session = await observeOnboardingUnderstandingOperation(- { ...operationAttributes, operation: 'session.read' },- () => this.activeSession(input.topicId, input.sessionId),- );- const provider = this.dependencies.providers.get(input.providerId);- const state = session.sources[input.providerId];- if (!provider || !state) throw new UnderstandingResourceNotFoundError('session');- const stale = () => ({- failedCount: 0,- providerId: input.providerId,- revision: input.revision,- sourceCount: 0,- status: 'stale' as const,- succeededCount: 0,- });-- if (state.status === 'completed') {- if (state.revision !== input.revision) return stale();- const sourceFingerprint = getUnderstandingSourceFingerprint(session);- if (!sourceFingerprint) throw new UnderstandingProviderContextUnavailableError();- const stored = await this.dependencies.sourceStore().get({- providerId: input.providerId,- revision: input.revision,- sessionId: input.sessionId,- userId: this.dependencies.userId,- });- if (stored) {- return {- failedCount: stored.diagnostics.failedCount,- providerId: input.providerId,- revision: input.revision,- sourceCount: stored.sourceCount,- sourceFingerprint,- status: 'completed' as const,- succeededCount: stored.diagnostics.succeededCount,- };- }- const expired = await this.dependencies.repository.expireProviderContexts({- providers: [{ providerId: input.providerId, revision: input.revision }],- sessionId: input.sessionId,- sourceFingerprint,- topicId: input.topicId,- });- const expiredState = expired.sources[input.providerId];- return expiredState?.revision === input.revision && expiredState.status === 'failed'- ? {- failedCount: expiredState.failedCount,- providerId: input.providerId,- revision: input.revision,- sourceCount: 0,- status: 'failed' as const,- succeededCount: expiredState.succeededCount,- }- : stale();- }-- if (state.status === 'pending') {- if (state.revision + 1 !== input.revision) return stale();- const running = await observeOnboardingUnderstandingOperation(- { ...operationAttributes, operation: 'provider.mark-running' },- () =>- this.dependencies.repository.markProviderRunning(- input.topicId,- input.sessionId,- input.providerId,- ),- );- if (running.revision !== input.revision) return stale();- } else if (state.status !== 'running' || state.revision !== input.revision) {- return stale();- }-- let collection;- try {- collection = await observeOnboardingUnderstandingProviderCollection(- operationAttributes,- async () => {- const collected = await provider.collect({- connectorData: this.dependencies.connectorData,- userId: this.dependencies.userId,- });- const context = collected.context.trim().slice(0, MAX_SOURCE_BRIEF_LENGTH);- const diagnostics = boundProviderDiagnostics(collected.diagnostics);- const usable =- Boolean(context) &&- collected.sourceCount > 0 &&- diagnostics.evidenceCount > 0 &&- diagnostics.succeededCount > 0;- const outcome = !usable- ? ('failed' as const)- : diagnostics.failedCount > 0 || diagnostics.errors.length > 0- ? ('partial' as const)- : ('completed' as const);-- return {- diagnostics: diagnostics.errors,- evidenceCount: diagnostics.evidenceCount,- failedCount: diagnostics.failedCount,- outcome,- result: { context, diagnostics, sourceCount: collected.sourceCount, usable },- sourceCount: collected.sourceCount,- succeededCount: diagnostics.succeededCount,- };- },- (error) => createProviderCollectionError(input.providerId, error),- );- } catch (error) {- const diagnostic = createProviderCollectionError(input.providerId, error);- if (diagnostic.retryable) throw error;- return this.recordProviderFailure(input, 0, {- errors: [diagnostic],- evidenceCount: 0,- failedCount: 1,- succeededCount: 0,- });- }-- const { context, diagnostics, sourceCount, usable } = collection;- if (!usable)- return this.recordProviderFailure(input, diagnostics.succeededCount, diagnostics);-- const stored = {- context,- diagnostics,- providerId: input.providerId,- revision: input.revision,- sessionId: input.sessionId,- sourceCount,- userId: this.dependencies.userId,- };- await observeOnboardingUnderstandingOperation(- { ...operationAttributes, operation: 'provider.persist-context' },- () => this.dependencies.sourceStore().put(stored),- );- const transition = await observeOnboardingUnderstandingOperation(- { ...operationAttributes, operation: 'provider.complete' },- () =>- this.dependencies.repository.completeProvider({- errors: diagnostics.errors,- failedCount: diagnostics.failedCount,- providerId: input.providerId,- revision: input.revision,- sessionId: input.sessionId,- succeededCount: diagnostics.succeededCount,- topicId: input.topicId,- }),- );- const sourceFingerprint = getUnderstandingSourceFingerprint(transition);- if (!sourceFingerprint) throw new UnderstandingProviderContextUnavailableError();- return {- failedCount: diagnostics.failedCount,- providerId: input.providerId,- revision: input.revision,- sourceCount,- sourceFingerprint,- status: 'completed' as const,- succeededCount: diagnostics.succeededCount,- };- },- );-- failProvider = async (input: ProviderOperationInput) => {- try {- return await this.dependencies.repository.failProvider({- errors: [- createCollectionError(- input.providerId,- 'collection',- 'UNDERSTANDING_PROVIDER_COLLECTION_FAILED',- true,- ),- ],- failedCount: 1,- providerId: input.providerId,- revision: input.revision,- sessionId: input.sessionId,- succeededCount: 0,- topicId: input.topicId,- });- } catch (error) {- if (- error instanceof StaleUnderstandingRevisionError ||- error instanceof StaleUnderstandingSessionError- ) {- return;- }- throw error;- }- };-- processCollected = async ({- expectedSourceFingerprint,- responseLanguage,- sessionId,- topicId,- }: ProcessCollectedInput) =>- observeOnboardingUnderstandingOperation(- { operation: 'writer.process', sessionId, topicId },- async () => {- const operationAttributes = { sessionId, topicId };- const session = await observeOnboardingUnderstandingOperation(- { ...operationAttributes, operation: 'session.read' },- () => this.activeSession(topicId, sessionId),- );- const feedback = session.feedback ?? { revision: 0, turns: [] };- if (getUnderstandingSourceFingerprint(session) !== expectedSourceFingerprint) {- return { published: false as const, sourceFingerprint: expectedSourceFingerprint };- }- if (- session.writing?.sourceFingerprint === expectedSourceFingerprint &&- (session.writing.feedbackRevision ?? 0) === feedback.revision &&- session.writing.status === 'completed'- ) {- return {- feedbackRevision: session.writing.feedbackRevision ?? 0,- generationRevision: session.writing.generationRevision ?? 0,- published: true as const,- resultId: session.writing.resultMessageId,- sourceFingerprint: expectedSourceFingerprint,- };- }-- const completed = Object.entries(session.sources)- .filter(([, state]) => state.status === 'completed')- .sort(([left], [right]) => left.localeCompare(right));- const sourceStore = this.dependencies.sourceStore();- const contexts = await observeOnboardingUnderstandingOperation(- { ...operationAttributes, operation: 'writer.read-contexts' },- () =>- Promise.all(- completed.map(([providerId, state]) =>- sourceStore.get({- providerId,- revision: state.revision,- sessionId,- userId: this.dependencies.userId,- }),- ),- ),- );- const missing = completed.flatMap(([providerId, state], index) =>- contexts[index] ? [] : [{ providerId, revision: state.revision }],- );- if (missing.length > 0) {- await this.dependencies.repository.expireProviderContexts({- providers: missing,- sessionId,- sourceFingerprint: expectedSourceFingerprint,- topicId,- });- return { published: false as const, sourceFingerprint: expectedSourceFingerprint };- }-- const sourceContexts = contexts as StoredUnderstandingProviderContext[];- const threadId = writingThreadId(sessionId, expectedSourceFingerprint, feedback.revision);- const writerAgent = await observeOnboardingUnderstandingOperation(- { ...operationAttributes, operation: 'writer.resolve-agent' },- () => this.dependencies.writerAgent(),- );- const prepared = await observeOnboardingUnderstandingOperation(- { ...operationAttributes, operation: 'writer.prepare' },- () =>- this.dependencies.repository.prepareWriting({- agentId: writerAgent.id,- expectedFeedbackRevision: feedback.revision,- sessionId,- sourceFingerprint: expectedSourceFingerprint,- threadId,- topicId,- }),- );- if (!prepared.ready) {- return { published: false as const, sourceFingerprint: expectedSourceFingerprint };- }-- const providers = sourceContexts.map(({ providerId }) => providerId);- const diagnostics = sumDiagnostics(session, sourceContexts);- const writerResult = await this.runWriter({- contexts: sourceContexts,- diagnostics,- feedback: feedback.turns,- providers,- responseLanguage,- sessionId,- threadId,- topicId,- writerAgent,- });- const metadata = OnboardingUnderstandingMessageMetadataSchema.parse({- analysis: writerResult.analysis,- diagnostics,- feedbackRevision: prepared.feedbackRevision,- generationRevision: prepared.generationRevision,- kind: 'proposal',- providers,- resultId: writerResult.assistantMessageId,- sourceFingerprint: expectedSourceFingerprint,- });- const committed = await observeOnboardingUnderstandingOperation(- { ...operationAttributes, operation: 'writer.commit' },- () =>- this.dependencies.repository.commitWriting({- assistantMessageId: writerResult.assistantMessageId,- feedbackRevision: prepared.feedbackRevision,- generationRevision: prepared.generationRevision,- metadata,- sessionId,- sourceFingerprint: expectedSourceFingerprint,- threadId,- topicId,- }),- );- if (!committed.published) {- return { published: false as const, sourceFingerprint: expectedSourceFingerprint };- }- return {- feedbackRevision: prepared.feedbackRevision,- generationRevision: prepared.generationRevision,- ...(committed.personaVersion === undefined- ? {}- : { personaVersion: committed.personaVersion }),- published: true as const,- resultId: writerResult.assistantMessageId,- sourceFingerprint: expectedSourceFingerprint,- };- },- );-- failWriting = async ({- sessionId,- sourceFingerprint,- topicId,- }: {- sessionId: string;- sourceFingerprint: string;- topicId: string;- }) => {- try {- const current = await this.activeSession(topicId, sessionId);- if (current.writing && current.writing.sourceFingerprint !== sourceFingerprint) return;- const session = await this.dependencies.repository.failWriting({- error: createCollectionError(- 'understanding',- 'writing',- 'UNDERSTANDING_WRITING_FAILED',- true,- ),- feedbackRevision: current.writing?.feedbackRevision ?? current.feedback?.revision ?? 0,- generationRevision: current.writing?.generationRevision ?? current.generationRevision ?? 0,- sessionId,- sourceFingerprint,- topicId,- });- return session.writing?.sourceFingerprint === sourceFingerprint &&- session.writing.status === 'failed'- ? session- : undefined;- } catch (error) {- if (- error instanceof StaleUnderstandingRevisionError ||- error instanceof StaleUnderstandingSessionError- ) {- return;- }- throw error;- }- };-- processDetailedPersona = async ({- expectedSourceFingerprint,- responseLanguage,- sessionId,- topicId,- }: ProcessCollectedInput) =>- observeOnboardingUnderstandingOperation(- { operation: 'detailed.process', sessionId, topicId },- async () => {- const operationAttributes = { sessionId, topicId };- const session = await observeOnboardingUnderstandingOperation(- { ...operationAttributes, operation: 'session.read' },- () => this.activeSession(topicId, sessionId),- );- const writing = session.writing;- if (- getUnderstandingSourceFingerprint(session) !== expectedSourceFingerprint ||- writing?.status !== 'completed' ||- writing.sourceFingerprint !== expectedSourceFingerprint- ) {- return { published: false as const, sourceFingerprint: expectedSourceFingerprint };- }- if (writing.detailed?.status === 'completed') {- return { published: true as const, sourceFingerprint: expectedSourceFingerprint };- }- if (writing.detailed?.status !== 'running') {- return { published: false as const, sourceFingerprint: expectedSourceFingerprint };- }-- const resultMessage = await observeOnboardingUnderstandingOperation(- { ...operationAttributes, operation: 'detailed.read-result' },- () => this.dependencies.messages.findById(writing.resultMessageId),- );- const proposal = storedProposal(resultMessage?.metadata);- if (!proposal) throw new UnderstandingProviderContextUnavailableError();- if (- proposal.sourceFingerprint !== expectedSourceFingerprint ||- proposal.feedbackRevision !== writing.feedbackRevision ||- proposal.generationRevision !== writing.generationRevision- ) {- return { published: false as const, sourceFingerprint: expectedSourceFingerprint };- }-- const completed = Object.entries(session.sources)- .filter(([, state]) => state.status === 'completed')- .sort(([left], [right]) => left.localeCompare(right));- const sourceStore = this.dependencies.sourceStore();- const contexts = await observeOnboardingUnderstandingOperation(- { ...operationAttributes, operation: 'writer.read-contexts' },- () =>- Promise.all(- completed.map(([providerId, state]) =>- sourceStore.get({- providerId,- revision: state.revision,- sessionId,- userId: this.dependencies.userId,- }),- ),- ),- );- if (contexts.some((context) => !context)) {- throw new UnderstandingProviderContextUnavailableError();- }-- const baseline = await observeOnboardingUnderstandingOperation(- { ...operationAttributes, operation: 'detailed.read-baseline' },- () => this.dependencies.persona.getLatestPersonaDocument(),- );- const writerAgent = await observeOnboardingUnderstandingOperation(- { ...operationAttributes, operation: 'writer.resolve-agent' },- () => this.dependencies.writerAgent(),- );- const detailedPersona: UnderstandingPersonaProposal =- UnderstandingPersonaProposalSchema.parse(- await observeOnboardingUnderstandingOperation(- { ...operationAttributes, operation: 'detailed.generate' },- () =>- this.dependencies.generator.generateObject(- {- ...chainUnderstandingDetailedPersona({- analysis: proposal.analysis,- context: buildEphemeralDocument(- contexts as StoredUnderstandingProviderContext[],- baseline,- ),- responseLanguage,- }),- model: writerAgent.model,- provider: writerAgent.provider,- schema: UNDERSTANDING_DETAILED_PERSONA_JSON_SCHEMA,- thinking: { type: 'disabled' },- },- {- metadata: { trigger: RequestTrigger.Onboarding },- tracing: {- promptVersion: UNDERSTANDING_DETAILED_PERSONA_PROMPT_VERSION,- scenario: TRACING_SCENARIOS.UnderstandingDetailedPersona,- schemaName: UNDERSTANDING_DETAILED_PERSONA_JSON_SCHEMA.name,- },- },- ),- ),- );- const committed = await observeOnboardingUnderstandingOperation(- { ...operationAttributes, operation: 'detailed.commit' },- () =>- this.dependencies.repository.commitDetailedWriting({- detailedPersona,- feedbackRevision: writing.feedbackRevision ?? 0,- generationRevision: writing.generationRevision ?? 0,- sessionId,- sourceFingerprint: expectedSourceFingerprint,- topicId,- }),- );- return { ...committed, sourceFingerprint: expectedSourceFingerprint };- },- );-- failDetailedPersona = async ({- sessionId,- sourceFingerprint,- topicId,- }: {- sessionId: string;- sourceFingerprint: string;- topicId: string;- }) => {- try {- const current = await this.activeSession(topicId, sessionId);- const writing = current.writing;- if (- writing?.status !== 'completed' ||- writing.sourceFingerprint !== sourceFingerprint ||- writing.detailed?.status !== 'running'- ) {- return;- }- return this.dependencies.repository.failDetailedWriting({- error: createCollectionError(- 'understanding',- 'detailed-writing',- 'UNDERSTANDING_DETAILED_WRITING_FAILED',- true,- ),- feedbackRevision: writing.feedbackRevision ?? 0,- generationRevision: writing.generationRevision ?? 0,- sessionId,- sourceFingerprint,- topicId,- });- } catch (error) {- if (- error instanceof StaleUnderstandingRevisionError ||- error instanceof StaleUnderstandingSessionError- ) {- return;- }- throw error;- }- };-- confirm = (input: ConfirmOnboardingUnderstandingInput) =>- this.dependencies.repository.confirm(input);-- private activeSession = async (topicId: string, sessionId: string) => {- await this.dependencies.topic.assertActiveOnboardingTopic(topicId);- const session = await this.dependencies.repository.get(topicId);- if (!session) throw new UnderstandingSessionNotFoundError(topicId);- if (session.id !== sessionId) throw new StaleUnderstandingSessionError(sessionId);- return session;- };-- private recordProviderFailure = async (- input: ProviderOperationInput,- succeededCount: number,- diagnostics?: CollectionDiagnostics,- ) => {- const errors = diagnostics?.errors.length- ? diagnostics.errors- : [- createCollectionError(- input.providerId,- 'collection',- 'UNDERSTANDING_PROVIDER_COLLECTION_FAILED',- false,- ),- ];- await this.dependencies.repository.failProvider({- errors,- failedCount: Math.max(1, diagnostics?.failedCount ?? 1),- providerId: input.providerId,- revision: input.revision,- sessionId: input.sessionId,- succeededCount,- topicId: input.topicId,- });- return {- failedCount: Math.max(1, diagnostics?.failedCount ?? 1),- providerId: input.providerId,- revision: input.revision,- sourceCount: 0,- status: 'failed' as const,- succeededCount,- };- };-- private runWriter = async ({- contexts,- diagnostics,- feedback,- providers,- responseLanguage,- sessionId,- threadId,- topicId,- writerAgent,- }: {- contexts: StoredUnderstandingProviderContext[];- diagnostics: CollectionDiagnostics;- feedback: UnderstandingFeedbackTurn[];- providers: string[];- responseLanguage: string;- sessionId: string;- threadId: string;- topicId: string;- writerAgent: { id: string; model: string; provider: string };- }) =>- observeOnboardingUnderstandingOperation(- { operation: 'writer.generate', sessionId, topicId },- async () => {- const operationAttributes = { sessionId, topicId };- const existing = await observeOnboardingUnderstandingOperation(- { ...operationAttributes, operation: 'writer.read-existing' },- () =>- this.dependencies.messages.findLatestAssistantMessageByThread({- agentId: writerAgent.id,- threadId,- topicId,- }),- );- if (existing && !existing.error) {- const analysis = parseStoredAnalysis(existing.content);- if (analysis) return { analysis, assistantMessageId: existing.id };- }-- const baseline = await observeOnboardingUnderstandingOperation(- { ...operationAttributes, operation: 'writer.read-baseline' },- () => this.dependencies.persona.getLatestPersonaDocument(),- );- const analysis = UnderstandingAnalysisSchema.parse(- await observeOnboardingUnderstandingOperation(- { ...operationAttributes, operation: 'generation.runtime-call' },- () =>- this.dependencies.generator.generateObject(- {- ...chainUnderstandingPersona({- context: buildEphemeralDocument(contexts, baseline),- diagnostics,- feedback,- providers,- responseLanguage,- }),- model: writerAgent.model,- provider: writerAgent.provider,- schema: UNDERSTANDING_ANALYSIS_JSON_SCHEMA,- thinking: { type: 'disabled' },- },- {- metadata: { trigger: RequestTrigger.Onboarding },- tracing: {- promptVersion: UNDERSTANDING_ANALYSIS_PROMPT_VERSION,- scenario: TRACING_SCENARIOS.UnderstandingAnalysis,- schemaName: UNDERSTANDING_ANALYSIS_JSON_SCHEMA.name,- },- },- ),- ),- );- const message = await observeOnboardingUnderstandingOperation(- { ...operationAttributes, operation: 'writer.create-message' },- () =>- this.dependencies.messages.create({- agentId: writerAgent.id,- content: JSON.stringify(analysis),- model: writerAgent.model,- provider: writerAgent.provider,- role: 'assistant',- threadId,- topicId,- }),- );- return {- analysis,- assistantMessageId: message.id,- };- },- );-}--interface CreateUnderstandingServiceOptions {- db: LobeChatDatabase;- providers?: readonly UnderstandingProvider[];- userId: string;- workspaceId?: string;-}--export const createUnderstandingService = async ({- db,- providers,- userId,- workspaceId,-}: CreateUnderstandingServiceOptions): Promise<UnderstandingService> => {- if (workspaceId) throw new Error('Onboarding Understanding is available only in personal scope');-- const messageModel = new MessageModel(db, userId);- const topicModel = new TopicModel(db, userId);- const aiGenerationService = new AiGenerationService(db, userId);-- return new UnderstandingService({- connectorData: new ConnectorDataService(db, userId),- generator: aiGenerationService,- ids: randomUUID,- messages: {- create: (params) => messageModel.create(params),- findById: (id) => messageModel.findById(id),- findLatestAssistantMessageByThread: async (input) => {- const message = await messageModel.findLatestAssistantMessageByThread(input);- return message- ? {- content: message.content,- error: message.error,- id: message.id,- role: message.role,- threadId: message.threadId,- }- : message;- },- },- persona: new UserPersonaModel(db, userId),- providers: providers- ? new Map(providers.map((provider) => [provider.id, provider]))- : understandingProviderMap,- repository: new OnboardingUnderstandingRepository(db, userId),- sourceStore: () => new UnderstandingSourceStore(),- topic: {- assertActiveOnboardingTopic: async (topicId) => {- const topic = await topicModel.findById(topicId);- const onboarding = topic?.metadata?.onboardingSession;- if (!topic || !onboarding || onboarding.finishedAt) {- throw new UnderstandingResourceNotFoundError('topic');- }- },- },- userId,- writerAgent: async () => {- const agentModel = new AgentModel(db, userId);- const writerAgent = await agentModel.getBuiltinAgent(- BUILTIN_AGENT_SLUGS.onboardingUnderstanding,- );- if (!writerAgent) throw new Error('Onboarding Understanding agent is unavailable');- const modelConfig = await agentModel.getAgentModelConfig(writerAgent.id);- if (!modelConfig) throw new Error('Onboarding Understanding agent is unavailable');- return { ...modelConfig, id: writerAgent.id };- },- });-};diff --git a/apps/server/src/services/understanding/service/detailedPersona.ts b/apps/server/src/services/understanding/service/detailedPersona.tsnew file mode 100644index 00000000000..d4bf0053988--- /dev/null+++ b/apps/server/src/services/understanding/service/detailedPersona.ts@@ -0,0 +1,191 @@+import { TRACING_SCENARIOS } from '@lobechat/const';+import {+ getUnderstandingSourceFingerprint,+ StaleUnderstandingRevisionError,+ StaleUnderstandingSessionError,+} from '@lobechat/database';+import { observeOnboardingUnderstandingOperation } from '@lobechat/observability-otel/modules/onboarding-understanding';+import {+ chainUnderstandingDetailedPersona,+ UNDERSTANDING_DETAILED_PERSONA_JSON_SCHEMA,+ UNDERSTANDING_DETAILED_PERSONA_PROMPT_VERSION,+} from '@lobechat/prompts';+import type { UnderstandingPersonaProposal } from '@lobechat/types';+import { RequestTrigger, UnderstandingPersonaProposalSchema } from '@lobechat/types';+import pMap from 'p-map';++import type { StoredUnderstandingProviderContext } from '../sourceStore';+import { UnderstandingProviderContextUnavailableError } from './errors';+import { readActiveSession } from './session';+import type { ProcessCollectedInput, UnderstandingServiceDependencies } from './types';+import {+ buildEphemeralDocument,+ createCollectionError,+ PROVIDER_IO_CONCURRENCY,+ storedProposal,+} from './utils';++export const processDetailedPersona = async (+ dependencies: UnderstandingServiceDependencies,+ { expectedSourceFingerprint, responseLanguage, sessionId, topicId }: ProcessCollectedInput,+) =>+ observeOnboardingUnderstandingOperation(+ { operation: 'detailed.process', sessionId, topicId },+ async () => {+ const operationAttributes = { sessionId, topicId };+ const session = await observeOnboardingUnderstandingOperation(+ { ...operationAttributes, operation: 'session.read' },+ () => readActiveSession(dependencies, topicId, sessionId),+ );+ const writing = session.writing;+ if (+ getUnderstandingSourceFingerprint(session) !== expectedSourceFingerprint ||+ writing?.status !== 'completed' ||+ writing.sourceFingerprint !== expectedSourceFingerprint+ ) {+ return { published: false as const, sourceFingerprint: expectedSourceFingerprint };+ }+ if (writing.detailed?.status === 'completed') {+ return { published: true as const, sourceFingerprint: expectedSourceFingerprint };+ }+ if (writing.detailed?.status !== 'running') {+ return { published: false as const, sourceFingerprint: expectedSourceFingerprint };+ }++ const resultMessage = await observeOnboardingUnderstandingOperation(+ { ...operationAttributes, operation: 'detailed.read-result' },+ () => dependencies.messages.findById(writing.resultMessageId),+ );+ const proposal = storedProposal(resultMessage?.metadata);+ if (!proposal) throw new UnderstandingProviderContextUnavailableError();+ if (+ proposal.sourceFingerprint !== expectedSourceFingerprint ||+ proposal.feedbackRevision !== writing.feedbackRevision ||+ proposal.generationRevision !== writing.generationRevision+ ) {+ return { published: false as const, sourceFingerprint: expectedSourceFingerprint };+ }++ const completed = Object.entries(session.sources)+ .filter(([, state]) => state.status === 'completed')+ .sort(([left], [right]) => left.localeCompare(right));+ const sourceStore = dependencies.sourceStore();+ const contexts = await observeOnboardingUnderstandingOperation(+ { ...operationAttributes, operation: 'writer.read-contexts' },+ () =>+ pMap(+ completed,+ ([providerId, state]) =>+ sourceStore.get({+ providerId,+ revision: state.revision,+ sessionId,+ userId: dependencies.userId,+ }),+ { concurrency: PROVIDER_IO_CONCURRENCY },+ ),+ );+ if (contexts.some((context) => !context)) {+ throw new UnderstandingProviderContextUnavailableError();+ }++ const baseline = await observeOnboardingUnderstandingOperation(+ { ...operationAttributes, operation: 'detailed.read-baseline' },+ () => dependencies.persona.getLatestPersonaDocument(),+ );+ const writerAgent = await observeOnboardingUnderstandingOperation(+ { ...operationAttributes, operation: 'writer.resolve-agent' },+ () => dependencies.writerAgent(),+ );+ const detailedPersona: UnderstandingPersonaProposal =+ UnderstandingPersonaProposalSchema.parse(+ await observeOnboardingUnderstandingOperation(+ { ...operationAttributes, operation: 'detailed.generate' },+ () =>+ dependencies.generator.generateObject(+ {+ ...chainUnderstandingDetailedPersona({+ analysis: proposal.analysis,+ context: buildEphemeralDocument(+ contexts as StoredUnderstandingProviderContext[],+ baseline,+ ),+ responseLanguage,+ }),+ model: writerAgent.model,+ provider: writerAgent.provider,+ schema: UNDERSTANDING_DETAILED_PERSONA_JSON_SCHEMA,+ thinking: { type: 'disabled' },+ },+ {+ metadata: { trigger: RequestTrigger.Onboarding },+ tracing: {+ promptVersion: UNDERSTANDING_DETAILED_PERSONA_PROMPT_VERSION,+ scenario: TRACING_SCENARIOS.UnderstandingDetailedPersona,+ schemaName: UNDERSTANDING_DETAILED_PERSONA_JSON_SCHEMA.name,+ },+ },+ ),+ ),+ );+ const committed = await observeOnboardingUnderstandingOperation(+ { ...operationAttributes, operation: 'detailed.commit' },+ () =>+ dependencies.repository.commitDetailedWriting({+ detailedPersona,+ feedbackRevision: writing.feedbackRevision ?? 0,+ generationRevision: writing.generationRevision ?? 0,+ sessionId,+ sourceFingerprint: expectedSourceFingerprint,+ topicId,+ }),+ );+ return { ...committed, sourceFingerprint: expectedSourceFingerprint };+ },+ );++export const failDetailedPersona = async (+ dependencies: UnderstandingServiceDependencies,+ {+ sessionId,+ sourceFingerprint,+ topicId,+ }: {+ sessionId: string;+ sourceFingerprint: string;+ topicId: string;+ },+) => {+ try {+ const current = await readActiveSession(dependencies, topicId, sessionId);+ const writing = current.writing;+ if (+ writing?.status !== 'completed' ||+ writing.sourceFingerprint !== sourceFingerprint ||+ writing.detailed?.status !== 'running'+ ) {+ return;+ }+ return dependencies.repository.failDetailedWriting({+ error: createCollectionError(+ 'understanding',+ 'detailed-writing',+ 'UNDERSTANDING_DETAILED_WRITING_FAILED',+ true,+ ),+ feedbackRevision: writing.feedbackRevision ?? 0,+ generationRevision: writing.generationRevision ?? 0,+ sessionId,+ sourceFingerprint,+ topicId,+ });+ } catch (error) {+ if (+ error instanceof StaleUnderstandingRevisionError ||+ error instanceof StaleUnderstandingSessionError+ ) {+ return;+ }+ throw error;+ }+};diff --git a/apps/server/src/services/understanding/service/errors.ts b/apps/server/src/services/understanding/service/errors.tsnew file mode 100644index 00000000000..5620237b9c9--- /dev/null+++ b/apps/server/src/services/understanding/service/errors.ts@@ -0,0 +1,6 @@+export class UnderstandingProviderContextUnavailableError extends Error {+ constructor() {+ super('Current onboarding Understanding provider context is unavailable');+ this.name = 'UnderstandingProviderContextUnavailableError';+ }+}diff --git a/apps/server/src/services/understanding/service/index.guards.test.ts b/apps/server/src/services/understanding/service/index.guards.test.tsnew file mode 100644index 00000000000..5310d2980a3--- /dev/null+++ b/apps/server/src/services/understanding/service/index.guards.test.ts@@ -0,0 +1,275 @@+import {+ StaleUnderstandingRevisionError,+ StaleUnderstandingSessionError,+} from '@lobechat/database';+import type { OnboardingUnderstandingSession } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { createHarness, createSession, providerState } from './testUtils';++const { mockAssertWorkflowAvailable, mockTriggerProviders, mockTriggerWriting } = vi.hoisted(+ () => ({+ mockAssertWorkflowAvailable: vi.fn(),+ mockTriggerProviders: vi.fn(),+ mockTriggerWriting: vi.fn(),+ }),+);++vi.mock('@/server/workflows/onboardingUnderstanding', () => ({+ OnboardingUnderstandingWorkflow: {+ assertAvailable: mockAssertWorkflowAvailable,+ triggerProviders: mockTriggerProviders,+ triggerWriting: mockTriggerWriting,+ },+}));++const fingerprint = 'github@1';+const sessionRef = { sessionId: 'session-1', topicId: 'topic-1' };++const completedWriting = (+ detailed?: NonNullable<OnboardingUnderstandingSession['writing']>['detailed'],+ sourceFingerprint = fingerprint,+): OnboardingUnderstandingSession =>+ ({+ ...createSession({ github: providerState('completed', 1) }),+ feedback: { revision: 2, turns: [] },+ writing: {+ detailed,+ feedbackRevision: 2,+ generationRevision: 3,+ resultMessageId: 'assistant-1',+ sourceFingerprint,+ status: 'completed',+ updatedAt: '2026-07-20T00:00:00.000Z',+ },+ }) as OnboardingUnderstandingSession;++const staleErrors = [+ new StaleUnderstandingRevisionError('provider', 1),+ new StaleUnderstandingSessionError('session-1'),+];++describe('UnderstandingService guards and compensation', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockTriggerProviders.mockResolvedValue({ workflowRunId: 'workflow-1' });+ });++ it('fails a provider attempt with a retryable collection error', async () => {+ const harness = createHarness(createSession({ github: providerState('running', 1) }));++ await harness.service.failProvider({ ...sessionRef, providerId: 'github', revision: 1 });++ expect(harness.repository.failProvider).toHaveBeenCalledWith({+ errors: [+ {+ code: 'UNDERSTANDING_PROVIDER_COLLECTION_FAILED',+ message: 'github collection failed',+ operation: 'collection',+ provider: 'github',+ retryable: true,+ },+ ],+ failedCount: 1,+ providerId: 'github',+ revision: 1,+ sessionId: 'session-1',+ succeededCount: 0,+ topicId: 'topic-1',+ });+ });++ it.each(staleErrors)('ignores a stale provider failure ($name)', async (error) => {+ const harness = createHarness(createSession({ github: providerState('running', 1) }));+ harness.repository.failProvider.mockRejectedValueOnce(error);++ await expect(+ harness.service.failProvider({ ...sessionRef, providerId: 'github', revision: 1 }),+ ).resolves.toBeUndefined();+ });++ it('rethrows any other provider failure error', async () => {+ const harness = createHarness(createSession({ github: providerState('running', 1) }));+ harness.repository.failProvider.mockRejectedValueOnce(new Error('db down'));++ await expect(+ harness.service.failProvider({ ...sessionRef, providerId: 'github', revision: 1 }),+ ).rejects.toThrow('db down');+ });++ it('returns stale for a provider revision that is no longer current', async () => {+ const harness = createHarness(createSession({ github: providerState('completed', 2) }));++ await expect(+ harness.service.processProvider({ ...sessionRef, providerId: 'github', revision: 1 }),+ ).resolves.toEqual({+ failedCount: 0,+ providerId: 'github',+ revision: 1,+ sourceCount: 0,+ status: 'stale',+ succeededCount: 0,+ });+ expect(harness.githubCollect).not.toHaveBeenCalled();+ });++ it('marks the provider failed and rethrows when a retry cannot be dispatched', async () => {+ const harness = createHarness(+ createSession({+ github: {+ ...providerState('failed', 1),+ errors: [+ {+ code: 'X',+ message: 'x',+ operation: 'collection',+ provider: 'github',+ retryable: true,+ },+ ],+ },+ }),+ );+ mockTriggerProviders.mockRejectedValueOnce(new Error('workflow down'));++ await expect(+ harness.service.retry({ ...sessionRef, providerId: 'github', responseLanguage: 'en-US' }),+ ).rejects.toThrow('workflow down');+ expect(harness.repository.failProvider).toHaveBeenCalledWith(+ expect.objectContaining({ providerId: 'github', revision: 2 }),+ );+ });++ it('fails every recollection attempt and rethrows the trigger error when revise cannot dispatch', async () => {+ const harness = createHarness(+ createSession({+ github: providerState('completed', 1),+ gmail: providerState('completed', 1),+ }),+ );+ mockTriggerProviders.mockRejectedValueOnce(new Error('workflow down'));+ harness.repository.failProvider.mockRejectedValueOnce(new Error('db down'));++ await expect(+ harness.service.revise({+ expectedFeedbackRevision: 0,+ providerIds: [],+ responseLanguage: 'en-US',+ ...sessionRef,+ }),+ ).rejects.toThrow('workflow down');+ expect(harness.repository.failProvider).toHaveBeenCalledTimes(2);+ expect(harness.repository.failProvider).toHaveBeenCalledWith(+ expect.objectContaining({ providerId: 'github', revision: 2 }),+ );+ expect(harness.repository.failProvider).toHaveBeenCalledWith(+ expect.objectContaining({ providerId: 'gmail', revision: 2 }),+ );+ });++ it('returns the published result when the writing already completed', async () => {+ const harness = createHarness(completedWriting());++ await expect(+ harness.service.processCollected({+ ...sessionRef,+ expectedSourceFingerprint: fingerprint,+ responseLanguage: 'en-US',+ }),+ ).resolves.toEqual({+ feedbackRevision: 2,+ generationRevision: 3,+ published: true,+ resultId: 'assistant-1',+ sourceFingerprint: fingerprint,+ });+ expect(harness.writerAgent).not.toHaveBeenCalled();+ });++ it('does not fail a writing that belongs to another fingerprint', async () => {+ const harness = createHarness(completedWriting(undefined, 'gmail@1'));++ await expect(+ harness.service.failWriting({ ...sessionRef, sourceFingerprint: fingerprint }),+ ).resolves.toBeUndefined();+ expect(harness.repository.failWriting).not.toHaveBeenCalled();+ });++ it.each(staleErrors)('ignores a stale writing failure ($name)', async (error) => {+ const harness = createHarness(createSession({ github: providerState('completed', 1) }));+ harness.repository.failWriting.mockRejectedValueOnce(error);++ await expect(+ harness.service.failWriting({ ...sessionRef, sourceFingerprint: fingerprint }),+ ).resolves.toBeUndefined();+ });++ it.each([+ {+ expected: { published: false, sourceFingerprint: fingerprint },+ name: 'no completed writing',+ session: createSession({ github: providerState('completed', 1) }),+ },+ {+ expected: { published: true, sourceFingerprint: fingerprint },+ name: 'a completed detailed pass',+ session: completedWriting({ status: 'completed', updatedAt: '2026-07-20T00:00:00.000Z' }),+ },+ {+ expected: { published: false, sourceFingerprint: fingerprint },+ name: 'no running detailed pass',+ session: completedWriting(),+ },+ ])('settles the detailed persona early for $name', async ({ expected, session }) => {+ const harness = createHarness(session);++ await expect(+ harness.service.processDetailedPersona({+ ...sessionRef,+ expectedSourceFingerprint: fingerprint,+ responseLanguage: 'en-US',+ }),+ ).resolves.toEqual(expected);+ expect(harness.generateObject).not.toHaveBeenCalled();+ });++ it('fails only a running detailed pass', async () => {+ const idle = createHarness(completedWriting());+ await expect(+ idle.service.failDetailedPersona({ ...sessionRef, sourceFingerprint: fingerprint }),+ ).resolves.toBeUndefined();+ expect(idle.repository.failDetailedWriting).not.toHaveBeenCalled();++ const running = createHarness(+ completedWriting({ status: 'running', updatedAt: '2026-07-20T00:00:00.000Z' }),+ );+ await running.service.failDetailedPersona({ ...sessionRef, sourceFingerprint: fingerprint });+ expect(running.repository.failDetailedWriting).toHaveBeenCalledWith({+ error: {+ code: 'UNDERSTANDING_DETAILED_WRITING_FAILED',+ message: 'understanding detailed-writing failed',+ operation: 'detailed-writing',+ provider: 'understanding',+ retryable: true,+ },+ feedbackRevision: 2,+ generationRevision: 3,+ sessionId: 'session-1',+ sourceFingerprint: fingerprint,+ topicId: 'topic-1',+ });+ });++ // Current behavior, pinned as is: `failDetailedPersona` returns the repository promise without+ // awaiting it, so its `catch` never sees a stale rejection and the error reaches the caller.+ it.each(staleErrors)('propagates a stale detailed failure ($name)', async (error) => {+ const harness = createHarness(+ completedWriting({ status: 'running', updatedAt: '2026-07-20T00:00:00.000Z' }),+ );+ harness.repository.failDetailedWriting.mockRejectedValueOnce(error);++ await expect(+ harness.service.failDetailedPersona({ ...sessionRef, sourceFingerprint: fingerprint }),+ ).rejects.toBe(error);+ });+});diff --git a/apps/server/src/services/understanding/service.test.ts b/apps/server/src/services/understanding/service/index.test.tssimilarity index 72%rename from apps/server/src/services/understanding/service.test.tsrename to apps/server/src/services/understanding/service/index.test.tsindex cbb61956e86..f5c33d8bb86 100644--- a/apps/server/src/services/understanding/service.test.ts+++ b/apps/server/src/services/understanding/service/index.test.ts@@ -2,18 +2,17 @@ import {UNDERSTANDING_ANALYSIS_JSON_SCHEMA,UNDERSTANDING_DETAILED_PERSONA_JSON_SCHEMA,} from '@lobechat/prompts';-import {- type CollectionDiagnostics,- type OnboardingUnderstandingMessageMetadata,- type OnboardingUnderstandingSession,- RequestTrigger,- type UnderstandingAnalysis,-} from '@lobechat/types';+import { RequestTrigger } from '@lobechat/types';import { beforeEach, describe, expect, it, vi } from 'vitest';-import { UnderstandingService, type UnderstandingServiceDependencies } from './service';-import type { StoredUnderstandingProviderContext } from './sourceStore';-import type { UnderstandingProvider } from './types';+import {+ analysis,+ createHarness,+ createSession,+ diagnostics,+ providerState,+ storedContext,+} from './testUtils';const { mockAssertWorkflowAvailable, mockTriggerProviders, mockTriggerWriting } = vi.hoisted(() => ({@@ -31,289 +30,6 @@ vi.mock('@/server/workflows/onboardingUnderstanding', () => ({},}));-const analysis: UnderstandingAnalysis = {- composition: {- identities: [],- interests: [- {- description: 'TEST_INTEREST_DESCRIPTION',- rank: 96,- title: 'TEST_INTEREST_TITLE',- },- ],- lifeStyle: [],- social: [],- working: [],- },- personaProposal: {- content: 'TEST_PERSONA_CONTENT',- reasoning: 'TEST_PERSONA_REASONING',- tagline: 'TEST_PERSONA_TAGLINE',- },- profile: {- description: 'TEST_PROFILE_DESCRIPTION',- domains: ['TEST_PROFILE_DOMAIN'],- name: 'TEST_PROFILE_NAME',- pronoun: 'TEST_PROFILE_PRONOUN',- roles: ['TEST_PROFILE_ROLE'],- summary: 'TEST_PROFILE_SUMMARY',- tagline: 'TEST_PROFILE_TAGLINE',- },-};--const diagnostics: CollectionDiagnostics = {- errors: [],- evidenceCount: 3,- failedCount: 0,- succeededCount: 2,-};--const providerState = (- status: 'pending' | 'running' | 'completed' | 'failed',- revision = status === 'pending' ? 0 : 1,-) => ({- errors: [],- failedCount: 0,- revision,- status,- succeededCount: status === 'completed' ? 2 : 0,-});--const createSession = (- sources: OnboardingUnderstandingSession['sources'] = {- github: providerState('pending'),- gmail: providerState('pending'),- },-): OnboardingUnderstandingSession => ({ id: 'session-1', sources });--const storedContext = (- providerId: string,- context: string,- revision = 1,-): StoredUnderstandingProviderContext => ({- context,- diagnostics,- providerId,- revision,- sourceCount: 3,-});--const createHarness = (initialSession?: OnboardingUnderstandingSession) => {- let session = initialSession;- let latestAssistant:- | { content?: unknown; error?: unknown; id: string; role: string; threadId?: string | null }- | undefined;- const stored = new Map<string, StoredUnderstandingProviderContext>();- const assistantMetadata = new Map<string, OnboardingUnderstandingMessageMetadata>();- const providers = new Map<string, UnderstandingProvider>();- const githubCollect = vi.fn(async () => ({- context: 'Provider: github\n\n# Source Brief\n\nPRIVATE_GITHUB_CONTEXT',- diagnostics,- sourceCount: 3,- }));- providers.set('github', {- collect: githubCollect,- connectionSource: 'lobehub',- id: 'github',- });- providers.set('gmail', {- collect: vi.fn(async () => ({- context:- 'Provider: gmail\n\n# Source Brief\n\n```xml\n<gmail>PRIVATE_GMAIL_CONTEXT</gmail>\n```',- diagnostics,- sourceCount: 3,- })),- connectionSource: 'composio',- id: 'gmail',- });-- const repository = {- commitDetailedWriting: vi.fn(async (_input: unknown) => ({ published: true })),- commitWriting: vi.fn(async (_input: unknown) => ({ published: true })),- completeProvider: vi.fn(- async ({ providerId, revision }: { providerId: string; revision: number }) => {- const transition = {- ...session!,- sources: {- ...session!.sources,- [providerId]: providerState('completed', revision),- },- };- session = transition;- return transition;- },- ),- confirm: vi.fn(async () => ({ personaVersion: 1 })),- expireProviderContexts: vi.fn(async () => session!),- extend: vi.fn(- async ({ feedback, providerIds }: { feedback?: string; providerIds: string[] }) => {- const currentFeedback = session?.feedback ?? { revision: 0, turns: [] };- const nextRevision = feedback ? currentFeedback.revision + 1 : currentFeedback.revision;- session = {- ...session!,- feedback: {- revision: nextRevision,- turns: feedback- ? [- ...currentFeedback.turns,- {- content: feedback,- createdAt: '2026-07-24T00:00:00.000Z',- revision: nextRevision,- },- ]- : currentFeedback.turns,- },- sources: {- ...session!.sources,- ...Object.fromEntries(- providerIds- .filter((providerId) => !session!.sources[providerId])- .map((providerId) => [providerId, providerState('pending')]),- ),- },- };- return {- attempts: providerIds- .filter((providerId) => session!.sources[providerId]?.status === 'pending')- .map((id) => ({ id, revision: 1 })),- session,- };- },- ),- failProvider: vi.fn(async () => session!),- failDetailedWriting: vi.fn(async () => 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 = {- id: sessionId,- sources: Object.fromEntries(providerIds.map((id) => [id, providerState('pending')])),- } as OnboardingUnderstandingSession;- return session;- }),- markProviderRunning: vi.fn(async (_topicId: string, _sessionId: string, providerId: string) => {- const revision = (session?.sources[providerId]?.revision ?? 0) + 1;- session = {- ...session!,- sources: { ...session!.sources, [providerId]: providerState('running', revision) },- };- return { revision };- }),- prepareWriting: vi.fn(async ({ sourceFingerprint, threadId }) => {- const feedbackRevision = session?.feedback?.revision ?? 0;- const generationRevision = (session?.generationRevision ?? 0) + 1;- session = {- ...session!,- generationRevision,- writing: {- feedbackRevision,- generationRevision,- resultMessageId: session?.writing?.resultMessageId,- sourceFingerprint,- status: 'running',- updatedAt: '2026-07-20T00:00:00.000Z',- },- };- return { feedbackRevision, generationRevision, ready: true, threadId };- }),- };- const sourceStore = {- deleteSession: vi.fn(),- get: vi.fn(- async ({ providerId, revision }: { providerId: string; revision: number }) =>- stored.get(`${providerId}:${revision}`) ?? null,- ),- put: vi.fn(async (value: StoredUnderstandingProviderContext) => {- stored.set(`${value.providerId}:${value.revision}`, value);- }),- };- const sourceStoreFactory = vi.fn(function () {- return sourceStore;- });- const writerAgent = vi.fn(async () => ({- id: 'agent-1',- model: 'gpt-5.4-mini',- provider: 'lobehub',- }));- const generateObject = vi.fn(- async (- _input: Parameters<UnderstandingServiceDependencies['generator']['generateObject']>[0],- _options: Parameters<UnderstandingServiceDependencies['generator']['generateObject']>[1],- ): Promise<unknown> => analysis,- );- type CreateMessageInput = Parameters<UnderstandingServiceDependencies['messages']['create']>[0];- const messages = {- create: vi.fn(async (_input: CreateMessageInput) => ({ id: 'assistant-structured' })),- findById: vi.fn(async (id: string) => ({- content: JSON.stringify(analysis),- metadata: assistantMetadata.has(id)- ? { onboardingUnderstanding: assistantMetadata.get(id) }- : undefined,- })),- findLatestAssistantMessageByThread: vi.fn(async () => latestAssistant),- };- const listAvailableProviderIds = vi.fn(async (providerIds: readonly string[]) => [- ...providerIds,- ]);- const dependencies: UnderstandingServiceDependencies = {- connectorData: {- listAvailableProviderIds,- } as unknown as UnderstandingServiceDependencies['connectorData'],- generator: {- generateObject:- generateObject as UnderstandingServiceDependencies['generator']['generateObject'],- },- ids: () => 'session-new',- messages,- persona: { getLatestPersonaDocument: vi.fn(async () => null) },- providers,- repository,- sourceStore: sourceStoreFactory,- topic: {- assertActiveOnboardingTopic: vi.fn(),- },- userId: 'user-1',- writerAgent,- };-- return {- dependencies,- githubCollect,- generateObject,- listAvailableProviderIds,- messages,- repository,- service: new UnderstandingService(dependencies),- setLatestAssistant: (value: typeof latestAssistant) => (latestAssistant = value),- setAssistantMetadata: (id: string, value: OnboardingUnderstandingMessageMetadata) =>- assistantMetadata.set(id, value),- setProvider: (providerId: string, provider: UnderstandingProvider) =>- providers.set(providerId, provider),- setSession: (value: OnboardingUnderstandingSession) => (session = value),- sourceStore,- sourceStoreFactory,- stored,- writerAgent,- };-};-describe('UnderstandingService', () => {beforeEach(() => {vi.clearAllMocks();diff --git a/apps/server/src/services/understanding/service/index.ts b/apps/server/src/services/understanding/service/index.tsnew file mode 100644index 00000000000..07509d9ca72--- /dev/null+++ b/apps/server/src/services/understanding/service/index.ts@@ -0,0 +1,447 @@+import { createHash, randomUUID } from 'node:crypto';++import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';+import {+ getUnderstandingSourceFingerprint,+ OnboardingUnderstandingRepository,+ UnderstandingPreconditionError,+ UnderstandingResourceNotFoundError,+ UnderstandingSessionNotFoundError,+} from '@lobechat/database';+import { observeOnboardingUnderstandingOperation } from '@lobechat/observability-otel/modules/onboarding-understanding';+import type {+ ConfirmOnboardingUnderstandingInput,+ OnboardingUnderstandingMessageMetadata,+ OnboardingUnderstandingPollingResult,+ OnboardingUnderstandingSession,+ RetryOnboardingUnderstandingProviderInput,+ ReviseOnboardingUnderstandingInput,+} from '@lobechat/types';+import { projectOnboardingUnderstandingSessionStatus } from '@lobechat/types';+import pMap from 'p-map';++import { AgentModel } from '@/database/models/agent';+import { MessageModel } from '@/database/models/message';+import { TopicModel } from '@/database/models/topic';+import { UserPersonaModel } from '@/database/models/userMemory/persona';+import type { LobeChatDatabase } from '@/database/type';+import { AiGenerationService } from '@/server/services/aiGeneration';+import { ConnectorDataService } from '@/server/services/connectorData';+import { OnboardingUnderstandingWorkflow } from '@/server/workflows/onboardingUnderstanding';++import { understandingProviderMap } from '../providers';+import { UnderstandingSourceStore } from '../sourceStore';+import type { UnderstandingProvider } from '../types';+import * as detailedPersona from './detailedPersona';+import * as providerCollection from './providerCollection';+import { readActiveSession } from './session';+import type {+ ProcessCollectedInput,+ ProviderOperationInput,+ UnderstandingServiceDependencies,+} from './types';+import { PROVIDER_IO_CONCURRENCY, storedProposal } from './utils';+import * as writing from './writing';++export { UnderstandingProviderContextUnavailableError } from './errors';+export type { UnderstandingServiceDependencies } from './types';++/** Controls optional downstream work started with an Understanding collection run. */+export interface UnderstandingStartOptions {+ /**+ * Starts task recommendations as soon as the first source completes.+ *+ * @default true+ */+ triggerTaskRecommendations?: boolean;+}++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[],+ ): Promise<OnboardingUnderstandingSession> =>+ observeOnboardingUnderstandingOperation({ operation: 'initialize', topicId }, async () => {+ await observeOnboardingUnderstandingOperation(+ { operation: 'topic.assert-active', topicId },+ () => this.dependencies.topic.assertActiveOnboardingTopic(topicId),+ );++ const current = await observeOnboardingUnderstandingOperation(+ { operation: 'session.read', topicId },+ () => this.dependencies.repository.get(topicId),+ );+ if (current) return current;++ const requestedProviderIds = selectedProviderIds+ ? [...new Set(selectedProviderIds)].sort()+ : [...this.dependencies.providers.keys()].sort();+ if (requestedProviderIds.some((providerId) => !this.dependencies.providers.has(providerId))) {+ throw new UnderstandingResourceNotFoundError('session');+ }+ const availableProviderIds = new Set(+ await observeOnboardingUnderstandingOperation(+ { operation: 'provider.resolve-available', topicId },+ () => this.listSourceProviderIds(),+ ),+ );+ const providerIds = requestedProviderIds.filter((providerId) =>+ availableProviderIds.has(providerId),+ );+ const sessionId = this.dependencies.ids();+ return observeOnboardingUnderstandingOperation(+ { operation: 'session.persist', sessionId, topicId },+ () => this.dependencies.repository.initialize(topicId, sessionId, providerIds),+ );+ });++ start = async (+ topicId: string,+ responseLanguage: string,+ selectedProviderIds?: string[],+ options: UnderstandingStartOptions = {},+ ): Promise<OnboardingUnderstandingPollingResult> => {+ const startedAt = Date.now();+ return observeOnboardingUnderstandingOperation(+ { operation: 'session.start', topicId },+ async () => {+ OnboardingUnderstandingWorkflow.assertAvailable();++ const session = await this.initialize(topicId, selectedProviderIds);+ const providers = Object.entries(session.sources)+ .filter(([, state]) => state.status === 'pending')+ .toSorted(([left], [right]) => left.localeCompare(right))+ .map(([id, state]) => ({ id, revision: state.revision + 1 }));+ if (providers.length > 0) {+ await observeOnboardingUnderstandingOperation(+ { operation: 'workflow.trigger', sessionId: session.id, topicId },+ () =>+ OnboardingUnderstandingWorkflow.triggerProviders(+ {+ providers,+ responseLanguage,+ sessionId: session.id,+ startedAt,+ triggerTaskRecommendations: options.triggerTaskRecommendations,+ topicId,+ userId: this.dependencies.userId,+ },+ { workflowRunId: `onboarding-understanding-initial-${session.id}` },+ ),+ );+ }+ return this.get(topicId);+ },+ );+ };++ revise = async (+ input: ReviseOnboardingUnderstandingInput,+ ): Promise<OnboardingUnderstandingPollingResult> => {+ OnboardingUnderstandingWorkflow.assertAvailable();+ 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) =>+ availableProviderIds.has(providerId),+ );++ 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',+ );+ const sourceStore = completedProviders.length > 0 ? this.dependencies.sourceStore() : undefined;+ const storedContexts = sourceStore+ ? await pMap(+ completedProviders,+ ([providerId, state]) =>+ sourceStore.get({+ providerId,+ revision: state.revision,+ sessionId: input.sessionId,+ userId: this.dependencies.userId,+ }),+ { concurrency: PROVIDER_IO_CONCURRENCY },+ )+ : [];+ const expiredProviders = completedProviders.flatMap(([providerId, state], index) =>+ storedContexts[index] ? [] : [{ providerId, revision: state.revision }],+ );+ const currentSourceFingerprint = getUnderstandingSourceFingerprint(next);+ const availableSession =+ expiredProviders.length > 0 && currentSourceFingerprint+ ? await this.dependencies.repository.expireProviderContexts({+ providers: expiredProviders,+ sessionId: input.sessionId,+ sourceFingerprint: currentSourceFingerprint,+ topicId: input.topicId,+ })+ : next;+ const recollectedProviders = await pMap(+ expiredProviders,+ async ({ providerId }) => ({+ id: providerId,+ ...(await this.dependencies.repository.markProviderRunning(+ input.topicId,+ input.sessionId,+ providerId,+ )),+ }),+ { concurrency: PROVIDER_IO_CONCURRENCY },+ );+ const attempts = [...providerAttempts, ...recollectedProviders].sort((left, right) =>+ left.id.localeCompare(right.id),+ );+ 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) {+ // Best effort: every attempt is marked failed even if some writes+ // reject, and the trigger error is what the caller sees.+ await pMap(+ attempts,+ ({ id, revision }) =>+ this.failProvider({+ providerId: id,+ revision,+ sessionId: input.sessionId,+ topicId: input.topicId,+ }).catch(() => undefined),+ { concurrency: PROVIDER_IO_CONCURRENCY },+ );+ throw triggerError;+ }+ }++ const sourceFingerprint = getUnderstandingSourceFingerprint(availableSession);+ if (input.feedback?.trim() && sourceFingerprint) {+ await OnboardingUnderstandingWorkflow.triggerWriting(+ {+ sessionId: input.sessionId,+ responseLanguage: input.responseLanguage,+ sourceFingerprint,+ startedAt: Date.now(),+ topicId: input.topicId,+ userId: this.dependencies.userId,+ },+ {+ workflowRunId: `onboarding-understanding-feedback-${createHash('sha256')+ .update(input.sessionId)+ .update('\0')+ .update(sourceFingerprint)+ .update('\0')+ .update(String(next.feedback?.revision ?? 0))+ .digest('hex')+ .slice(0, 32)}`,+ },+ );+ }++ return this.get(input.topicId);+ };++ get = async (topicId: string): Promise<OnboardingUnderstandingPollingResult> => {+ await this.dependencies.topic.assertActiveOnboardingTopic(topicId);+ const session = await this.dependencies.repository.get(topicId);+ if (!session) throw new UnderstandingSessionNotFoundError(topicId);+ let proposal: OnboardingUnderstandingMessageMetadata | undefined;+ if (session.writing?.resultMessageId) {+ const message = await this.dependencies.messages.findById(session.writing.resultMessageId);+ proposal = storedProposal(message?.metadata);+ }+ return {+ confirmed: Boolean(session.confirmedAt),+ feedback: session.feedback,+ generationRevision: session.generationRevision,+ id: session.id,+ ...(proposal ? { proposal } : {}),+ sources: session.sources,+ status: projectOnboardingUnderstandingSessionStatus(session),+ ...(session.writing ? { writing: session.writing } : {}),+ };+ };++ retry = async (+ input: RetryOnboardingUnderstandingProviderInput,+ ): Promise<OnboardingUnderstandingPollingResult> => {+ OnboardingUnderstandingWorkflow.assertAvailable();+ const session = await this.activeSession(input.topicId, input.sessionId);+ const state = session.sources[input.providerId];+ if (!this.dependencies.providers.has(input.providerId) || !state) {+ throw new UnderstandingResourceNotFoundError('session');+ }+ 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,+ ]);+ if (!availableProviderIds.includes(input.providerId)) return this.get(input.topicId);+ const { revision } = await this.dependencies.repository.markProviderRunning(+ input.topicId,+ input.sessionId,+ input.providerId,+ );+ try {+ await OnboardingUnderstandingWorkflow.triggerProviders(+ {+ providers: [{ id: input.providerId, revision }],+ responseLanguage: input.responseLanguage,+ sessionId: input.sessionId,+ startedAt: Date.now(),+ topicId: input.topicId,+ userId: this.dependencies.userId,+ },+ {+ workflowRunId: `onboarding-understanding-retry-${input.sessionId}-${input.providerId}-${revision}`,+ },+ );+ } catch (triggerError) {+ try {+ await this.failProvider({ ...input, revision });+ } catch (compensationError) {+ console.error('[understanding:retryCompensation]', {+ errorName: compensationError instanceof Error ? compensationError.name : 'UnknownError',+ });+ }+ throw triggerError;+ }+ return this.get(input.topicId);+ };++ processProvider = (input: ProviderOperationInput) =>+ providerCollection.processProvider(this.dependencies, input);++ failProvider = (input: ProviderOperationInput) =>+ providerCollection.failProvider(this.dependencies, input);++ processCollected = (input: ProcessCollectedInput) =>+ writing.processCollected(this.dependencies, input);++ failWriting = (input: Parameters<typeof writing.failWriting>[1]) =>+ writing.failWriting(this.dependencies, input);++ processDetailedPersona = (input: ProcessCollectedInput) =>+ detailedPersona.processDetailedPersona(this.dependencies, input);++ failDetailedPersona = (input: Parameters<typeof detailedPersona.failDetailedPersona>[1]) =>+ detailedPersona.failDetailedPersona(this.dependencies, input);++ confirm = (input: ConfirmOnboardingUnderstandingInput) =>+ this.dependencies.repository.confirm(input);++ private activeSession = (topicId: string, sessionId: string) =>+ readActiveSession(this.dependencies, topicId, sessionId);+}++interface CreateUnderstandingServiceOptions {+ db: LobeChatDatabase;+ providers?: readonly UnderstandingProvider[];+ userId: string;+ workspaceId?: string;+}++export const createUnderstandingService = async ({+ db,+ providers,+ userId,+ workspaceId,+}: CreateUnderstandingServiceOptions): Promise<UnderstandingService> => {+ if (workspaceId) throw new Error('Onboarding Understanding is available only in personal scope');++ const messageModel = new MessageModel(db, userId);+ const topicModel = new TopicModel(db, userId);+ const aiGenerationService = new AiGenerationService(db, userId);++ return new UnderstandingService({+ connectorData: new ConnectorDataService(db, userId),+ generator: aiGenerationService,+ ids: randomUUID,+ messages: {+ create: (params) => messageModel.create(params),+ findById: (id) => messageModel.findById(id),+ findLatestAssistantMessageByThread: async (input) => {+ const message = await messageModel.findLatestAssistantMessageByThread(input);+ return message+ ? {+ content: message.content,+ error: message.error,+ id: message.id,+ role: message.role,+ threadId: message.threadId,+ }+ : message;+ },+ },+ persona: new UserPersonaModel(db, userId),+ providers: providers+ ? new Map(providers.map((provider) => [provider.id, provider]))+ : understandingProviderMap,+ repository: new OnboardingUnderstandingRepository(db, userId),+ sourceStore: () => new UnderstandingSourceStore(),+ topic: {+ assertActiveOnboardingTopic: async (topicId) => {+ const topic = await topicModel.findById(topicId);+ const onboarding = topic?.metadata?.onboardingSession;+ if (!topic || !onboarding || onboarding.finishedAt) {+ throw new UnderstandingResourceNotFoundError('topic');+ }+ },+ },+ userId,+ writerAgent: async () => {+ const agentModel = new AgentModel(db, userId);+ const writerAgent = await agentModel.getBuiltinAgent(+ BUILTIN_AGENT_SLUGS.onboardingUnderstanding,+ );+ if (!writerAgent) throw new Error('Onboarding Understanding agent is unavailable');+ const modelConfig = await agentModel.getAgentModelConfig(writerAgent.id);+ if (!modelConfig) throw new Error('Onboarding Understanding agent is unavailable');+ return { ...modelConfig, id: writerAgent.id };+ },+ });+};diff --git a/apps/server/src/services/understanding/service/providerCollection.ts b/apps/server/src/services/understanding/service/providerCollection.tsnew file mode 100644index 00000000000..03dd7c89b12--- /dev/null+++ b/apps/server/src/services/understanding/service/providerCollection.ts@@ -0,0 +1,288 @@+import {+ ConnectorDataError,+ getConnectorErrorMessage,+ isConnectorErrorRetryable,+} from '@lobechat/connector-data';+import {+ getUnderstandingSourceFingerprint,+ StaleUnderstandingRevisionError,+ StaleUnderstandingSessionError,+ UnderstandingResourceNotFoundError,+} from '@lobechat/database';+import {+ observeOnboardingUnderstandingOperation,+ observeOnboardingUnderstandingProviderCollection,+} from '@lobechat/observability-otel/modules/onboarding-understanding';+import type { CollectionDiagnostics } from '@lobechat/types';++import { MAX_SOURCE_BRIEF_LENGTH } from '../sourceStore';+import { UnderstandingProviderContextUnavailableError } from './errors';+import { readActiveSession } from './session';+import type { ProviderOperationInput, UnderstandingServiceDependencies } from './types';+import { boundProviderDiagnostics, createCollectionError } from './utils';++/**+ * Normalizes a thrown provider value into the persisted diagnostic shape without replacing its+ * original message.+ *+ * Before:+ * - `Error("GraphQL FORBIDDEN at viewer.repository")`+ *+ * After:+ * - `{ provider: "github", operation: "collection", message: "GraphQL FORBIDDEN at viewer.repository" }`+ */+const createProviderCollectionError = (providerId: string, error: unknown) => {+ const connectorError = error instanceof ConnectorDataError ? error : undefined;+ return createCollectionError(+ providerId,+ connectorError?.operation ?? 'collection',+ connectorError?.code ?? 'UNDERSTANDING_PROVIDER_COLLECTION_FAILED',+ isConnectorErrorRetryable(error),+ getConnectorErrorMessage(error) ?? String(error),+ );+};++export const processProvider = async (+ dependencies: UnderstandingServiceDependencies,+ input: ProviderOperationInput,+) =>+ observeOnboardingUnderstandingOperation(+ {+ operation: 'provider.process',+ providerId: input.providerId,+ sessionId: input.sessionId,+ topicId: input.topicId,+ },+ async () => {+ const operationAttributes = {+ providerId: input.providerId,+ sessionId: input.sessionId,+ topicId: input.topicId,+ };+ const session = await observeOnboardingUnderstandingOperation(+ { ...operationAttributes, operation: 'session.read' },+ () => readActiveSession(dependencies, input.topicId, input.sessionId),+ );+ const provider = dependencies.providers.get(input.providerId);+ const state = session.sources[input.providerId];+ if (!provider || !state) throw new UnderstandingResourceNotFoundError('session');+ const stale = () => ({+ failedCount: 0,+ providerId: input.providerId,+ revision: input.revision,+ sourceCount: 0,+ status: 'stale' as const,+ succeededCount: 0,+ });++ if (state.status === 'completed') {+ if (state.revision !== input.revision) return stale();+ const sourceFingerprint = getUnderstandingSourceFingerprint(session);+ if (!sourceFingerprint) throw new UnderstandingProviderContextUnavailableError();+ const stored = await dependencies.sourceStore().get({+ providerId: input.providerId,+ revision: input.revision,+ sessionId: input.sessionId,+ userId: dependencies.userId,+ });+ if (stored) {+ return {+ failedCount: stored.diagnostics.failedCount,+ providerId: input.providerId,+ revision: input.revision,+ sourceCount: stored.sourceCount,+ sourceFingerprint,+ status: 'completed' as const,+ succeededCount: stored.diagnostics.succeededCount,+ };+ }+ const expired = await dependencies.repository.expireProviderContexts({+ providers: [{ providerId: input.providerId, revision: input.revision }],+ sessionId: input.sessionId,+ sourceFingerprint,+ topicId: input.topicId,+ });+ const expiredState = expired.sources[input.providerId];+ return expiredState?.revision === input.revision && expiredState.status === 'failed'+ ? {+ failedCount: expiredState.failedCount,+ providerId: input.providerId,+ revision: input.revision,+ sourceCount: 0,+ status: 'failed' as const,+ succeededCount: expiredState.succeededCount,+ }+ : stale();+ }++ if (state.status === 'pending') {+ if (state.revision + 1 !== input.revision) return stale();+ const running = await observeOnboardingUnderstandingOperation(+ { ...operationAttributes, operation: 'provider.mark-running' },+ () =>+ dependencies.repository.markProviderRunning(+ input.topicId,+ input.sessionId,+ input.providerId,+ ),+ );+ if (running.revision !== input.revision) return stale();+ } else if (state.status !== 'running' || state.revision !== input.revision) {+ return stale();+ }++ let collection;+ try {+ collection = await observeOnboardingUnderstandingProviderCollection(+ operationAttributes,+ async () => {+ const collected = await provider.collect({+ connectorData: dependencies.connectorData,+ userId: dependencies.userId,+ });+ const context = collected.context.trim().slice(0, MAX_SOURCE_BRIEF_LENGTH);+ const diagnostics = boundProviderDiagnostics(collected.diagnostics);+ const usable =+ Boolean(context) &&+ collected.sourceCount > 0 &&+ diagnostics.evidenceCount > 0 &&+ diagnostics.succeededCount > 0;+ const outcome = !usable+ ? ('failed' as const)+ : diagnostics.failedCount > 0 || diagnostics.errors.length > 0+ ? ('partial' as const)+ : ('completed' as const);++ return {+ diagnostics: diagnostics.errors,+ evidenceCount: diagnostics.evidenceCount,+ failedCount: diagnostics.failedCount,+ outcome,+ result: { context, diagnostics, sourceCount: collected.sourceCount, usable },+ sourceCount: collected.sourceCount,+ succeededCount: diagnostics.succeededCount,+ };+ },+ (error) => createProviderCollectionError(input.providerId, error),+ );+ } catch (error) {+ const diagnostic = createProviderCollectionError(input.providerId, error);+ if (diagnostic.retryable) throw error;+ return recordProviderFailure(dependencies, input, 0, {+ errors: [diagnostic],+ evidenceCount: 0,+ failedCount: 1,+ succeededCount: 0,+ });+ }++ const { context, diagnostics, sourceCount, usable } = collection;+ if (!usable)+ return recordProviderFailure(dependencies, input, diagnostics.succeededCount, diagnostics);++ const stored = {+ context,+ diagnostics,+ providerId: input.providerId,+ revision: input.revision,+ sessionId: input.sessionId,+ sourceCount,+ userId: dependencies.userId,+ };+ await observeOnboardingUnderstandingOperation(+ { ...operationAttributes, operation: 'provider.persist-context' },+ () => dependencies.sourceStore().put(stored),+ );+ const transition = await observeOnboardingUnderstandingOperation(+ { ...operationAttributes, operation: 'provider.complete' },+ () =>+ dependencies.repository.completeProvider({+ errors: diagnostics.errors,+ failedCount: diagnostics.failedCount,+ providerId: input.providerId,+ revision: input.revision,+ sessionId: input.sessionId,+ succeededCount: diagnostics.succeededCount,+ topicId: input.topicId,+ }),+ );+ const sourceFingerprint = getUnderstandingSourceFingerprint(transition);+ if (!sourceFingerprint) throw new UnderstandingProviderContextUnavailableError();+ return {+ failedCount: diagnostics.failedCount,+ providerId: input.providerId,+ revision: input.revision,+ sourceCount,+ sourceFingerprint,+ status: 'completed' as const,+ succeededCount: diagnostics.succeededCount,+ };+ },+ );++export const failProvider = async (+ dependencies: UnderstandingServiceDependencies,+ input: ProviderOperationInput,+) => {+ try {+ return await dependencies.repository.failProvider({+ errors: [+ createCollectionError(+ input.providerId,+ 'collection',+ 'UNDERSTANDING_PROVIDER_COLLECTION_FAILED',+ true,+ ),+ ],+ failedCount: 1,+ providerId: input.providerId,+ revision: input.revision,+ sessionId: input.sessionId,+ succeededCount: 0,+ topicId: input.topicId,+ });+ } catch (error) {+ if (+ error instanceof StaleUnderstandingRevisionError ||+ error instanceof StaleUnderstandingSessionError+ ) {+ return;+ }+ throw error;+ }+};++const recordProviderFailure = async (+ dependencies: UnderstandingServiceDependencies,+ input: ProviderOperationInput,+ succeededCount: number,+ diagnostics?: CollectionDiagnostics,+) => {+ const errors = diagnostics?.errors.length+ ? diagnostics.errors+ : [+ createCollectionError(+ input.providerId,+ 'collection',+ 'UNDERSTANDING_PROVIDER_COLLECTION_FAILED',+ false,+ ),+ ];+ await dependencies.repository.failProvider({+ errors,+ failedCount: Math.max(1, diagnostics?.failedCount ?? 1),+ providerId: input.providerId,+ revision: input.revision,+ sessionId: input.sessionId,+ succeededCount,+ topicId: input.topicId,+ });+ return {+ failedCount: Math.max(1, diagnostics?.failedCount ?? 1),+ providerId: input.providerId,+ revision: input.revision,+ sourceCount: 0,+ status: 'failed' as const,+ succeededCount,+ };+};diff --git a/apps/server/src/services/understanding/service/session.ts b/apps/server/src/services/understanding/service/session.tsnew file mode 100644index 00000000000..0e4b2917cd8--- /dev/null+++ b/apps/server/src/services/understanding/service/session.ts@@ -0,0 +1,18 @@+import {+ StaleUnderstandingSessionError,+ UnderstandingSessionNotFoundError,+} from '@lobechat/database';++import type { UnderstandingServiceDependencies } from './types';++export const readActiveSession = async (+ dependencies: UnderstandingServiceDependencies,+ topicId: string,+ sessionId: string,+) => {+ await dependencies.topic.assertActiveOnboardingTopic(topicId);+ const session = await dependencies.repository.get(topicId);+ if (!session) throw new UnderstandingSessionNotFoundError(topicId);+ if (session.id !== sessionId) throw new StaleUnderstandingSessionError(sessionId);+ return session;+};diff --git a/apps/server/src/services/understanding/service/testUtils.ts b/apps/server/src/services/understanding/service/testUtils.tsnew file mode 100644index 00000000000..bebb330ce14--- /dev/null+++ b/apps/server/src/services/understanding/service/testUtils.ts@@ -0,0 +1,294 @@+import {+ type CollectionDiagnostics,+ type OnboardingUnderstandingMessageMetadata,+ type OnboardingUnderstandingSession,+ type UnderstandingAnalysis,+} from '@lobechat/types';+import { vi } from 'vitest';++import type { StoredUnderstandingProviderContext } from '../sourceStore';+import type { UnderstandingProvider } from '../types';+import { UnderstandingService, type UnderstandingServiceDependencies } from '.';++export const analysis: UnderstandingAnalysis = {+ composition: {+ identities: [],+ interests: [+ {+ description: 'TEST_INTEREST_DESCRIPTION',+ rank: 96,+ title: 'TEST_INTEREST_TITLE',+ },+ ],+ lifeStyle: [],+ social: [],+ working: [],+ },+ personaProposal: {+ content: 'TEST_PERSONA_CONTENT',+ reasoning: 'TEST_PERSONA_REASONING',+ tagline: 'TEST_PERSONA_TAGLINE',+ },+ profile: {+ description: 'TEST_PROFILE_DESCRIPTION',+ domains: ['TEST_PROFILE_DOMAIN'],+ name: 'TEST_PROFILE_NAME',+ pronoun: 'TEST_PROFILE_PRONOUN',+ roles: ['TEST_PROFILE_ROLE'],+ summary: 'TEST_PROFILE_SUMMARY',+ tagline: 'TEST_PROFILE_TAGLINE',+ },+};++export const diagnostics: CollectionDiagnostics = {+ errors: [],+ evidenceCount: 3,+ failedCount: 0,+ succeededCount: 2,+};++export const providerState = (+ status: 'pending' | 'running' | 'completed' | 'failed',+ revision = status === 'pending' ? 0 : 1,+) => ({+ errors: [],+ failedCount: 0,+ revision,+ status,+ succeededCount: status === 'completed' ? 2 : 0,+});++export const createSession = (+ sources: OnboardingUnderstandingSession['sources'] = {+ github: providerState('pending'),+ gmail: providerState('pending'),+ },+): OnboardingUnderstandingSession => ({ id: 'session-1', sources });++export const storedContext = (+ providerId: string,+ context: string,+ revision = 1,+): StoredUnderstandingProviderContext => ({+ context,+ diagnostics,+ providerId,+ revision,+ sourceCount: 3,+});++export const createHarness = (initialSession?: OnboardingUnderstandingSession) => {+ let session = initialSession;+ let latestAssistant:+ | { content?: unknown; error?: unknown; id: string; role: string; threadId?: string | null }+ | undefined;+ const stored = new Map<string, StoredUnderstandingProviderContext>();+ const assistantMetadata = new Map<string, OnboardingUnderstandingMessageMetadata>();+ const providers = new Map<string, UnderstandingProvider>();+ const githubCollect = vi.fn(async () => ({+ context: 'Provider: github\n\n# Source Brief\n\nPRIVATE_GITHUB_CONTEXT',+ diagnostics,+ sourceCount: 3,+ }));+ providers.set('github', {+ collect: githubCollect,+ connectionSource: 'lobehub',+ id: 'github',+ });+ providers.set('gmail', {+ collect: vi.fn(async () => ({+ context:+ 'Provider: gmail\n\n# Source Brief\n\n```xml\n<gmail>PRIVATE_GMAIL_CONTEXT</gmail>\n```',+ diagnostics,+ sourceCount: 3,+ })),+ connectionSource: 'composio',+ id: 'gmail',+ });++ const repository = {+ commitDetailedWriting: vi.fn(async (_input: unknown) => ({ published: true })),+ commitWriting: vi.fn(async (_input: unknown) => ({ published: true })),+ completeProvider: vi.fn(+ async ({ providerId, revision }: { providerId: string; revision: number }) => {+ const transition = {+ ...session!,+ sources: {+ ...session!.sources,+ [providerId]: providerState('completed', revision),+ },+ };+ session = transition;+ return transition;+ },+ ),+ confirm: vi.fn(async () => ({ personaVersion: 1 })),+ expireProviderContexts: vi.fn(async () => session!),+ extend: vi.fn(+ async ({ feedback, providerIds }: { feedback?: string; providerIds: string[] }) => {+ const currentFeedback = session?.feedback ?? { revision: 0, turns: [] };+ const nextRevision = feedback ? currentFeedback.revision + 1 : currentFeedback.revision;+ session = {+ ...session!,+ feedback: {+ revision: nextRevision,+ turns: feedback+ ? [+ ...currentFeedback.turns,+ {+ content: feedback,+ createdAt: '2026-07-24T00:00:00.000Z',+ revision: nextRevision,+ },+ ]+ : currentFeedback.turns,+ },+ sources: {+ ...session!.sources,+ ...Object.fromEntries(+ providerIds+ .filter((providerId) => !session!.sources[providerId])+ .map((providerId) => [providerId, providerState('pending')]),+ ),+ },+ };+ return {+ attempts: providerIds+ .filter((providerId) => session!.sources[providerId]?.status === 'pending')+ .map((id) => ({ id, revision: 1 })),+ session,+ };+ },+ ),+ failProvider: vi.fn(async () => session!),+ failDetailedWriting: vi.fn(async () => 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 = {+ id: sessionId,+ sources: Object.fromEntries(providerIds.map((id) => [id, providerState('pending')])),+ } as OnboardingUnderstandingSession;+ return session;+ }),+ markProviderRunning: vi.fn(async (_topicId: string, _sessionId: string, providerId: string) => {+ const revision = (session?.sources[providerId]?.revision ?? 0) + 1;+ session = {+ ...session!,+ sources: { ...session!.sources, [providerId]: providerState('running', revision) },+ };+ return { revision };+ }),+ prepareWriting: vi.fn(async ({ sourceFingerprint, threadId }) => {+ const feedbackRevision = session?.feedback?.revision ?? 0;+ const generationRevision = (session?.generationRevision ?? 0) + 1;+ session = {+ ...session!,+ generationRevision,+ writing: {+ feedbackRevision,+ generationRevision,+ resultMessageId: session?.writing?.resultMessageId,+ sourceFingerprint,+ status: 'running',+ updatedAt: '2026-07-20T00:00:00.000Z',+ },+ };+ return { feedbackRevision, generationRevision, ready: true, threadId };+ }),+ };+ const sourceStore = {+ deleteSession: vi.fn(),+ get: vi.fn(+ async ({ providerId, revision }: { providerId: string; revision: number }) =>+ stored.get(`${providerId}:${revision}`) ?? null,+ ),+ put: vi.fn(async (value: StoredUnderstandingProviderContext) => {+ stored.set(`${value.providerId}:${value.revision}`, value);+ }),+ };+ const sourceStoreFactory = vi.fn(function () {+ return sourceStore;+ });+ const writerAgent = vi.fn(async () => ({+ id: 'agent-1',+ model: 'gpt-5.4-mini',+ provider: 'lobehub',+ }));+ const generateObject = vi.fn(+ async (+ _input: Parameters<UnderstandingServiceDependencies['generator']['generateObject']>[0],+ _options: Parameters<UnderstandingServiceDependencies['generator']['generateObject']>[1],+ ): Promise<unknown> => analysis,+ );+ type CreateMessageInput = Parameters<UnderstandingServiceDependencies['messages']['create']>[0];+ const messages = {+ create: vi.fn(async (_input: CreateMessageInput) => ({ id: 'assistant-structured' })),+ findById: vi.fn(async (id: string) => ({+ content: JSON.stringify(analysis),+ metadata: assistantMetadata.has(id)+ ? { onboardingUnderstanding: assistantMetadata.get(id) }+ : undefined,+ })),+ findLatestAssistantMessageByThread: vi.fn(async () => latestAssistant),+ };+ const listAvailableProviderIds = vi.fn(async (providerIds: readonly string[]) => [+ ...providerIds,+ ]);+ const dependencies: UnderstandingServiceDependencies = {+ connectorData: {+ listAvailableProviderIds,+ } as unknown as UnderstandingServiceDependencies['connectorData'],+ generator: {+ generateObject:+ generateObject as UnderstandingServiceDependencies['generator']['generateObject'],+ },+ ids: () => 'session-new',+ messages,+ persona: { getLatestPersonaDocument: vi.fn(async () => null) },+ providers,+ repository,+ sourceStore: sourceStoreFactory,+ topic: {+ assertActiveOnboardingTopic: vi.fn(),+ },+ userId: 'user-1',+ writerAgent,+ };++ return {+ dependencies,+ githubCollect,+ generateObject,+ listAvailableProviderIds,+ messages,+ repository,+ service: new UnderstandingService(dependencies),+ setLatestAssistant: (value: typeof latestAssistant) => (latestAssistant = value),+ setAssistantMetadata: (id: string, value: OnboardingUnderstandingMessageMetadata) =>+ assistantMetadata.set(id, value),+ setProvider: (providerId: string, provider: UnderstandingProvider) =>+ providers.set(providerId, provider),+ setSession: (value: OnboardingUnderstandingSession) => (session = value),+ sourceStore,+ sourceStoreFactory,+ stored,+ writerAgent,+ };+};diff --git a/apps/server/src/services/understanding/service/types.ts b/apps/server/src/services/understanding/service/types.tsnew file mode 100644index 00000000000..41f1e20041a--- /dev/null+++ b/apps/server/src/services/understanding/service/types.ts@@ -0,0 +1,80 @@+import type { OnboardingUnderstandingRepository } from '@lobechat/database';++import type { AiGenerationService } from '@/server/services/aiGeneration';+import type { ConnectorDataService } from '@/server/services/connectorData';++import type { UnderstandingSourceStore } from '../sourceStore';+import type { UnderstandingProvider } from '../types';++export interface ProviderOperationInput {+ providerId: string;+ revision: number;+ sessionId: string;+ topicId: string;+}++export interface ProcessCollectedInput {+ expectedSourceFingerprint: string;+ responseLanguage: string;+ sessionId: string;+ topicId: string;+}++export type UnderstandingRepository = Pick<+ OnboardingUnderstandingRepository,+ | 'commitWriting'+ | 'commitDetailedWriting'+ | 'completeProvider'+ | 'confirm'+ | 'expireProviderContexts'+ | 'extend'+ | 'failProvider'+ | 'failWriting'+ | 'failDetailedWriting'+ | 'get'+ | 'initialize'+ | 'markProviderRunning'+ | 'prepareWriting'+>;++export type UnderstandingContexts = Pick<UnderstandingSourceStore, 'get' | 'put'>;++export interface UnderstandingServiceDependencies {+ connectorData: ConnectorDataService;+ generator: Pick<AiGenerationService, 'generateObject'>;+ ids: () => string;+ messages: {+ create: (params: {+ agentId: string;+ content: string;+ model: string;+ provider: string;+ role: 'assistant';+ threadId: string;+ topicId: string;+ }) => Promise<{ id: string }>;+ findById: (id: string) => Promise<{ content?: unknown; metadata?: unknown } | null | undefined>;+ findLatestAssistantMessageByThread: (input: {+ agentId: string;+ threadId: string;+ topicId: string;+ }) => Promise<+ | { content?: unknown; error?: unknown; id: string; role: string; threadId?: string | null }+ | null+ | undefined+ >;+ };+ persona: {+ getLatestPersonaDocument: () => Promise<+ { persona?: string | null; tagline?: string | null } | null | undefined+ >;+ };+ providers: ReadonlyMap<string, UnderstandingProvider>;+ repository: UnderstandingRepository;+ sourceStore: () => UnderstandingContexts;+ topic: {+ assertActiveOnboardingTopic: (topicId: string) => Promise<void>;+ };+ userId: string;+ writerAgent: () => Promise<{ id: string; model: string; provider: string }>;+}diff --git a/apps/server/src/services/understanding/service/utils.ts b/apps/server/src/services/understanding/service/utils.tsnew file mode 100644index 00000000000..f135adba0a5--- /dev/null+++ b/apps/server/src/services/understanding/service/utils.ts@@ -0,0 +1,101 @@+import type { CollectionDiagnostics, CollectionError } from '@lobechat/types';+import {+ MAX_COLLECTION_COUNT,+ MAX_COLLECTION_ERRORS,+ OnboardingUnderstandingMessageMetadataSchema,+} from '@lobechat/types';+import { isPlainRecord } from '@lobechat/utils/object';++import type { StoredUnderstandingProviderContext } from '../sourceStore';+import { UnderstandingProviderContextUnavailableError } from './errors';++const BASELINE_MAX_LENGTH = 8_000;+const MAX_AGENT_INPUT_LENGTH = 128_000;++export const boundedCount = (value: number) =>+ Number.isFinite(value) ? Math.min(MAX_COLLECTION_COUNT, Math.max(0, Math.floor(value))) : 0;++/**+ * Bounds provider diagnostic counts without changing their error content.+ *+ * Use when:+ * - Moving provider collection diagnostics across the service boundary+ *+ * Expects:+ * - Providers return serializable CollectionError values+ *+ * Returns:+ * - Bounded counts and error cardinality with original diagnostics preserved+ */+export const boundProviderDiagnostics = (value: CollectionDiagnostics): CollectionDiagnostics => ({+ errors: value.errors.slice(0, MAX_COLLECTION_ERRORS),+ evidenceCount: boundedCount(value.evidenceCount),+ failedCount: boundedCount(value.failedCount),+ succeededCount: boundedCount(value.succeededCount),+});++/**+ * Creates one structured collection error while retaining its original message.+ *+ * Use when:+ * - Converting a structured internal or Connector Data error for persistence+ *+ * Expects:+ * - Provider, operation, and code are supplied by trusted internal code+ *+ * Returns:+ * - A collection error containing the supplied message without replacement+ */+export const createCollectionError = (+ provider: string,+ operation: string,+ code: string,+ retryable: boolean,+ message = `${provider} ${operation} failed`,+): CollectionError => ({ code, message, operation, provider, retryable });++export const buildEphemeralDocument = (+ contexts: StoredUnderstandingProviderContext[],+ baseline?: { persona?: string | null; tagline?: string | null } | null,+) => {+ const baselineContent = [baseline?.tagline, baseline?.persona]+ .filter((value): value is string => Boolean(value?.trim()))+ .join('\n\n')+ .slice(0, BASELINE_MAX_LENGTH);+ const baselineSection = baselineContent+ ? `<current-persona-baseline>\n${baselineContent}\n</current-persona-baseline>\n\n`+ : '';+ const delimiters = contexts.map(({ providerId, revision }) => ({+ close: '\n</provider-context>',+ open: `<provider-context provider="${providerId}" revision="${revision}">\n`,+ }));+ const structuralLength =+ baselineSection.length ++ Math.max(0, contexts.length - 1) * 2 ++ delimiters.reduce(+ (total, delimiter) => total + delimiter.open.length + delimiter.close.length,+ 0,+ );+ if (structuralLength > MAX_AGENT_INPUT_LENGTH) {+ throw new UnderstandingProviderContextUnavailableError();+ }+ let remainingContent = MAX_AGENT_INPUT_LENGTH - structuralLength;+ const providerSections = contexts.map(({ context }, index) => {+ const remainingProviders = contexts.length - index;+ const content = context.slice(0, Math.floor(remainingContent / remainingProviders));+ remainingContent -= content.length;+ return `${delimiters[index].open}${content}${delimiters[index].close}`;+ });+ return `${baselineSection}${providerSections.join('\n\n')}`;+};++export const storedProposal = (metadata: unknown) => {+ if (!isPlainRecord(metadata)) return;+ const parsed = OnboardingUnderstandingMessageMetadataSchema.safeParse(+ metadata.onboardingUnderstanding,+ );+ return parsed.success ? parsed.data : undefined;+};++/** Concurrency cap for per-provider source-store reads and session writes. */+export const PROVIDER_IO_CONCURRENCY = 5;diff --git a/apps/server/src/services/understanding/service/writing.ts b/apps/server/src/services/understanding/service/writing.tsnew file mode 100644index 00000000000..f815c48d9a5--- /dev/null+++ b/apps/server/src/services/understanding/service/writing.ts@@ -0,0 +1,349 @@+import { createHash } from 'node:crypto';++import { TRACING_SCENARIOS } from '@lobechat/const';+import {+ getUnderstandingSourceFingerprint,+ StaleUnderstandingRevisionError,+ StaleUnderstandingSessionError,+} from '@lobechat/database';+import { observeOnboardingUnderstandingOperation } from '@lobechat/observability-otel/modules/onboarding-understanding';+import {+ chainUnderstandingPersona,+ UNDERSTANDING_ANALYSIS_JSON_SCHEMA,+ UNDERSTANDING_ANALYSIS_PROMPT_VERSION,+} from '@lobechat/prompts';+import type {+ CollectionDiagnostics,+ OnboardingUnderstandingSession,+ UnderstandingFeedbackTurn,+} from '@lobechat/types';+import {+ MAX_COLLECTION_ERRORS,+ OnboardingUnderstandingMessageMetadataSchema,+ RequestTrigger,+ UnderstandingAnalysisSchema,+} from '@lobechat/types';+import pMap from 'p-map';++import type { StoredUnderstandingProviderContext } from '../sourceStore';+import { readActiveSession } from './session';+import type { ProcessCollectedInput, UnderstandingServiceDependencies } from './types';+import {+ boundProviderDiagnostics,+ buildEphemeralDocument,+ createCollectionError,+ PROVIDER_IO_CONCURRENCY,+} from './utils';++const parseStoredAnalysis = (content: unknown) => {+ if (typeof content !== 'string') return;+ try {+ const parsed = UnderstandingAnalysisSchema.safeParse(JSON.parse(content));+ return parsed.success ? parsed.data : undefined;+ } catch {+ return;+ }+};++const writingThreadId = (sessionId: string, sourceFingerprint: string, feedbackRevision: number) =>+ `thd_${createHash('sha256')+ .update(sessionId)+ .update('\0')+ .update(sourceFingerprint)+ .update('\0')+ .update(String(feedbackRevision))+ .digest('hex')+ .slice(0, 24)}`;++const sumDiagnostics = (+ session: OnboardingUnderstandingSession,+ contexts: StoredUnderstandingProviderContext[],+): CollectionDiagnostics => {+ const terminalSources = Object.values(session.sources).filter(+ ({ status }) => status === 'completed' || status === 'failed',+ );+ return boundProviderDiagnostics({+ errors: terminalSources.flatMap(({ errors }) => errors).slice(-MAX_COLLECTION_ERRORS),+ evidenceCount: contexts.reduce(+ (total, { diagnostics }) => total + diagnostics.evidenceCount,+ 0,+ ),+ failedCount: terminalSources.reduce((total, source) => total + source.failedCount, 0),+ succeededCount: terminalSources.reduce((total, source) => total + source.succeededCount, 0),+ });+};++export const processCollected = async (+ dependencies: UnderstandingServiceDependencies,+ { expectedSourceFingerprint, responseLanguage, sessionId, topicId }: ProcessCollectedInput,+) =>+ observeOnboardingUnderstandingOperation(+ { operation: 'writer.process', sessionId, topicId },+ async () => {+ const operationAttributes = { sessionId, topicId };+ const session = await observeOnboardingUnderstandingOperation(+ { ...operationAttributes, operation: 'session.read' },+ () => readActiveSession(dependencies, topicId, sessionId),+ );+ const feedback = session.feedback ?? { revision: 0, turns: [] };+ if (getUnderstandingSourceFingerprint(session) !== expectedSourceFingerprint) {+ return { published: false as const, sourceFingerprint: expectedSourceFingerprint };+ }+ if (+ session.writing?.sourceFingerprint === expectedSourceFingerprint &&+ (session.writing.feedbackRevision ?? 0) === feedback.revision &&+ session.writing.status === 'completed'+ ) {+ return {+ feedbackRevision: session.writing.feedbackRevision ?? 0,+ generationRevision: session.writing.generationRevision ?? 0,+ published: true as const,+ resultId: session.writing.resultMessageId,+ sourceFingerprint: expectedSourceFingerprint,+ };+ }++ const completed = Object.entries(session.sources)+ .filter(([, state]) => state.status === 'completed')+ .sort(([left], [right]) => left.localeCompare(right));+ const sourceStore = dependencies.sourceStore();+ const contexts = await observeOnboardingUnderstandingOperation(+ { ...operationAttributes, operation: 'writer.read-contexts' },+ () =>+ pMap(+ completed,+ ([providerId, state]) =>+ sourceStore.get({+ providerId,+ revision: state.revision,+ sessionId,+ userId: dependencies.userId,+ }),+ { concurrency: PROVIDER_IO_CONCURRENCY },+ ),+ );+ const missing = completed.flatMap(([providerId, state], index) =>+ contexts[index] ? [] : [{ providerId, revision: state.revision }],+ );+ if (missing.length > 0) {+ await dependencies.repository.expireProviderContexts({+ providers: missing,+ sessionId,+ sourceFingerprint: expectedSourceFingerprint,+ topicId,+ });+ return { published: false as const, sourceFingerprint: expectedSourceFingerprint };+ }++ const sourceContexts = contexts as StoredUnderstandingProviderContext[];+ const threadId = writingThreadId(sessionId, expectedSourceFingerprint, feedback.revision);+ const writerAgent = await observeOnboardingUnderstandingOperation(+ { ...operationAttributes, operation: 'writer.resolve-agent' },+ () => dependencies.writerAgent(),+ );+ const prepared = await observeOnboardingUnderstandingOperation(+ { ...operationAttributes, operation: 'writer.prepare' },+ () =>+ dependencies.repository.prepareWriting({+ agentId: writerAgent.id,+ expectedFeedbackRevision: feedback.revision,+ sessionId,+ sourceFingerprint: expectedSourceFingerprint,+ threadId,+ topicId,+ }),+ );+ if (!prepared.ready) {+ return { published: false as const, sourceFingerprint: expectedSourceFingerprint };+ }++ const providers = sourceContexts.map(({ providerId }) => providerId);+ const diagnostics = sumDiagnostics(session, sourceContexts);+ const writerResult = await runWriter(dependencies, {+ contexts: sourceContexts,+ diagnostics,+ feedback: feedback.turns,+ providers,+ responseLanguage,+ sessionId,+ threadId,+ topicId,+ writerAgent,+ });+ const metadata = OnboardingUnderstandingMessageMetadataSchema.parse({+ analysis: writerResult.analysis,+ diagnostics,+ feedbackRevision: prepared.feedbackRevision,+ generationRevision: prepared.generationRevision,+ kind: 'proposal',+ providers,+ resultId: writerResult.assistantMessageId,+ sourceFingerprint: expectedSourceFingerprint,+ });+ const committed = await observeOnboardingUnderstandingOperation(+ { ...operationAttributes, operation: 'writer.commit' },+ () =>+ dependencies.repository.commitWriting({+ assistantMessageId: writerResult.assistantMessageId,+ feedbackRevision: prepared.feedbackRevision,+ generationRevision: prepared.generationRevision,+ metadata,+ sessionId,+ sourceFingerprint: expectedSourceFingerprint,+ threadId,+ topicId,+ }),+ );+ if (!committed.published) {+ return { published: false as const, sourceFingerprint: expectedSourceFingerprint };+ }+ return {+ feedbackRevision: prepared.feedbackRevision,+ generationRevision: prepared.generationRevision,+ ...(committed.personaVersion === undefined+ ? {}+ : { personaVersion: committed.personaVersion }),+ published: true as const,+ resultId: writerResult.assistantMessageId,+ sourceFingerprint: expectedSourceFingerprint,+ };+ },+ );++export const failWriting = async (+ dependencies: UnderstandingServiceDependencies,+ {+ sessionId,+ sourceFingerprint,+ topicId,+ }: {+ sessionId: string;+ sourceFingerprint: string;+ topicId: string;+ },+) => {+ try {+ const current = await readActiveSession(dependencies, topicId, sessionId);+ if (current.writing && current.writing.sourceFingerprint !== sourceFingerprint) return;+ const session = await dependencies.repository.failWriting({+ error: createCollectionError(+ 'understanding',+ 'writing',+ 'UNDERSTANDING_WRITING_FAILED',+ true,+ ),+ feedbackRevision: current.writing?.feedbackRevision ?? current.feedback?.revision ?? 0,+ generationRevision: current.writing?.generationRevision ?? current.generationRevision ?? 0,+ sessionId,+ sourceFingerprint,+ topicId,+ });+ return session.writing?.sourceFingerprint === sourceFingerprint &&+ session.writing.status === 'failed'+ ? session+ : undefined;+ } catch (error) {+ if (+ error instanceof StaleUnderstandingRevisionError ||+ error instanceof StaleUnderstandingSessionError+ ) {+ return;+ }+ throw error;+ }+};++const runWriter = async (+ dependencies: UnderstandingServiceDependencies,+ {+ contexts,+ diagnostics,+ feedback,+ providers,+ responseLanguage,+ sessionId,+ threadId,+ topicId,+ writerAgent,+ }: {+ contexts: StoredUnderstandingProviderContext[];+ diagnostics: CollectionDiagnostics;+ feedback: UnderstandingFeedbackTurn[];+ providers: string[];+ responseLanguage: string;+ sessionId: string;+ threadId: string;+ topicId: string;+ writerAgent: { id: string; model: string; provider: string };+ },+) =>+ observeOnboardingUnderstandingOperation(+ { operation: 'writer.generate', sessionId, topicId },+ async () => {+ const operationAttributes = { sessionId, topicId };+ const existing = await observeOnboardingUnderstandingOperation(+ { ...operationAttributes, operation: 'writer.read-existing' },+ () =>+ dependencies.messages.findLatestAssistantMessageByThread({+ agentId: writerAgent.id,+ threadId,+ topicId,+ }),+ );+ if (existing && !existing.error) {+ const analysis = parseStoredAnalysis(existing.content);+ if (analysis) return { analysis, assistantMessageId: existing.id };+ }++ const baseline = await observeOnboardingUnderstandingOperation(+ { ...operationAttributes, operation: 'writer.read-baseline' },+ () => dependencies.persona.getLatestPersonaDocument(),+ );+ const analysis = UnderstandingAnalysisSchema.parse(+ await observeOnboardingUnderstandingOperation(+ { ...operationAttributes, operation: 'generation.runtime-call' },+ () =>+ dependencies.generator.generateObject(+ {+ ...chainUnderstandingPersona({+ context: buildEphemeralDocument(contexts, baseline),+ diagnostics,+ feedback,+ providers,+ responseLanguage,+ }),+ model: writerAgent.model,+ provider: writerAgent.provider,+ schema: UNDERSTANDING_ANALYSIS_JSON_SCHEMA,+ thinking: { type: 'disabled' },+ },+ {+ metadata: { trigger: RequestTrigger.Onboarding },+ tracing: {+ promptVersion: UNDERSTANDING_ANALYSIS_PROMPT_VERSION,+ scenario: TRACING_SCENARIOS.UnderstandingAnalysis,+ schemaName: UNDERSTANDING_ANALYSIS_JSON_SCHEMA.name,+ },+ },+ ),+ ),+ );+ const message = await observeOnboardingUnderstandingOperation(+ { ...operationAttributes, operation: 'writer.create-message' },+ () =>+ dependencies.messages.create({+ agentId: writerAgent.id,+ content: JSON.stringify(analysis),+ model: writerAgent.model,+ provider: writerAgent.provider,+ role: 'assistant',+ threadId,+ topicId,+ }),+ );+ return {+ analysis,+ assistantMessageId: message.id,+ };+ },+ );