🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat: trace onboarding understanding workflows (#18191)
Neko083e231a9e9b
diff --git a/apps/server/src/services/understanding/service.test.ts b/apps/server/src/services/understanding/service.test.tsindex 5c2e80a238f..cfe04999f48 100644--- a/apps/server/src/services/understanding/service.test.ts+++ b/apps/server/src/services/understanding/service.test.ts@@ -345,6 +345,7 @@ describe('UnderstandingService', () => {providers: [{ id: 'gmail', revision: 1 }],responseLanguage: 'zh-CN',sessionId: 'session-1',+ startedAt: expect.any(Number),topicId: 'topic-1',userId: 'user-1',},@@ -357,6 +358,7 @@ describe('UnderstandingService', () => {responseLanguage: 'zh-CN',sessionId: 'session-1',sourceFingerprint: 'github@1',+ startedAt: expect.any(Number),topicId: 'topic-1',userId: 'user-1',},@@ -420,6 +422,7 @@ describe('UnderstandingService', () => {],responseLanguage: 'zh-CN',sessionId: 'session-new',+ startedAt: expect.any(Number),topicId: 'topic-1',userId: 'user-1',},diff --git a/apps/server/src/services/understanding/service.ts b/apps/server/src/services/understanding/service.tsindex 4c46cdaae3e..1f49d379120 100644--- a/apps/server/src/services/understanding/service.ts+++ b/apps/server/src/services/understanding/service.ts@@ -11,6 +11,7 @@ import {UnderstandingResourceNotFoundError,UnderstandingSessionNotFoundError,} from '@lobechat/database';+import { observeOnboardingUnderstandingOperation } from '@lobechat/observability-otel/modules/onboarding-understanding';import {chainUnderstandingDetailedPersona,chainUnderstandingPersona,@@ -255,22 +256,40 @@ export class UnderstandingService {private initialize = async (topicId: string,selectedProviderIds?: string[],- ): Promise<OnboardingUnderstandingSession> => {- await this.dependencies.topic.assertActiveOnboardingTopic(topicId);- const current = await 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 this.listSourceProviderIds());- const providerIds = requestedProviderIds.filter((providerId) =>- availableProviderIds.has(providerId),- );- return this.dependencies.repository.initialize(topicId, this.dependencies.ids(), providerIds);- };+ ): 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,@@ -278,28 +297,40 @@ export class UnderstandingService {selectedProviderIds?: string[],options: UnderstandingStartOptions = {},): Promise<OnboardingUnderstandingPollingResult> => {- 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 OnboardingUnderstandingWorkflow.triggerProviders(- {- providers,- responseLanguage,- sessionId: session.id,- triggerTaskRecommendations: options.triggerTaskRecommendations,- topicId,- userId: this.dependencies.userId,- },- { workflowRunId: `onboarding-understanding-initial-${session.id}` },- );- }- return this.get(topicId);+ 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 (@@ -376,6 +407,7 @@ export class UnderstandingService {providers: providerAttempts,responseLanguage: input.responseLanguage,sessionId: input.sessionId,+ startedAt: Date.now(),topicId: input.topicId,userId: this.dependencies.userId,},@@ -392,6 +424,7 @@ export class UnderstandingService {sessionId: input.sessionId,responseLanguage: input.responseLanguage,sourceFingerprint,+ startedAt: Date.now(),topicId: input.topicId,userId: this.dependencies.userId,},@@ -461,6 +494,7 @@ export class UnderstandingService {providers: [{ id: input.providerId, revision }],responseLanguage: input.responseLanguage,sessionId: input.sessionId,+ startedAt: Date.now(),topicId: input.topicId,userId: this.dependencies.userId,},@@ -481,123 +515,156 @@ export class UnderstandingService {return this.get(input.topicId);};- processProvider = async (input: ProviderOperationInput) => {- const session = await 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({+ processProvider = async (input: ProviderOperationInput) =>+ observeOnboardingUnderstandingOperation(+ {+ operation: 'provider.process',providerId: input.providerId,- revision: input.revision,sessionId: input.sessionId,- userId: this.dependencies.userId,- });- if (stored) {- return {- failedCount: stored.diagnostics.failedCount,+ topicId: input.topicId,+ },+ async () => {+ const operationAttributes = {providerId: input.providerId,- revision: input.revision,- sourceCount: stored.sourceCount,- sourceFingerprint,- status: 'completed' as const,- succeededCount: stored.diagnostics.succeededCount,+ sessionId: input.sessionId,+ topicId: input.topicId,};- }- 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,+ 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,- sourceCount: 0,- status: 'failed' as const,- succeededCount: expiredState.succeededCount,+ 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,+ };}- : stale();- }+ 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 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();- }+ 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 collected;- try {- collected = await provider.collect({- connectorData: this.dependencies.connectorData,- userId: this.dependencies.userId,- });- } catch (error) {- if (!(error instanceof ConnectorDataError) || error.retryable) throw error;- return this.recordProviderFailure(input, 0);- }+ let collected;+ try {+ collected = await observeOnboardingUnderstandingOperation(+ { ...operationAttributes, operation: 'provider.collect' },+ () =>+ provider.collect({+ connectorData: this.dependencies.connectorData,+ userId: this.dependencies.userId,+ }),+ );+ } catch (error) {+ if (!(error instanceof ConnectorDataError) || error.retryable) throw error;+ return this.recordProviderFailure(input, 0);+ }- const context = collected.context.trim().slice(0, MAX_SOURCE_BRIEF_LENGTH);- const diagnostics = sanitizeProviderDiagnostics(input.providerId, collected.diagnostics);- const usable =- Boolean(context) &&- collected.sourceCount > 0 &&- diagnostics.evidenceCount > 0 &&- diagnostics.succeededCount > 0;- if (!usable) return this.recordProviderFailure(input, diagnostics.succeededCount, diagnostics);+ const context = collected.context.trim().slice(0, MAX_SOURCE_BRIEF_LENGTH);+ const diagnostics = sanitizeProviderDiagnostics(input.providerId, collected.diagnostics);+ const usable =+ Boolean(context) &&+ collected.sourceCount > 0 &&+ diagnostics.evidenceCount > 0 &&+ diagnostics.succeededCount > 0;+ if (!usable)+ return this.recordProviderFailure(input, diagnostics.succeededCount, diagnostics);- const stored = {- context,- diagnostics,- providerId: input.providerId,- revision: input.revision,- sessionId: input.sessionId,- sourceCount: collected.sourceCount,- userId: this.dependencies.userId,- };- await this.dependencies.sourceStore().put(stored);- const transition = await 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: collected.sourceCount,- sourceFingerprint,- status: 'completed' as const,- succeededCount: diagnostics.succeededCount,- };- };+ const stored = {+ context,+ diagnostics,+ providerId: input.providerId,+ revision: input.revision,+ sessionId: input.sessionId,+ sourceCount: collected.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: collected.sourceCount,+ sourceFingerprint,+ status: 'completed' as const,+ succeededCount: diagnostics.succeededCount,+ };+ },+ );failProvider = async (input: ProviderOperationInput) => {try {@@ -633,114 +700,138 @@ export class UnderstandingService {responseLanguage,sessionId,topicId,- }: ProcessCollectedInput) => {- const session = await 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,- };- }+ }: 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 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 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 this.dependencies.writerAgent();- const prepared = await 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 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,- 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 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,- };- };+ 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,@@ -787,91 +878,124 @@ export class UnderstandingService {responseLanguage,sessionId,topicId,- }: ProcessCollectedInput) => {- const session = await 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 };- }+ }: 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 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 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 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 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 this.dependencies.persona.getLatestPersonaDocument();- const writerAgent = await this.dependencies.writerAgent();- const detailedPersona: UnderstandingPersonaProposal = UnderstandingPersonaProposalSchema.parse(- await this.dependencies.generator.generateObject(- {- messages: [- {- content: chainUnderstandingDetailedPersona({- analysis: proposal.analysis,- responseLanguage,- }),- role: 'system',- },- {- content: [- 'Write the complete persona from the original collected provider contexts.',- buildEphemeralDocument(contexts as StoredUnderstandingProviderContext[], baseline),- ].join('\n\n'),- role: 'user',- },- ],- model: writerAgent.model,- provider: writerAgent.provider,- schema: UNDERSTANDING_DETAILED_PERSONA_JSON_SCHEMA,- thinking: { type: 'disabled' },- },- { metadata: { trigger: RequestTrigger.Onboarding } },- ),+ 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(+ {+ messages: [+ {+ content: chainUnderstandingDetailedPersona({+ analysis: proposal.analysis,+ responseLanguage,+ }),+ role: 'system',+ },+ {+ content: [+ 'Write the complete persona from the original collected provider contexts.',+ buildEphemeralDocument(+ contexts as StoredUnderstandingProviderContext[],+ baseline,+ ),+ ].join('\n\n'),+ role: 'user',+ },+ ],+ model: writerAgent.model,+ provider: writerAgent.provider,+ schema: UNDERSTANDING_DETAILED_PERSONA_JSON_SCHEMA,+ thinking: { type: 'disabled' },+ },+ { metadata: { trigger: RequestTrigger.Onboarding } },+ ),+ ),+ );+ 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 };+ },);- const committed = await this.dependencies.repository.commitDetailedWriting({- detailedPersona,- feedbackRevision: writing.feedbackRevision ?? 0,- generationRevision: writing.generationRevision ?? 0,- sessionId,- sourceFingerprint: expectedSourceFingerprint,- topicId,- });- return { ...committed, sourceFingerprint: expectedSourceFingerprint };- };failDetailedPersona = async ({sessionId,@@ -967,6 +1091,7 @@ export class UnderstandingService {feedback,providers,responseLanguage,+ sessionId,threadId,topicId,writerAgent,@@ -976,64 +1101,85 @@ export class UnderstandingService {feedback: UnderstandingFeedbackTurn[];providers: string[];responseLanguage: string;+ sessionId: string;threadId: string;topicId: string;writerAgent: { id: string; model: string; provider: string };- }) => {- const existing = await 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 };- }+ }) =>+ 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 this.dependencies.persona.getLatestPersonaDocument();- const analysis = UnderstandingAnalysisSchema.parse(- await this.dependencies.generator.generateObject(- {- messages: [- {- content: chainUnderstandingPersona({- diagnostics,- feedback,- providers,- responseLanguage,- }),- role: 'system',- },- {- content: [- 'Write onboarding persona from collected provider contexts.',- buildEphemeralDocument(contexts, baseline),- ].join('\n\n'),- role: 'user',- },- ],- model: writerAgent.model,- provider: writerAgent.provider,- schema: UNDERSTANDING_ANALYSIS_JSON_SCHEMA,- thinking: { type: 'disabled' },- },- { metadata: { trigger: RequestTrigger.Onboarding } },- ),+ 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(+ {+ messages: [+ {+ content: chainUnderstandingPersona({+ diagnostics,+ feedback,+ providers,+ responseLanguage,+ }),+ role: 'system',+ },+ {+ content: [+ 'Write onboarding persona from collected provider contexts.',+ buildEphemeralDocument(contexts, baseline),+ ].join('\n\n'),+ role: 'user',+ },+ ],+ model: writerAgent.model,+ provider: writerAgent.provider,+ schema: UNDERSTANDING_ANALYSIS_JSON_SCHEMA,+ thinking: { type: 'disabled' },+ },+ { metadata: { trigger: RequestTrigger.Onboarding } },+ ),+ ),+ );+ 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,+ };+ },);- const message = await 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 {diff --git a/apps/server/src/workflows/onboardingUnderstanding/observability.ts b/apps/server/src/workflows/onboardingUnderstanding/observability.tsnew file mode 100644index 00000000000..92da945a2e7--- /dev/null+++ b/apps/server/src/workflows/onboardingUnderstanding/observability.ts@@ -0,0 +1,57 @@+import { context as otContext } from '@lobechat/observability-otel/api';+import {+ observeOnboardingUnderstandingOperation,+ type OnboardingUnderstandingOperationAttributes,+} from '@lobechat/observability-otel/modules/onboarding-understanding';++import { extractTraceContext, injectActiveTraceHeaders } from '@/libs/observability/traceparent';++interface WorkflowTraceContext {+ headers?: Headers;+}++/**+ * Restores QStash trace context and observes one Understanding workflow delivery.+ *+ * Use when:+ * - Entering an onboarding Understanding Hono workflow handler+ *+ * Expects:+ * - QStash request headers are available when the delivery carries `traceparent`+ *+ * Returns:+ * - The workflow callback result under the restored distributed trace+ */+export const observeOnboardingUnderstandingWorkflow = async <Result>(+ context: WorkflowTraceContext,+ attributes: OnboardingUnderstandingOperationAttributes,+ operation: () => Promise<Result>,+): Promise<Result> => {+ // NOTICE:+ // Hono workflow routes bypass the backend middleware that normally extracts traceparent.+ // QStash forwards trigger headers, but the workflow handler must restore them before spans open.+ // Source/context: `apps/server/src/workflows/agentSignal/run.ts` uses the same extraction boundary.+ // Removal condition: a shared Hono workflow middleware guarantees trace-context extraction.+ const traceContext = context.headers ? extractTraceContext(context.headers) : otContext.active();+ return otContext.with(traceContext, () =>+ observeOnboardingUnderstandingOperation(attributes, operation),+ );+};++/**+ * Serializes the active trace context for an invoked child workflow.+ *+ * Use when:+ * - Calling `WorkflowContext.invoke` from an active Understanding workflow span+ *+ * Expects:+ * - An active span exists when distributed trace continuity is required+ *+ * Returns:+ * - Headers suitable for the Upstash Workflow invoke options+ */+export const getOnboardingUnderstandingTraceHeaders = (): Record<string, string> => {+ const headers = new Headers();+ injectActiveTraceHeaders(headers);+ return Object.fromEntries(headers.entries());+};diff --git a/apps/server/src/workflows/onboardingUnderstanding/processCollected.ts b/apps/server/src/workflows/onboardingUnderstanding/processCollected.tsindex cca346cbdd1..d599fec0d6b 100644--- a/apps/server/src/workflows/onboardingUnderstanding/processCollected.ts+++ b/apps/server/src/workflows/onboardingUnderstanding/processCollected.ts@@ -6,6 +6,7 @@ import {UnderstandingResourceNotFoundError,UnderstandingSessionNotFoundError,} from '@lobechat/database';+import { observeOnboardingUnderstandingOperation } from '@lobechat/observability-otel/modules/onboarding-understanding';import type { PublicServeOptions, WorkflowContext } from '@upstash/workflow';import { getServerDB } from '@/database/server';@@ -16,6 +17,7 @@ import {} from '@/server/services/understanding/service';import { runStep } from '@/server/workflows/step';+import { observeOnboardingUnderstandingWorkflow } from './observability';import {type ProcessCollectedUnderstandingPayload,ProcessCollectedUnderstandingPayloadSchema,@@ -29,7 +31,8 @@ type CollectedService = Pick<type CollectedWorkflowContext = Pick<WorkflowContext<ProcessCollectedUnderstandingPayload>,'requestPayload' | 'run'->;+> &+ Partial<Pick<WorkflowContext<ProcessCollectedUnderstandingPayload>, 'headers'>>;interface CollectedWorkflowDependencies {createService?: (userId: string) => Promise<CollectedService>;@@ -48,46 +51,82 @@ const isStaleSession = (error: unknown) =>error instanceof StaleUnderstandingRevisionError ||error instanceof StaleUnderstandingSessionError;+/**+ * Writes the quick Understanding proposal and starts detailed persona generation.+ *+ * Use when:+ * - A provider workflow has committed a new source fingerprint+ *+ * Expects:+ * - A fingerprint-scoped payload owned by the onboarding user+ *+ * Returns:+ * - Whether the quick proposal was published for the requested fingerprint+ *+ * Call stack:+ *+ * processCollectedWorkflow+ * -> {@link processCollectedUnderstanding}+ * -> UnderstandingService.processCollected+ * -> OnboardingUnderstandingWorkflow.triggerDetailedPersona+ */export const processCollectedUnderstanding = async (context: CollectedWorkflowContext,dependencies: CollectedWorkflowDependencies = {},) => {const payload = ProcessCollectedUnderstandingPayloadSchema.parse(context.requestPayload);- const service = await (dependencies.createService ?? createService)(payload.userId);- const result = await runStep(context, 'collected:process', async () => {- try {- return await service.processCollected({- expectedSourceFingerprint: payload.sourceFingerprint,- responseLanguage: payload.responseLanguage,- sessionId: payload.sessionId,- topicId: payload.topicId,+ return observeOnboardingUnderstandingWorkflow(+ context,+ {+ operation: 'workflow.collected',+ sessionId: payload.sessionId,+ topicId: payload.topicId,+ },+ async () => {+ const service = await (dependencies.createService ?? createService)(payload.userId);+ const result = await runStep(context, 'collected:process', async () => {+ try {+ return await service.processCollected({+ expectedSourceFingerprint: payload.sourceFingerprint,+ responseLanguage: payload.responseLanguage,+ sessionId: payload.sessionId,+ topicId: payload.topicId,+ });+ } catch (error) {+ if (isStaleSession(error)) {+ return { published: false as const, sourceFingerprint: payload.sourceFingerprint };+ }+ throw error;+ }});- } catch (error) {- if (isStaleSession(error)) {- return { published: false as const, sourceFingerprint: payload.sourceFingerprint };+ await observeOnboardingUnderstandingOperation(+ {+ operation: 'progress.publish',+ sessionId: payload.sessionId,+ topicId: payload.topicId,+ },+ () => publishOnboardingGenerationProgress(payload.userId, payload.topicId),+ );+ const triggerDetailedPersona = dependencies.triggerDetailedPersona;+ if (result.published && triggerDetailedPersona) {+ await runStep(context, 'collected:trigger-detailed-persona', () =>+ triggerDetailedPersona(payload, {+ workflowRunId: `onboarding-understanding-detailed-${createHash('sha256')+ .update(payload.sessionId)+ .update('\0')+ .update(payload.sourceFingerprint)+ .update('\0')+ .update(String(result.generationRevision))+ .update('\0')+ .update(String(result.feedbackRevision))+ .digest('hex')+ .slice(0, 32)}`,+ }),+ );}- throw error;- }- });- await publishOnboardingGenerationProgress(payload.userId, payload.topicId);- const triggerDetailedPersona = dependencies.triggerDetailedPersona;- if (result.published && triggerDetailedPersona) {- await runStep(context, 'collected:trigger-detailed-persona', () =>- triggerDetailedPersona(payload, {- workflowRunId: `onboarding-understanding-detailed-${createHash('sha256')- .update(payload.sessionId)- .update('\0')- .update(payload.sourceFingerprint)- .update('\0')- .update(String(result.generationRevision))- .update('\0')- .update(String(result.feedbackRevision))- .digest('hex')- .slice(0, 32)}`,- }),- );- }- return result;+ return result;+ },+ );};export const failRunningUnderstandingWriting = async (diff --git a/apps/server/src/workflows/onboardingUnderstanding/processDetailedPersona.test.ts b/apps/server/src/workflows/onboardingUnderstanding/processDetailedPersona.test.tsindex 2cf82aa88c5..f017156573e 100644--- a/apps/server/src/workflows/onboardingUnderstanding/processDetailedPersona.test.ts+++ b/apps/server/src/workflows/onboardingUnderstanding/processDetailedPersona.test.ts@@ -8,6 +8,10 @@ import {processDetailedUnderstandingPersona,} from './processDetailedPersona';+const telemetry = vi.hoisted(() => ({+ recordSessionDuration: vi.fn(),+}));+const errors = vi.hoisted(() => {class DomainError extends Error {}return { DomainError };@@ -23,11 +27,19 @@ vi.mock('@/database/server', () => ({ getServerDB: vi.fn() }));vi.mock('@/server/services/understanding/service', () => ({createUnderstandingService: vi.fn(),}));+vi.mock('@lobechat/observability-otel/modules/onboarding-understanding', () => ({+ observeOnboardingUnderstandingOperation: async <Result>(+ _attributes: unknown,+ operation: () => Promise<Result>,+ ) => operation(),+ recordOnboardingUnderstandingEndToEndDuration: telemetry.recordSessionDuration,+}));const payload = {responseLanguage: 'zh-CN',sessionId: 'session-1',sourceFingerprint: 'github@1',+ startedAt: 1000,topicId: 'topic-1',userId: 'user-1',};@@ -54,6 +66,8 @@ describe('processDetailedUnderstandingPersona', () => {}),).resolves.toEqual({ published: true, sourceFingerprint: 'github@1' });expect(steps).toEqual(['detailed-persona:process']);+ /** @example expect(recordSessionDuration).toHaveBeenCalledWith(startedAt); */+ expect(telemetry.recordSessionDuration).toHaveBeenCalledWith(1000);});});diff --git a/apps/server/src/workflows/onboardingUnderstanding/processDetailedPersona.ts b/apps/server/src/workflows/onboardingUnderstanding/processDetailedPersona.tsindex fbdf8ffb9d0..402c6ccbe2f 100644--- a/apps/server/src/workflows/onboardingUnderstanding/processDetailedPersona.ts+++ b/apps/server/src/workflows/onboardingUnderstanding/processDetailedPersona.ts@@ -4,6 +4,10 @@ import {UnderstandingResourceNotFoundError,UnderstandingSessionNotFoundError,} from '@lobechat/database';+import {+ observeOnboardingUnderstandingOperation,+ recordOnboardingUnderstandingEndToEndDuration,+} from '@lobechat/observability-otel/modules/onboarding-understanding';import type { PublicServeOptions, WorkflowContext } from '@upstash/workflow';import { getServerDB } from '@/database/server';@@ -14,6 +18,7 @@ import {} from '@/server/services/understanding/service';import { runStep } from '@/server/workflows/step';+import { observeOnboardingUnderstandingWorkflow } from './observability';import {type ProcessCollectedUnderstandingPayload,ProcessCollectedUnderstandingPayloadSchema,@@ -27,7 +32,8 @@ type DetailedPersonaService = Pick<type DetailedPersonaWorkflowContext = Pick<WorkflowContext<ProcessCollectedUnderstandingPayload>,'requestPayload' | 'run'->;+> &+ Partial<Pick<WorkflowContext<ProcessCollectedUnderstandingPayload>, 'headers'>>;interface DetailedPersonaWorkflowDependencies {createService?: (userId: string) => Promise<DetailedPersonaService>;@@ -65,24 +71,45 @@ export const processDetailedUnderstandingPersona = async (dependencies: DetailedPersonaWorkflowDependencies = {},) => {const payload = ProcessCollectedUnderstandingPayloadSchema.parse(context.requestPayload);- const service = await (dependencies.createService ?? createService)(payload.userId);- const result = await runStep(context, 'detailed-persona:process', async () => {- try {- return await service.processDetailedPersona({- expectedSourceFingerprint: payload.sourceFingerprint,- responseLanguage: payload.responseLanguage,- sessionId: payload.sessionId,- topicId: payload.topicId,+ return observeOnboardingUnderstandingWorkflow(+ context,+ {+ operation: 'workflow.detailed-persona',+ sessionId: payload.sessionId,+ topicId: payload.topicId,+ },+ async () => {+ const service = await (dependencies.createService ?? createService)(payload.userId);+ const result = await runStep(context, 'detailed-persona:process', async () => {+ try {+ const result = await service.processDetailedPersona({+ expectedSourceFingerprint: payload.sourceFingerprint,+ responseLanguage: payload.responseLanguage,+ sessionId: payload.sessionId,+ topicId: payload.topicId,+ });+ if (result.published) {+ recordOnboardingUnderstandingEndToEndDuration(payload.startedAt);+ }+ return result;+ } catch (error) {+ if (isStaleSession(error)) {+ return { published: false as const, sourceFingerprint: payload.sourceFingerprint };+ }+ throw error;+ }});- } catch (error) {- if (isStaleSession(error)) {- return { published: false as const, sourceFingerprint: payload.sourceFingerprint };- }- throw error;- }- });- await publishOnboardingGenerationProgress(payload.userId, payload.topicId);- return result;+ await observeOnboardingUnderstandingOperation(+ {+ operation: 'progress.publish',+ sessionId: payload.sessionId,+ topicId: payload.topicId,+ },+ () => publishOnboardingGenerationProgress(payload.userId, payload.topicId),+ );+ return result;+ },+ );};/**diff --git a/apps/server/src/workflows/onboardingUnderstanding/processProviders.test.ts b/apps/server/src/workflows/onboardingUnderstanding/processProviders.test.tsindex a6216cd77f3..099e4c414fe 100644--- a/apps/server/src/workflows/onboardingUnderstanding/processProviders.test.ts+++ b/apps/server/src/workflows/onboardingUnderstanding/processProviders.test.ts@@ -34,6 +34,7 @@ const payload = {],responseLanguage: 'zh-CN',sessionId: 'session-1',+ startedAt: 1000,topicId: 'topic-1',userId: 'user-1',};@@ -93,6 +94,7 @@ describe('processUnderstandingProviders', () => {responseLanguage: 'zh-CN',sessionId: 'session-1',sourceFingerprint: 'github@1',+ startedAt: 1000,topicId: 'topic-1',userId: 'user-1',});diff --git a/apps/server/src/workflows/onboardingUnderstanding/processProviders.ts b/apps/server/src/workflows/onboardingUnderstanding/processProviders.tsindex 960fdea375a..35adeaab264 100644--- a/apps/server/src/workflows/onboardingUnderstanding/processProviders.ts+++ b/apps/server/src/workflows/onboardingUnderstanding/processProviders.ts@@ -5,6 +5,7 @@ import {UnderstandingResourceNotFoundError,UnderstandingSessionNotFoundError,} from '@lobechat/database';+import { observeOnboardingUnderstandingOperation } from '@lobechat/observability-otel/modules/onboarding-understanding';import type { InvokableWorkflow, PublicServeOptions, WorkflowContext } from '@upstash/workflow';import { getServerDB } from '@/database/server';@@ -17,6 +18,10 @@ import type { ProcessOnboardingTaskRecommendationPayload } from '@/server/workflimport { getTaskRecommendationFlowControlKey } from '@/server/workflows/onboardingTaskRecommendation/types';import { runStep } from '@/server/workflows/step';+import {+ getOnboardingUnderstandingTraceHeaders,+ observeOnboardingUnderstandingWorkflow,+} from './observability';import {getUnderstandingWritingFlowControlKey,type ProcessCollectedUnderstandingPayload,@@ -29,7 +34,8 @@ type ProviderService = Pick<UnderstandingService, 'failProvider' | 'processProvitype ProviderWorkflowContext = Pick<WorkflowContext<ProcessUnderstandingProvidersPayload>,'invoke' | 'requestPayload' | 'run'->;+> &+ Partial<Pick<WorkflowContext<ProcessUnderstandingProvidersPayload>, 'headers'>>;interface ProviderWorkflowDependencies {createService?: (userId: string) => Promise<ProviderService>;@@ -71,6 +77,25 @@ const taskRecommendationWorkflowRunId = (sessionId: string, sourceFingerprint: s.digest('hex').slice(0, 32)}`;+/**+ * Collects selected Understanding providers and schedules fingerprint-scoped writers.+ *+ * Use when:+ * - QStash delivers an onboarding Understanding provider workflow+ *+ * Expects:+ * - A validated user, topic, session, and deterministic provider revision list+ *+ * Returns:+ * - The terminal result observed for each provider attempt+ *+ * Call stack:+ *+ * processProvidersWorkflow+ * -> {@link processUnderstandingProviders}+ * -> UnderstandingService.processProvider+ * -> WorkflowContext.invoke(processCollectedWorkflow)+ */export const processUnderstandingProviders = async (context: ProviderWorkflowContext,dependencies: ProviderWorkflowDependencies,@@ -80,79 +105,108 @@ export const processUnderstandingProviders = async (...parsed,providers: parsed.providers.toSorted((left, right) => left.id.localeCompare(right.id)),};- const service = await (dependencies.createService ?? createService)(payload.userId);-- const providers = await Promise.all(- payload.providers.map(async ({ id: providerId, revision }) => {- const result = await runStep(context, `provider:${providerId}:${revision}:process`, () =>- service.processProvider({- providerId,- revision,- sessionId: payload.sessionId,- topicId: payload.topicId,- }),- );- await publishOnboardingGenerationProgress(payload.userId, payload.topicId);- if (result.status === 'completed' && result.revision === revision) {- const body = {- responseLanguage: payload.responseLanguage,- sessionId: payload.sessionId,- sourceFingerprint: result.sourceFingerprint,- topicId: payload.topicId,- userId: payload.userId,- };- const downstreamTasks: Promise<unknown>[] = [- context.invoke(`provider:${providerId}:write:${result.revision}`, {- body,- // Serialize writers for this session. The repository's fingerprint CAS then prevents a- // delayed failure callback for an older invocation from terminalizing newer writing.- flowControl: {- key: getUnderstandingWritingFlowControlKey(payload.sessionId),- parallelism: 1,+ return observeOnboardingUnderstandingWorkflow(+ context,+ {+ operation: 'workflow.providers',+ sessionId: payload.sessionId,+ topicId: payload.topicId,+ },+ async () => {+ const service = await (dependencies.createService ?? createService)(payload.userId);++ const providers = await Promise.all(+ payload.providers.map(async ({ id: providerId, revision }) => {+ const result = await runStep(context, `provider:${providerId}:${revision}:process`, () =>+ service.processProvider({+ providerId,+ revision,+ sessionId: payload.sessionId,+ topicId: payload.topicId,+ }),+ );+ await observeOnboardingUnderstandingOperation(+ {+ operation: 'progress.publish',+ providerId,+ sessionId: payload.sessionId,+ topicId: payload.topicId,},- workflow: dependencies.processCollectedWorkflow,- workflowRunId: collectedWorkflowRunId(payload.sessionId, result.sourceFingerprint),- }),- ];- if (payload.triggerTaskRecommendations !== false) {- downstreamTasks.push(- runStep(context, `provider:${providerId}:recommend:${result.revision}`, () =>- // NOTICE:- // Cross-route workflow fan-out must use an absolute QStash trigger.- // context.invoke only replaces the current URL's final path segment, which sent this- // child to `/api/workflows/onboarding/understanding/process` and returned 404.- // Source/context: `router-hono/workflows/memory-user-memory/workflows/processUserTopics.ts:193`.- // Remove when Upstash context.invoke supports absolute cross-route workflow URLs.- dependencies.triggerTaskRecommendations(body, {- // Every completed provider may race to schedule a fingerprint-specific run. The- // session-scoped flow-control key makes the first accepted fingerprint immutable.+ () => publishOnboardingGenerationProgress(payload.userId, payload.topicId),+ );+ if (result.status === 'completed' && result.revision === revision) {+ const body = {+ responseLanguage: payload.responseLanguage,+ sessionId: payload.sessionId,+ sourceFingerprint: result.sourceFingerprint,+ ...(payload.startedAt === undefined ? {} : { startedAt: payload.startedAt }),+ topicId: payload.topicId,+ userId: payload.userId,+ };+ const downstreamTasks: Promise<unknown>[] = [+ context.invoke(`provider:${providerId}:write:${result.revision}`, {+ body,+ // Serialize writers for this session. The repository's fingerprint CAS then prevents a+ // delayed failure callback for an older invocation from terminalizing newer writing.flowControl: {- key: getTaskRecommendationFlowControlKey(payload.sessionId),+ key: getUnderstandingWritingFlowControlKey(payload.sessionId),parallelism: 1,},- workflowRunId: taskRecommendationWorkflowRunId(- payload.sessionId,- result.sourceFingerprint,- ),+ headers: getOnboardingUnderstandingTraceHeaders(),+ workflow: dependencies.processCollectedWorkflow,+ workflowRunId: collectedWorkflowRunId(payload.sessionId, result.sourceFingerprint),}),- ),- );- }- await Promise.all(downstreamTasks);- }+ ];+ if (payload.triggerTaskRecommendations !== false) {+ downstreamTasks.push(+ runStep(context, `provider:${providerId}:recommend:${result.revision}`, () =>+ // NOTICE:+ // Cross-route workflow fan-out must use an absolute QStash trigger.+ // context.invoke only replaces the current URL's final path segment, which sent this+ // child to `/api/workflows/onboarding/understanding/process` and returned 404.+ // Source/context: `router-hono/workflows/memory-user-memory/workflows/processUserTopics.ts:193`.+ // Remove when Upstash context.invoke supports absolute cross-route workflow URLs.+ dependencies.triggerTaskRecommendations(+ {+ responseLanguage: payload.responseLanguage,+ sessionId: payload.sessionId,+ sourceFingerprint: result.sourceFingerprint,+ topicId: payload.topicId,+ userId: payload.userId,+ },+ {+ // Every completed provider may race to schedule a fingerprint-specific run. The+ // session-scoped flow-control key makes the first accepted fingerprint immutable.+ flowControl: {+ key: getTaskRecommendationFlowControlKey(payload.sessionId),+ parallelism: 1,+ },+ workflowRunId: taskRecommendationWorkflowRunId(+ payload.sessionId,+ result.sourceFingerprint,+ ),+ },+ ),+ ),+ );+ }+ await Promise.all(downstreamTasks);+ }++ return {+ failedCount: result.failedCount,+ providerId,+ revision: result.revision,+ sourceCount: result.sourceCount,+ status: result.status,+ succeededCount: result.succeededCount,+ };+ }),+ );- return {- failedCount: result.failedCount,- providerId,- revision: result.revision,- sourceCount: result.sourceCount,- status: result.status,- succeededCount: result.succeededCount,- };- }),+ return { providers };+ },);-- return { providers };};export const failRunningUnderstandingProviders = async (diff --git a/apps/server/src/workflows/onboardingUnderstanding/types.ts b/apps/server/src/workflows/onboardingUnderstanding/types.tsindex 43c80d95fee..cbdee1052c3 100644--- a/apps/server/src/workflows/onboardingUnderstanding/types.ts+++ b/apps/server/src/workflows/onboardingUnderstanding/types.ts@@ -12,6 +12,8 @@ export interface ProcessUnderstandingProvidersPayload {/** Language required for the eventual user-visible proposal. */responseLanguage: string;sessionId: string;+ /** API start timestamp used only for end-to-end latency telemetry. */+ startedAt?: number;topicId: string;/*** Whether completed sources should also start task recommendation generation.@@ -34,6 +36,8 @@ export interface ProcessCollectedUnderstandingPayload {responseLanguage: string;sessionId: string;sourceFingerprint: string;+ /** API start timestamp propagated across asynchronous workflow boundaries. */+ startedAt?: number;topicId: string;userId: string;}@@ -59,6 +63,7 @@ export const ProcessUnderstandingProvidersPayloadSchema = z.max(64).regex(/^[A-Z]{2,3}(?:-[A-Z0-9]{2,8})*$/i),sessionId: identifierSchema,+ startedAt: z.number().int().nonnegative().optional(),triggerTaskRecommendations: z.boolean().optional(),topicId: identifierSchema,userId: identifierSchema,@@ -79,6 +84,7 @@ export const ProcessCollectedUnderstandingPayloadSchema = z.min(1).max(2048).regex(/^[\w-]+@\d+(,[\w-]+@\d+)*$/),+ startedAt: z.number().int().nonnegative().optional(),topicId: identifierSchema,userId: identifierSchema,})diff --git a/packages/observability-otel/package.json b/packages/observability-otel/package.jsonindex 60bc22bb7ac..8f39d81025e 100644--- a/packages/observability-otel/package.json+++ b/packages/observability-otel/package.json@@ -10,6 +10,7 @@"./modules/agent-runtime": "./src/modules/agent-runtime/index.ts","./modules/agent-signal": "./src/modules/agent-signal/index.ts","./modules/memory-user-memory": "./src/modules/memory-user-memory/index.ts",+ "./modules/onboarding-understanding": "./src/modules/onboarding-understanding/index.ts","./modules/upstash-workflow": "./src/modules/upstash-workflow/index.ts"},"dependencies": {diff --git a/packages/observability-otel/src/modules/onboarding-understanding/index.test.ts b/packages/observability-otel/src/modules/onboarding-understanding/index.test.tsnew file mode 100644index 00000000000..cb4a5871c14--- /dev/null+++ b/packages/observability-otel/src/modules/onboarding-understanding/index.test.ts@@ -0,0 +1,50 @@+import { describe, expect, it } from 'vitest';++import {+ ATTR_ONBOARDING_UNDERSTANDING_OPERATION,+ ATTR_ONBOARDING_UNDERSTANDING_PROVIDER,+ ATTR_ONBOARDING_UNDERSTANDING_SESSION_ID,+ ATTR_ONBOARDING_UNDERSTANDING_STATUS,+ ATTR_ONBOARDING_UNDERSTANDING_TOPIC_ID,+ buildOnboardingUnderstandingMetricAttributes,+ buildOnboardingUnderstandingTraceAttributes,+} from './index';++/** @example describe('onboarding Understanding observability', () => {}); */+describe('onboarding Understanding observability', () => {+ /** @example expect(metricAttributes).not.toHaveProperty('session.id'); */+ it('keeps high-cardinality correlation identifiers out of metrics', () => {+ const attributes = buildOnboardingUnderstandingMetricAttributes(+ {+ operation: 'provider.collect',+ providerId: 'github',+ sessionId: 'session-1',+ topicId: 'topic-1',+ },+ 'success',+ );++ /** @example expect(attributes).toEqual({ operation: 'provider.collect' }); */+ expect(attributes).toEqual({+ [ATTR_ONBOARDING_UNDERSTANDING_OPERATION]: 'provider.collect',+ [ATTR_ONBOARDING_UNDERSTANDING_PROVIDER]: 'github',+ [ATTR_ONBOARDING_UNDERSTANDING_STATUS]: 'success',+ });+ });++ /** @example expect(traceAttributes).toHaveProperty('session.id'); */+ it('keeps session and topic identifiers available for trace correlation', () => {+ const attributes = buildOnboardingUnderstandingTraceAttributes({+ operation: 'writer.process',+ sessionId: 'session-1',+ topicId: 'topic-1',+ });++ /** @example expect(attributes).toEqual({ operation: 'writer.process' }); */+ expect(attributes).toEqual({+ [ATTR_ONBOARDING_UNDERSTANDING_OPERATION]: 'writer.process',+ [ATTR_ONBOARDING_UNDERSTANDING_SESSION_ID]: 'session-1',+ [ATTR_ONBOARDING_UNDERSTANDING_TOPIC_ID]: 'topic-1',+ });+ });+});diff --git a/packages/observability-otel/src/modules/onboarding-understanding/index.ts b/packages/observability-otel/src/modules/onboarding-understanding/index.tsnew file mode 100644index 00000000000..424e0843166--- /dev/null+++ b/packages/observability-otel/src/modules/onboarding-understanding/index.ts@@ -0,0 +1,217 @@+import type { Attributes } from '@opentelemetry/api';+import { metrics, SpanStatusCode, trace } from '@opentelemetry/api';++const meter = metrics.getMeter('server-services-onboarding-understanding');++/** Shared tracer for the complete onboarding Understanding pipeline. */+export const tracer = trace.getTracer('@lobechat/onboarding-understanding', '0.0.1');++/** Semantic operation attribute shared by spans and metrics. */+export const ATTR_ONBOARDING_UNDERSTANDING_OPERATION =+ 'onboarding.understanding.operation' as const;+/** Provider identifier attached to provider-scoped work. */+export const ATTR_ONBOARDING_UNDERSTANDING_PROVIDER = 'onboarding.understanding.provider' as const;+/** Durable session identifier used only for trace correlation. */+export const ATTR_ONBOARDING_UNDERSTANDING_SESSION_ID =+ 'onboarding.understanding.session.id' as const;+/** Technical success or error outcome. */+export const ATTR_ONBOARDING_UNDERSTANDING_STATUS = 'onboarding.understanding.status' as const;+/** Topic identifier used only for trace correlation. */+export const ATTR_ONBOARDING_UNDERSTANDING_TOPIC_ID = 'onboarding.understanding.topic.id' as const;++/** Stable operation names used by onboarding Understanding metrics and spans. */+export type OnboardingUnderstandingOperation =+ | 'detailed.commit'+ | 'detailed.generate'+ | 'detailed.process'+ | 'detailed.read-baseline'+ | 'detailed.read-result'+ | 'generation.runtime-call'+ | 'initialize'+ | 'progress.publish'+ | 'provider.collect'+ | 'provider.complete'+ | 'provider.mark-running'+ | 'provider.persist-context'+ | 'provider.process'+ | 'provider.resolve-available'+ | 'session.read'+ | 'session.persist'+ | 'session.start'+ | 'topic.assert-active'+ | 'workflow.collected'+ | 'workflow.detailed-persona'+ | 'workflow.providers'+ | 'workflow.trigger'+ | 'writer.create-message'+ | 'writer.commit'+ | 'writer.generate'+ | 'writer.prepare'+ | 'writer.process'+ | 'writer.read-baseline'+ | 'writer.read-contexts'+ | 'writer.read-existing'+ | 'writer.resolve-agent';++/** Outcome attached to aggregate operation metrics. */+export type OnboardingUnderstandingOperationStatus = 'error' | 'success';++/** Context attached to an onboarding Understanding operation. */+export interface OnboardingUnderstandingOperationAttributes {+ /** Stable low-cardinality operation identifier. */+ operation: OnboardingUnderstandingOperation;+ /** Provider identifier for provider-scoped work. */+ providerId?: string;+ /** Durable Understanding session identifier, emitted only on traces. */+ sessionId?: string;+ /** Personal onboarding topic identifier, emitted only on traces. */+ topicId?: string;+}++/** Count of onboarding Understanding operations grouped by operation and outcome. */+export const operationCounter = meter.createCounter('onboarding_understanding_operations_total', {+ description: 'Count of onboarding Understanding operations grouped by operation and outcome.',+ unit: '{operation}',+});++/** Duration of onboarding Understanding operations grouped by operation and outcome. */+export const operationDurationHistogram = meter.createHistogram(+ 'onboarding_understanding_operation_duration',+ {+ description:+ 'Duration of onboarding Understanding operations grouped by operation and outcome.',+ unit: 'ms',+ },+);++/** End-to-end duration from API start until a detailed persona is published. */+export const endToEndDurationHistogram = meter.createHistogram(+ 'onboarding_understanding_end_to_end_duration',+ {+ description:+ 'End-to-end duration from onboarding Understanding API start until a detailed persona publication.',+ unit: 'ms',+ },+);++/**+ * Builds low-cardinality attributes for aggregate Understanding metrics.+ *+ * Use when:+ * - Recording operation counters and duration histograms+ * - Keeping topic and session identifiers out of Prometheus label sets+ *+ * Expects:+ * - Operation names come from the bounded operation union+ *+ * Returns:+ * - Metric-safe attributes containing operation, status, and optional provider+ */+export const buildOnboardingUnderstandingMetricAttributes = (+ attributes: OnboardingUnderstandingOperationAttributes,+ status: OnboardingUnderstandingOperationStatus,+): Attributes => {+ const result: Attributes = {+ [ATTR_ONBOARDING_UNDERSTANDING_OPERATION]: attributes.operation,+ [ATTR_ONBOARDING_UNDERSTANDING_STATUS]: status,+ };+ if (attributes.providerId) {+ result[ATTR_ONBOARDING_UNDERSTANDING_PROVIDER] = attributes.providerId;+ }+ return result;+};++/**+ * Builds trace attributes for one Understanding operation.+ *+ * Use when:+ * - Correlating asynchronous workflow deliveries by topic and session+ *+ * Expects:+ * - Identifiers are already validated by the service or workflow payload schema+ *+ * Returns:+ * - Trace attributes with high-cardinality correlation fields+ */+export const buildOnboardingUnderstandingTraceAttributes = (+ attributes: OnboardingUnderstandingOperationAttributes,+): Attributes => {+ const result: Attributes = {+ [ATTR_ONBOARDING_UNDERSTANDING_OPERATION]: attributes.operation,+ };+ if (attributes.providerId) {+ result[ATTR_ONBOARDING_UNDERSTANDING_PROVIDER] = attributes.providerId;+ }+ if (attributes.sessionId) {+ result[ATTR_ONBOARDING_UNDERSTANDING_SESSION_ID] = attributes.sessionId;+ }+ if (attributes.topicId) {+ result[ATTR_ONBOARDING_UNDERSTANDING_TOPIC_ID] = attributes.topicId;+ }+ return result;+};++/**+ * Observes one asynchronous onboarding Understanding operation.+ *+ * Use when:+ * - Timing service, provider, writer, or workflow boundaries+ * - Preserving the active trace context across nested async work+ *+ * Expects:+ * - The callback owns the complete operation being timed+ *+ * Returns:+ * - The callback result while recording success or error telemetry+ */+export const observeOnboardingUnderstandingOperation = async <Result>(+ attributes: OnboardingUnderstandingOperationAttributes,+ operation: () => Promise<Result>,+): Promise<Result> =>+ tracer.startActiveSpan(+ `onboarding_understanding.${attributes.operation}`,+ { attributes: buildOnboardingUnderstandingTraceAttributes(attributes) },+ async (span) => {+ const startedAt = Date.now();+ let status: OnboardingUnderstandingOperationStatus = 'success';++ try {+ const result = await operation();+ span.setStatus({ code: SpanStatusCode.OK });+ return result;+ } catch (error) {+ status = 'error';+ const errorType = error instanceof Error ? error.name : typeof error;+ span.setAttribute('error.type', errorType);+ span.setStatus({ code: SpanStatusCode.ERROR, message: errorType });+ span.recordException(error instanceof Error ? error : String(error));+ throw error;+ } finally {+ const metricAttributes = buildOnboardingUnderstandingMetricAttributes(attributes, status);+ operationCounter.add(1, metricAttributes);+ operationDurationHistogram.record(Date.now() - startedAt, metricAttributes);+ span.end();+ }+ },+ );++/**+ * Records successful end-to-end onboarding Understanding latency.+ *+ * Use when:+ * - Detailed persona writing has committed for a workflow carrying the API start timestamp+ *+ * Expects:+ * - `startedAt` is an epoch-millisecond timestamp no later than the current time+ *+ * Returns:+ * - Nothing; invalid or future timestamps are ignored+ */+export const recordOnboardingUnderstandingEndToEndDuration = (startedAt?: number): void => {+ if (!startedAt || !Number.isFinite(startedAt)) return;+ const duration = Date.now() - startedAt;+ if (duration < 0) return;+ endToEndDurationHistogram.record(duration, {+ [ATTR_ONBOARDING_UNDERSTANDING_STATUS]: 'success',+ });+};