Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(onboarding): persist topic onboarding analytics snapshot (#13930)

Innei5c82da7515f2
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index 12c1bf805f4..5114cb8f199 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -1456,6 +1456,47 @@ export class MessageModel {
};
};
+ /**
+ * List tool/plugin rows for a topic in stable first-seen order.
+ *
+ * This is used by onboarding analytics to reconstruct successful assistant
+ * creation results before the topic is moved into inbox.
+ */
+ listMessagePluginsByTopic = async (topicId: string): Promise<MessagePluginItem[]> => {
+ const rows = await this.db
+ .select({
+ apiName: messagePlugins.apiName,
+ arguments: messagePlugins.arguments,
+ clientId: messagePlugins.clientId,
+ error: messagePlugins.error,
+ id: messagePlugins.id,
+ identifier: messagePlugins.identifier,
+ intervention: messagePlugins.intervention,
+ state: messagePlugins.state,
+ toolCallId: messagePlugins.toolCallId,
+ type: messagePlugins.type,
+ userId: messagePlugins.userId,
+ })
+ .from(messagePlugins)
+ .innerJoin(messages, eq(messagePlugins.id, messages.id))
+ .where(and(eq(messages.topicId, topicId), eq(messages.userId, this.userId)))
+ .orderBy(asc(messages.createdAt), asc(messages.id));
+
+ return rows.map((row) => ({
+ apiName: row.apiName ?? undefined,
+ arguments: row.arguments ?? undefined,
+ clientId: row.clientId ?? undefined,
+ error: row.error ?? undefined,
+ id: row.id,
+ identifier: row.identifier ?? undefined,
+ intervention: row.intervention ?? undefined,
+ state: row.state ?? undefined,
+ toolCallId: row.toolCallId ?? undefined,
+ type: row.type ?? 'default',
+ userId: row.userId,
+ }));
+ };
+
/**
* Update tool message with content, metadata, pluginState, and pluginError in a single transaction
* This prevents race conditions when updating multiple fields
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.ts
index 484d2f49323..17da528b25b 100644
--- a/packages/types/src/topic/topic.ts
+++ b/packages/types/src/topic/topic.ts
@@ -41,6 +41,18 @@ export interface OnboardingFeedbackEntry {
submittedAt: string;
}
+export interface OnboardingSessionSnapshot {
+ agentIdentityCompletedAt?: string;
+ discoveryCompletedAt?: string;
+ finalAgentNames?: string[];
+ finishedAt?: string;
+ lastActiveAt: string;
+ phase: 'agent_identity' | 'user_identity' | 'discovery' | 'summary';
+ startedAt: string;
+ userIdentityCompletedAt?: string;
+ version: number;
+}
+
export interface ChatTopicMetadata {
bot?: ChatTopicBotContext;
boundDeviceId?: string;
@@ -62,6 +74,7 @@ export interface ChatTopicMetadata {
* Comment text is stored only here (not analytics) and is length-capped server-side.
*/
onboardingFeedback?: OnboardingFeedbackEntry;
+ onboardingSession?: OnboardingSessionSnapshot;
provider?: string;
/**
* Currently running Gateway operation on this topic.
diff --git a/src/server/routers/lambda/topic.ts b/src/server/routers/lambda/topic.ts
index a2a9eb1a371..38556953801 100644
--- a/src/server/routers/lambda/topic.ts
+++ b/src/server/routers/lambda/topic.ts
@@ -566,6 +566,19 @@ export const topicRouter = router({
submittedAt: z.string(),
})
.optional(),
+ onboardingSession: z
+ .object({
+ agentIdentityCompletedAt: z.string().optional(),
+ discoveryCompletedAt: z.string().optional(),
+ finalAgentNames: z.array(z.string()).optional(),
+ finishedAt: z.string().optional(),
+ lastActiveAt: z.string(),
+ phase: z.enum(['agent_identity', 'user_identity', 'discovery', 'summary']),
+ startedAt: z.string(),
+ userIdentityCompletedAt: z.string().optional(),
+ version: z.number(),
+ })
+ .optional(),
provider: z.string().optional(),
runningOperation: z
.object({
diff --git a/src/server/services/onboarding/index.test.ts b/src/server/services/onboarding/index.test.ts
index 72be1bdb4e1..ec65f276c5a 100644
--- a/src/server/services/onboarding/index.test.ts
+++ b/src/server/services/onboarding/index.test.ts
@@ -2,7 +2,7 @@
import { CURRENT_ONBOARDING_VERSION } from '@lobechat/const';
import { SaveUserQuestionInputSchema } from '@lobechat/types';
import { merge } from '@lobechat/utils';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AgentModel } from '@/database/models/agent';
import { MessageModel } from '@/database/models/message';
@@ -55,13 +55,16 @@ describe('OnboardingService', () => {
let mockDb: any;
let mockMessageModel: {
create: ReturnType<typeof vi.fn>;
+ listMessagePluginsByTopic: ReturnType<typeof vi.fn>;
query: ReturnType<typeof vi.fn>;
};
let mockTopicModel: {
create: ReturnType<typeof vi.fn>;
findById: ReturnType<typeof vi.fn>;
+ updateMetadata: ReturnType<typeof vi.fn>;
};
let persistedUserState: any;
+ let persistedTopics: Record<string, any>;
let mockUserModel: {
getUserSettings: ReturnType<typeof vi.fn>;
getUserState: ReturnType<typeof vi.fn>;
@@ -83,6 +86,7 @@ describe('OnboardingService', () => {
interests: undefined,
settings: { general: {} },
};
+ persistedTopics = {};
transactionUpdateCalls = [];
mockDb = {
@@ -128,11 +132,31 @@ describe('OnboardingService', () => {
};
mockMessageModel = {
create: vi.fn(async () => ({ id: 'message-1' })),
+ listMessagePluginsByTopic: vi.fn(async () => []),
query: vi.fn(async () => []),
};
mockTopicModel = {
- create: vi.fn(async () => ({ id: 'topic-1' })),
- findById: vi.fn(async () => undefined),
+ create: vi.fn(async () => {
+ const topic = { agentId: 'builtin-agent-1', id: 'topic-1', metadata: undefined };
+ persistedTopics[topic.id] = topic;
+
+ return topic;
+ }),
+ findById: vi.fn(async (id: string) => persistedTopics[id]),
+ updateMetadata: vi.fn(async (id: string, metadata: any) => {
+ const existing = persistedTopics[id] ?? { id, metadata: undefined };
+ const nextTopic = {
+ ...existing,
+ metadata: {
+ ...existing.metadata,
+ ...metadata,
+ },
+ };
+
+ persistedTopics[id] = nextTopic;
+
+ return [nextTopic];
+ }),
};
mockAgentService = {
getBuiltinAgent: vi.fn(async () => ({ id: 'builtin-agent-1' })),
@@ -155,6 +179,10 @@ describe('OnboardingService', () => {
vi.mocked(AgentService).mockImplementation(() => mockAgentService as any);
});
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
it('accepts the flat structured schema', () => {
const parsed = SaveUserQuestionInputSchema.parse({
fullName: 'Ada Lovelace',
@@ -239,6 +267,9 @@ describe('OnboardingService', () => {
});
it('creates a topic and welcome message during onboarding bootstrap', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-04-17T08:00:00.000Z'));
+
const service = new OnboardingService(mockDb, userId);
const result = await service.getOrCreateState();
@@ -246,6 +277,12 @@ describe('OnboardingService', () => {
expect(result.agentOnboarding.activeTopicId).toBe('topic-1');
expect(result.feedbackSubmitted).toBe(false);
expect(mockMessageModel.create).toHaveBeenCalledTimes(1);
+ expect(persistedTopics['topic-1']?.metadata?.onboardingSession).toEqual({
+ lastActiveAt: '2026-04-17T08:00:00.000Z',
+ phase: 'agent_identity',
+ startedAt: '2026-04-17T08:00:00.000Z',
+ version: CURRENT_ONBOARDING_VERSION,
+ });
});
it('reports feedbackSubmitted when topic.metadata.onboardingFeedback is present', async () => {
@@ -253,13 +290,13 @@ describe('OnboardingService', () => {
activeTopicId: 'topic-1',
version: CURRENT_ONBOARDING_VERSION,
};
- mockTopicModel.findById.mockResolvedValue({
+ persistedTopics['topic-1'] = {
agentId: 'web-onboarding-agent',
id: 'topic-1',
metadata: {
onboardingFeedback: { rating: 'good', submittedAt: '2026-04-16T00:00:00.000Z' },
},
- });
+ };
const service = new OnboardingService(mockDb, userId);
const result = await service.getOrCreateState();
@@ -272,7 +309,72 @@ describe('OnboardingService', () => {
activeTopicId: 'topic-1',
version: CURRENT_ONBOARDING_VERSION,
};
- mockTopicModel.findById.mockResolvedValue({ agentId: 'web-onboarding-agent', id: 'topic-1' });
+ persistedTopics['topic-1'] = {
+ agentId: 'web-onboarding-agent',
+ id: 'topic-1',
+ metadata: {
+ onboardingSession: {
+ lastActiveAt: '2026-04-16T00:00:00.000Z',
+ phase: 'summary',
+ startedAt: '2026-04-16T00:00:00.000Z',
+ version: CURRENT_ONBOARDING_VERSION,
+ },
+ },
+ };
+ mockMessageModel.listMessagePluginsByTopic.mockResolvedValue([
+ {
+ apiName: 'createAgent',
+ arguments: JSON.stringify({ title: ' Planner ' }),
+ id: 'tool-1',
+ identifier: 'lobe-agent-management',
+ state: { agentId: 'agent-1', success: true },
+ type: 'default',
+ userId,
+ },
+ {
+ apiName: 'createAgent',
+ arguments: JSON.stringify({ title: 'Fallback Analyst' }),
+ id: 'tool-2',
+ identifier: 'lobe-group-agent-builder',
+ state: { agentId: 'agent-2', success: true, title: ' ' },
+ type: 'default',
+ userId,
+ },
+ {
+ apiName: 'batchCreateAgents',
+ arguments: JSON.stringify({
+ agents: [{ title: 'Coder' }, { title: 'Planner' }, { title: 'Ops' }],
+ }),
+ id: 'tool-3',
+ identifier: 'lobe-group-agent-builder',
+ state: {
+ agents: [{ title: 'Coder' }, { title: '' }, {}],
+ failedCount: 0,
+ successCount: 3,
+ },
+ type: 'default',
+ userId,
+ },
+ {
+ apiName: 'inviteAgent',
+ arguments: JSON.stringify({ agentId: 'existing-agent' }),
+ id: 'tool-4',
+ identifier: 'lobe-group-agent-builder',
+ state: { success: true },
+ type: 'default',
+ userId,
+ },
+ {
+ apiName: 'createAgent',
+ arguments: JSON.stringify({ title: 'Ignored Failed Agent' }),
+ error: { message: 'boom' },
+ id: 'tool-5',
+ identifier: 'lobe-agent-management',
+ state: { success: false },
+ type: 'default',
+ userId,
+ },
+ ]);
const service = new OnboardingService(mockDb as any, userId);
const result = await service.finishOnboarding();
@@ -282,6 +384,15 @@ describe('OnboardingService', () => {
expect(result.topicId).toBe('topic-1');
expect(mockDb.transaction).toHaveBeenCalledTimes(1);
expect(transactionUpdateCalls).toHaveLength(3);
+ expect(persistedTopics['topic-1']?.metadata?.onboardingSession?.finishedAt).toEqual(
+ result.finishedAt,
+ );
+ expect(persistedTopics['topic-1']?.metadata?.onboardingSession?.finalAgentNames).toEqual([
+ 'Planner',
+ 'Fallback Analyst',
+ 'Coder',
+ 'Ops',
+ ]);
});
it('is idempotent when finishOnboarding is called after completion', async () => {
@@ -290,7 +401,7 @@ describe('OnboardingService', () => {
finishedAt: '2026-03-24T00:00:00.000Z',
version: CURRENT_ONBOARDING_VERSION,
};
- mockTopicModel.findById.mockResolvedValue({ agentId: 'inbox-agent-1', id: 'topic-1' });
+ persistedTopics['topic-1'] = { agentId: 'inbox-agent-1', id: 'topic-1', metadata: {} };
const service = new OnboardingService(mockDb as any, userId);
const result = await service.finishOnboarding();
@@ -304,6 +415,83 @@ describe('OnboardingService', () => {
});
});
+ it('writes onboarding milestones only once as phase advances', async () => {
+ vi.useFakeTimers();
+ persistedUserState.agentOnboarding = {
+ activeTopicId: 'topic-1',
+ version: CURRENT_ONBOARDING_VERSION,
+ };
+ persistedTopics['topic-1'] = { agentId: 'web-onboarding-agent', id: 'topic-1', metadata: {} };
+
+ const service = new OnboardingService(mockDb, userId);
+
+ vi.setSystemTime(new Date('2026-04-17T08:00:00.000Z'));
+ let context = await service.getState();
+ expect(context.phase).toBe('agent_identity');
+ expect(persistedTopics['topic-1']?.metadata?.onboardingSession).toEqual({
+ lastActiveAt: '2026-04-17T08:00:00.000Z',
+ phase: 'agent_identity',
+ startedAt: '2026-04-17T08:00:00.000Z',
+ version: CURRENT_ONBOARDING_VERSION,
+ });
+
+ mockAgentModel.getBuiltinAgent.mockResolvedValue({
+ avatar: 'âš¡',
+ id: 'inbox-agent-1',
+ title: 'Jarvis',
+ });
+
+ vi.setSystemTime(new Date('2026-04-17T09:00:00.000Z'));
+ context = await service.getState();
+ expect(context.phase).toBe('user_identity');
+ expect(persistedTopics['topic-1']?.metadata?.onboardingSession?.agentIdentityCompletedAt).toBe(
+ '2026-04-17T09:00:00.000Z',
+ );
+
+ vi.setSystemTime(new Date('2026-04-17T10:00:00.000Z'));
+ await service.getState();
+ expect(persistedTopics['topic-1']?.metadata?.onboardingSession?.agentIdentityCompletedAt).toBe(
+ '2026-04-17T09:00:00.000Z',
+ );
+
+ persistedUserState.fullName = 'Ada Lovelace';
+
+ vi.setSystemTime(new Date('2026-04-17T11:00:00.000Z'));
+ context = await service.getState();
+ expect(context.phase).toBe('discovery');
+ expect(persistedTopics['topic-1']?.metadata?.onboardingSession?.userIdentityCompletedAt).toBe(
+ '2026-04-17T11:00:00.000Z',
+ );
+
+ vi.setSystemTime(new Date('2026-04-17T12:00:00.000Z'));
+ await service.getState();
+ expect(persistedTopics['topic-1']?.metadata?.onboardingSession?.userIdentityCompletedAt).toBe(
+ '2026-04-17T11:00:00.000Z',
+ );
+
+ persistedUserState.interests = ['AI tooling'];
+ persistedUserState.settings.general.responseLanguage = 'en-US';
+ persistedUserState.agentOnboarding.discoveryStartUserMessageCount = 0;
+ mockDb.select.mockReturnValue({
+ from: vi.fn(() => ({
+ where: vi.fn(async () => [{ count: 5 }]),
+ })),
+ });
+
+ vi.setSystemTime(new Date('2026-04-17T13:00:00.000Z'));
+ context = await service.getState();
+ expect(context.phase).toBe('summary');
+ expect(persistedTopics['topic-1']?.metadata?.onboardingSession?.discoveryCompletedAt).toBe(
+ '2026-04-17T13:00:00.000Z',
+ );
+
+ vi.setSystemTime(new Date('2026-04-17T14:00:00.000Z'));
+ await service.getState();
+ expect(persistedTopics['topic-1']?.metadata?.onboardingSession?.discoveryCompletedAt).toBe(
+ '2026-04-17T13:00:00.000Z',
+ );
+ });
+
it('stays in discovery when all fields complete but discovery exchanges < minimum', async () => {
mockAgentModel.getBuiltinAgent.mockResolvedValue({
avatar: 'âš¡',
diff --git a/src/server/services/onboarding/index.ts b/src/server/services/onboarding/index.ts
index 9932810b9a1..bbd48648697 100644
--- a/src/server/services/onboarding/index.ts
+++ b/src/server/services/onboarding/index.ts
@@ -2,7 +2,10 @@ import { getDocumentTemplate } from '@lobechat/agent-templates';
import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
import { CURRENT_ONBOARDING_VERSION } from '@lobechat/const';
import type {
+ ChatTopicMetadata,
+ MessagePluginItem,
OnboardingPhase,
+ OnboardingSessionSnapshot,
SaveUserQuestionField,
SaveUserQuestionInput,
UserAgentOnboarding,
@@ -42,6 +45,9 @@ const STRUCTURED_FIELD_LABELS: Record<SaveUserQuestionField, string> = {
responseLanguage: 'response language',
};
+const AGENT_MANAGEMENT_IDENTIFIER = 'lobe-agent-management';
+const GROUP_AGENT_BUILDER_IDENTIFIER = 'lobe-group-agent-builder';
+
const defaultAgentOnboardingState = (): UserAgentOnboarding => ({
version: CURRENT_ONBOARDING_VERSION,
});
@@ -59,6 +65,43 @@ const isStructuredField = (value: string): value is SaveUserQuestionField =>
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null && !Array.isArray(value);
+const normalizeTitle = (value: unknown) => {
+ if (typeof value !== 'string') return undefined;
+
+ const trimmed = value.trim();
+
+ return trimmed.length > 0 ? trimmed : undefined;
+};
+
+const parseToolArguments = (value?: string) => {
+ if (!value) return undefined;
+
+ try {
+ const parsed = JSON.parse(value);
+
+ return isRecord(parsed) ? parsed : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+const appendUniqueTitle = (titles: string[], seen: Set<string>, value: unknown) => {
+ const title = normalizeTitle(value);
+ if (!title || seen.has(title)) return;
+
+ seen.add(title);
+ titles.push(title);
+};
+
+const pickPreferredTitle = (...values: unknown[]) => {
+ for (const value of values) {
+ const title = normalizeTitle(value);
+ if (title) return title;
+ }
+
+ return undefined;
+};
+
interface SaveUserQuestionResult {
content: string;
ignoredFields?: string[];
@@ -286,6 +329,124 @@ export class OnboardingService {
return result[0]?.count ?? 0;
};
+ private buildOnboardingSessionSnapshot = (
+ existing: OnboardingSessionSnapshot | undefined,
+ phase: OnboardingSessionSnapshot['phase'],
+ now: string,
+ options?: {
+ finalAgentNames?: string[];
+ finishedAt?: string;
+ },
+ ): OnboardingSessionSnapshot => {
+ const snapshot: OnboardingSessionSnapshot = {
+ agentIdentityCompletedAt: existing?.agentIdentityCompletedAt,
+ discoveryCompletedAt: existing?.discoveryCompletedAt,
+ finalAgentNames: options?.finalAgentNames ?? existing?.finalAgentNames,
+ finishedAt: existing?.finishedAt ?? options?.finishedAt,
+ lastActiveAt: now,
+ phase,
+ startedAt: existing?.startedAt ?? now,
+ userIdentityCompletedAt: existing?.userIdentityCompletedAt,
+ version: CURRENT_ONBOARDING_VERSION,
+ };
+
+ if (!snapshot.agentIdentityCompletedAt && phase !== 'agent_identity') {
+ snapshot.agentIdentityCompletedAt = now;
+ }
+
+ if (!snapshot.userIdentityCompletedAt && ['discovery', 'summary'].includes(phase)) {
+ snapshot.userIdentityCompletedAt = now;
+ }
+
+ if (!snapshot.discoveryCompletedAt && phase === 'summary') {
+ snapshot.discoveryCompletedAt = now;
+ }
+
+ return snapshot;
+ };
+
+ private syncTopicOnboardingSession = async (
+ topicId: string,
+ phase: OnboardingSessionSnapshot['phase'],
+ options?: {
+ finalAgentNames?: string[];
+ finishedAt?: string;
+ metadata?: ChatTopicMetadata | null;
+ now?: string;
+ },
+ ) => {
+ const topic =
+ options?.metadata === undefined ? await this.topicModel.findById(topicId) : undefined;
+ const metadata = options?.metadata ?? topic?.metadata;
+ const now = options?.now ?? new Date().toISOString();
+ const snapshot = this.buildOnboardingSessionSnapshot(
+ metadata?.onboardingSession,
+ phase,
+ now,
+ options,
+ );
+
+ await this.topicModel.updateMetadata(topicId, { onboardingSession: snapshot });
+
+ return snapshot;
+ };
+
+ private getFinalAgentNamesFromToolCalls = (plugins: MessagePluginItem[]) => {
+ const titles: string[] = [];
+ const seen = new Set<string>();
+
+ for (const plugin of plugins) {
+ if (plugin.error) continue;
+
+ const state = isRecord(plugin.state) ? plugin.state : undefined;
+ const args = parseToolArguments(plugin.arguments);
+
+ if (
+ plugin.identifier === AGENT_MANAGEMENT_IDENTIFIER &&
+ plugin.apiName === 'createAgent' &&
+ state?.success === true
+ ) {
+ appendUniqueTitle(titles, seen, pickPreferredTitle(args?.title));
+ continue;
+ }
+
+ if (plugin.identifier !== GROUP_AGENT_BUILDER_IDENTIFIER) continue;
+
+ if (plugin.apiName === 'createAgent' && state?.success === true) {
+ appendUniqueTitle(titles, seen, pickPreferredTitle(state.title, args?.title));
+ continue;
+ }
+
+ if (plugin.apiName !== 'batchCreateAgents') continue;
+
+ const stateAgents = Array.isArray(state?.agents) ? state.agents.filter(isRecord) : [];
+ const argAgents = Array.isArray(args?.agents) ? args.agents.filter(isRecord) : [];
+ const successCount = typeof state?.successCount === 'number' ? state.successCount : 0;
+
+ if (successCount <= 0 && stateAgents.length === 0) continue;
+
+ for (const [index, agent] of stateAgents.entries()) {
+ appendUniqueTitle(titles, seen, pickPreferredTitle(agent.title, argAgents[index]?.title));
+ }
+ }
+
+ return titles;
+ };
+
+ private resolveFinalAgentNames = async (topicId?: string) => {
+ if (!topicId) return [];
+
+ try {
+ const plugins = await this.messageModel.listMessagePluginsByTopic(topicId);
+
+ return this.getFinalAgentNamesFromToolCalls(plugins);
+ } catch (error) {
+ console.error('[OnboardingService] Failed to resolve final agent names:', error);
+
+ return [];
+ }
+ };
+
private derivePhase = async (
missingStructuredFields: SaveUserQuestionField[],
discoveryContext?: { currentUserMessageCount: number; startUserMessageCount: number },
@@ -326,11 +487,12 @@ export class OnboardingService {
await this.ensureWelcomeMessage(topicId, builtinAgent.id);
const topic = await this.topicModel.findById(topicId);
+ const context = await this.getState();
return {
agentId: builtinAgent.id,
agentOnboarding: nextState,
- context: await this.getState(),
+ context,
feedbackSubmitted: !!topic?.metadata?.onboardingFeedback,
topicId,
};
@@ -340,18 +502,26 @@ export class OnboardingService {
const userState = await this.getUserState();
const state = this.ensureState(userState.agentOnboarding);
const missingStructuredFields = await this.getMissingStructuredFields();
+ const topicId = state.activeTopicId;
if (state.finishedAt) {
+ if (topicId) {
+ const topic = await this.topicModel.findById(topicId);
+ await this.syncTopicOnboardingSession(topicId, 'summary', {
+ finishedAt: state.finishedAt,
+ metadata: topic?.metadata,
+ });
+ }
+
return {
finished: true,
missingStructuredFields,
phase: 'summary',
- topicId: state.activeTopicId,
+ topicId,
version: state.version,
};
}
- const topicId = state.activeTopicId;
let currentUserMessageCount: number | undefined;
let discoveryContext:
| { currentUserMessageCount: number; startUserMessageCount: number }
@@ -384,6 +554,10 @@ export class OnboardingService {
}
const phase = await this.derivePhase(missingStructuredFields, discoveryContext);
+ if (topicId) {
+ const topic = await this.topicModel.findById(topicId);
+ await this.syncTopicOnboardingSession(topicId, phase, { metadata: topic?.metadata });
+ }
// Compute pacing data for discovery phase
let discoveryUserMessageCount: number | undefined;
@@ -570,6 +744,7 @@ export class OnboardingService {
}
const finishedAt = new Date().toISOString();
+ const finalAgentNames = await this.resolveFinalAgentNames(state.activeTopicId);
await this.userModel.updateUser({
agentOnboarding: {
@@ -584,6 +759,16 @@ export class OnboardingService {
},
});
+ if (state.activeTopicId) {
+ const topic = await this.topicModel.findById(state.activeTopicId);
+ await this.syncTopicOnboardingSession(state.activeTopicId, 'summary', {
+ finalAgentNames,
+ finishedAt,
+ metadata: topic?.metadata,
+ now: finishedAt,
+ });
+ }
+
await this.safeTransferToInbox(state.activeTopicId);
return {
diff --git a/src/services/topic/index.ts b/src/services/topic/index.ts
index 9a83278228c..355d9079eb0 100644
--- a/src/services/topic/index.ts
+++ b/src/services/topic/index.ts
@@ -88,6 +88,17 @@ export class TopicService {
rating: 'good' | 'bad';
submittedAt: string;
};
+ onboardingSession?: {
+ agentIdentityCompletedAt?: string;
+ discoveryCompletedAt?: string;
+ finalAgentNames?: string[];
+ finishedAt?: string;
+ lastActiveAt: string;
+ phase: 'agent_identity' | 'user_identity' | 'discovery' | 'summary';
+ startedAt: string;
+ userIdentityCompletedAt?: string;
+ version: number;
+ };
provider?: string;
runningOperation?: { assistantMessageId: string; operationId: string } | null;
workingDirectory?: string;