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): simplify first screen and defer topic creation to first send (#15090)

Innei029d4429927d
diff --git a/locales/en-US/onboarding.json b/locales/en-US/onboarding.json
index 4486e7f45ed..de244073369 100644
--- a/locales/en-US/onboarding.json
+++ b/locales/en-US/onboarding.json
@@ -20,6 +20,7 @@
"agent.greeting.vibePlaceholder": "e.g. Warm & friendly, Sharp & direct...",
"agent.history.current": "Current",
"agent.history.title": "History Topics",
+ "agent.input.preparing": "Getting ready…",
"agent.layout.mode.agent": "Conversational setup",
"agent.layout.mode.classic": "Manual setup",
"agent.layout.skip": "skip this step",
@@ -57,13 +58,6 @@
"agent.telemetryHint": "You can also answer in your own words.",
"agent.title": "Conversation Onboarding",
"agent.welcome": "Start by choosing my name and avatar. You can change them any time.",
- "agent.welcome.footer": "Configure your Lobe AI Agent. It learns from every interaction, and the longer it runs, the better it gets to know you.",
- "agent.welcome.guide.growTogether.desc": "With each chat, I'll understand you better and become a stronger teammate over time.",
- "agent.welcome.guide.growTogether.title": "Grow with You",
- "agent.welcome.guide.knowYou.desc": "What's on your plate these days? A little context helps me support you better.",
- "agent.welcome.guide.knowYou.title": "Get to Know You",
- "agent.welcome.guide.name.desc": "Give me a name so this feels more personal from the start.",
- "agent.welcome.guide.name.title": "Name Me",
"agent.welcome.sentence.1": "...hm? I just woke up — my mind's a blank.",
"agent.welcome.sentence.2": "What kind of partner should I become?",
"agent.welcome.suggestion.avatarHint": "Use {{emoji}} as the avatar.",
diff --git a/locales/zh-CN/onboarding.json b/locales/zh-CN/onboarding.json
index bffd6d32a05..e8e2d9d7b5c 100644
--- a/locales/zh-CN/onboarding.json
+++ b/locales/zh-CN/onboarding.json
@@ -20,6 +20,7 @@
"agent.greeting.vibePlaceholder": "例如:温暖友好,犀利直接...",
"agent.history.current": "当前",
"agent.history.title": "历史主题",
+ "agent.input.preparing": "正在准备…",
"agent.layout.mode.agent": "对话式设置",
"agent.layout.mode.classic": "手动设置",
"agent.layout.skip": "跳过此步骤",
@@ -57,13 +58,6 @@
"agent.telemetryHint": "您也可以用自己的话回答。",
"agent.title": "对话入职",
"agent.welcome": "先为我设置名称和头像,之后随时可以修改。",
- "agent.welcome.footer": "配置你的 Lobe AI 代理。它会从每次交互中学习,运行越久就越懂你。",
- "agent.welcome.guide.growTogether.desc": "每次交谈我都会更了解你,久而久之会成为更可靠的队友。",
- "agent.welcome.guide.growTogether.title": "与您一起成长",
- "agent.welcome.guide.knowYou.desc": "最近忙些什么?给我一些背景信息能让我更好地帮助你。",
- "agent.welcome.guide.knowYou.title": "了解你",
- "agent.welcome.guide.name.desc": "给我取个名字,这样从一开始就更有亲切感。",
- "agent.welcome.guide.name.title": "给我起个名字",
"agent.welcome.sentence.1": "...嗯?我刚醒来,脑子还是一片空白。",
"agent.welcome.sentence.2": "你希望我成为怎样的伙伴?",
"agent.welcome.suggestion.avatarHint": "头像用 {{emoji}}。",
diff --git a/packages/database/src/models/__tests__/messages/message.stats.test.ts b/packages/database/src/models/__tests__/messages/message.stats.test.ts
index 67cee3bd123..49c1e2fb078 100644
--- a/packages/database/src/models/__tests__/messages/message.stats.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.stats.test.ts
@@ -5,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { uuid } from '@/utils/uuid';
import { getTestDB } from '../../../core/getTestDB';
-import { embeddings, files, messages, sessions, users } from '../../../schemas';
+import { agents, embeddings, files, messages, sessions, topics, users } from '../../../schemas';
import type { LobeChatDatabase } from '../../../type';
import { MessageModel } from '../../message';
import { codeEmbedding } from '../fixtures/embedding';
@@ -661,4 +661,71 @@ describe('MessageModel Statistics Tests', () => {
expect(result).toBe(0);
});
});
+
+ describe('hasTopicMessages', () => {
+ const agentId = 'agent-has-topic-messages';
+ const topicWithMessages = 'topic-with-messages';
+ const emptyTopic = 'topic-empty';
+
+ beforeEach(async () => {
+ await serverDB.insert(agents).values({ id: agentId, userId });
+ await serverDB.insert(topics).values([
+ { id: topicWithMessages, userId, agentId, title: 'with-messages' },
+ { id: emptyTopic, userId, agentId, title: 'empty' },
+ ]);
+ await serverDB
+ .insert(messages)
+ .values([
+ { id: 'm1', userId, role: 'assistant', content: 'hi', topicId: topicWithMessages },
+ ]);
+ });
+
+ it('returns true when topic has at least one message', async () => {
+ const result = await messageModel.hasTopicMessages(topicWithMessages);
+ expect(result).toBe(true);
+ });
+
+ it('returns false when topic has no messages', async () => {
+ const result = await messageModel.hasTopicMessages(emptyTopic);
+ expect(result).toBe(false);
+ });
+
+ it('scopes by userId — other users’ messages do not leak', async () => {
+ const otherModel = new MessageModel(serverDB, otherUserId);
+ const result = await otherModel.hasTopicMessages(topicWithMessages);
+ expect(result).toBe(false);
+ });
+ });
+
+ describe('findFirstAssistantInTopic', () => {
+ const agentId = 'agent-find-first-assistant';
+ const topicId = 'topic-find-first-assistant';
+
+ beforeEach(async () => {
+ await serverDB.insert(agents).values({ id: agentId, userId });
+ await serverDB.insert(topics).values({ id: topicId, userId, agentId, title: 'topic' });
+ });
+
+ it('returns undefined when no assistant message exists', async () => {
+ await serverDB
+ .insert(messages)
+ .values([
+ { id: 'u1', userId, role: 'user', content: 'hi', topicId, createdAt: new Date(1) },
+ ]);
+
+ const result = await messageModel.findFirstAssistantInTopic(topicId);
+ expect(result).toBeUndefined();
+ });
+
+ it('returns the earliest assistant message in the topic', async () => {
+ await serverDB.insert(messages).values([
+ { id: 'u1', userId, role: 'user', content: 'hi', topicId, createdAt: new Date(2) },
+ { id: 'a-late', userId, role: 'assistant', content: 'b', topicId, createdAt: new Date(3) },
+ { id: 'a-early', userId, role: 'assistant', content: 'a', topicId, createdAt: new Date(1) },
+ ]);
+
+ const result = await messageModel.findFirstAssistantInTopic(topicId);
+ expect(result?.id).toBe('a-early');
+ });
+ });
});
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index 2b5bd871824..534f2af6204 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -1409,6 +1409,33 @@ export class MessageModel {
return result[0].count;
};
+ hasTopicMessages = async (topicId: string): Promise<boolean> => {
+ const rows = await this.db
+ .select({ id: messages.id })
+ .from(messages)
+ .where(and(eq(messages.userId, this.userId), eq(messages.topicId, topicId)))
+ .limit(1);
+
+ return rows.length > 0;
+ };
+
+ findFirstAssistantInTopic = async (topicId: string): Promise<DBMessageItem | undefined> => {
+ const rows = (await this.db
+ .select()
+ .from(messages)
+ .where(
+ and(
+ eq(messages.userId, this.userId),
+ eq(messages.topicId, topicId),
+ eq(messages.role, 'assistant'),
+ ),
+ )
+ .orderBy(asc(messages.createdAt))
+ .limit(1)) as DBMessageItem[];
+
+ return rows[0];
+ };
+
countWords = async (params?: {
endDate?: string;
range?: [string, string];
diff --git a/src/features/Onboarding/Agent/Conversation.test.tsx b/src/features/Onboarding/Agent/Conversation.test.tsx
index b6579963617..2521842b013 100644
--- a/src/features/Onboarding/Agent/Conversation.test.tsx
+++ b/src/features/Onboarding/Agent/Conversation.test.tsx
@@ -107,6 +107,26 @@ describe('AgentOnboardingConversation', () => {
expect(screen.queryByText('finish')).not.toBeInTheDocument();
});
+ it('suppresses the welcome flash while a returning user’s messages are still fetching', () => {
+ // Returning user: bootstrap says hasMessages=true but ChatList has not yet
+ // hydrated displayMessages — the welcome MUST stay hidden so we do not show
+ // a misleading "fresh" greeting before the transcript loads.
+ mockState.displayMessages = [];
+
+ render(<AgentOnboardingConversation hasMessages />);
+
+ expect(screen.queryByTestId('chat-welcome')).not.toBeInTheDocument();
+ expect(screen.queryByText('Welcome')).not.toBeInTheDocument();
+ });
+
+ it('forwards isInputReady=false to ChatInput as isConfigLoading', () => {
+ mockState.displayMessages = [];
+
+ render(<AgentOnboardingConversation isInputReady={false} />);
+
+ expect(chatInputSpy).toHaveBeenCalledWith(expect.objectContaining({ isConfigLoading: true }));
+ });
+
it('disables expand and runtime config in chat input', () => {
mockState.displayMessages = [{ id: 'assistant-1', role: 'assistant' }];
diff --git a/src/features/Onboarding/Agent/Conversation.tsx b/src/features/Onboarding/Agent/Conversation.tsx
index bdcd69099a1..95840c505c0 100644
--- a/src/features/Onboarding/Agent/Conversation.tsx
+++ b/src/features/Onboarding/Agent/Conversation.tsx
@@ -34,6 +34,16 @@ interface AgentOnboardingConversationProps {
discoveryUserMessageCount?: number;
feedbackSubmitted?: boolean;
finishTargetUrl?: string;
+ // When true, server reports the active topic already has at least one message.
+ // The welcome shell is suppressed and ChatList renders its built-in skeleton
+ // while messages fetch, avoiding the misleading "fresh Welcome flash" on
+ // returning users.
+ hasMessages?: boolean;
+ // While false, the underlying backend (bootstrap state or builtin agent
+ // config) is still hydrating: ChatInput shows its skeleton-style placeholder
+ // for the action/send area so the user cannot submit until the orchestration
+ // is ready to handle the first send.
+ isInputReady?: boolean;
onAfterWrapUp?: () => Promise<unknown> | void;
onAssistantTurnSettled?: (messageId: string) => Promise<unknown> | void;
onboardingFinished?: boolean;
@@ -56,6 +66,8 @@ const AgentOnboardingConversation = memo<AgentOnboardingConversationProps>(
discoveryUserMessageCount,
feedbackSubmitted,
finishTargetUrl,
+ hasMessages,
+ isInputReady = true,
onAfterWrapUp,
onAssistantTurnSettled,
onboardingFinished,
@@ -84,10 +96,15 @@ const AgentOnboardingConversation = memo<AgentOnboardingConversationProps>(
);
// The welcome ("AI opens") is rendered client-side from i18n until the
- // user sends their first message — at which point the welcome and the
- // user's reply are persisted together. Greeting state is therefore the
- // pre-conversation period when no messages have been recorded yet.
- const isGreetingState = useMemo(() => displayMessages.length === 0, [displayMessages]);
+ // user sends their first message. Greeting state is the pre-conversation
+ // period: when bootstrap reports no messages yet AND local store has not
+ // yet hydrated any. Using `hasMessages` as the authoritative signal
+ // (instead of only `displayMessages.length === 0`) prevents the brief
+ // window during messages-fetch for returning users from flashing Welcome.
+ const isGreetingState = useMemo(
+ () => !hasMessages && displayMessages.length === 0,
+ [hasMessages, displayMessages],
+ );
const latestAssistantMessageId = useMemo(() => {
const latest = displayMessages.at(-1);
@@ -226,6 +243,7 @@ const AgentOnboardingConversation = memo<AgentOnboardingConversationProps>(
disableQueue
allowExpand={false}
feature={chatInputFeature}
+ isConfigLoading={!isInputReady}
leftActions={chatInputLeftActions}
rightActions={chatInputRightActions}
showRuntimeConfig={false}
diff --git a/src/features/Onboarding/Agent/DebugExportButton.tsx b/src/features/Onboarding/Agent/DebugExportButton.tsx
index 10b7ce4888d..230cdb6ae74 100644
--- a/src/features/Onboarding/Agent/DebugExportButton.tsx
+++ b/src/features/Onboarding/Agent/DebugExportButton.tsx
@@ -17,7 +17,7 @@ interface DebugExportButtonContentProps {
interface DebugExportButtonProps {
agentId: string;
- topicId: string;
+ topicId: string | undefined;
}
const DEBUG_EXPORT_FIELDS = {
diff --git a/src/features/Onboarding/Agent/HistoryPanel.tsx b/src/features/Onboarding/Agent/HistoryPanel.tsx
index 57c11543432..138ce47f816 100644
--- a/src/features/Onboarding/Agent/HistoryPanel.tsx
+++ b/src/features/Onboarding/Agent/HistoryPanel.tsx
@@ -9,9 +9,9 @@ import type { ChatTopic } from '@/types/topic';
import { getOnboardingHistoryTopics } from './history';
interface HistoryPanelProps {
- activeTopicId: string;
+ activeTopicId?: string;
onSelectTopic: (topicId: string) => void;
- selectedTopicId: string;
+ selectedTopicId?: string;
topics: ChatTopic[];
}
diff --git a/src/features/Onboarding/Agent/OnboardingConversationProvider.tsx b/src/features/Onboarding/Agent/OnboardingConversationProvider.tsx
index 0f6b9db6660..53c1143cc51 100644
--- a/src/features/Onboarding/Agent/OnboardingConversationProvider.tsx
+++ b/src/features/Onboarding/Agent/OnboardingConversationProvider.tsx
@@ -15,7 +15,11 @@ interface OnboardingConversationProviderProps {
children: ReactNode;
frozen?: boolean;
hooks?: ConversationHooks;
- topicId: string;
+ // Allow undefined for the fresh-state window before the first message has
+ // created a real topic. Underlying ConversationProvider keys on
+ // messageMapKey(context) and remounts on transition, and useFetchMessages
+ // short-circuits when topicId is missing — so no extra refactor is needed.
+ topicId: string | undefined;
}
const OnboardingConversationProvider = memo<OnboardingConversationProviderProps>(
diff --git a/src/features/Onboarding/Agent/Welcome.mobile.tsx b/src/features/Onboarding/Agent/Welcome.mobile.tsx
index a4bea864512..c50f09946e9 100644
--- a/src/features/Onboarding/Agent/Welcome.mobile.tsx
+++ b/src/features/Onboarding/Agent/Welcome.mobile.tsx
@@ -1,4 +1,4 @@
-import { Flexbox, Markdown } from '@lobehub/ui';
+import { Flexbox } from '@lobehub/ui';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -24,14 +24,8 @@ const WelcomeMobile = memo(() => {
avatarSize={36}
fontSize={18}
gap={10}
- sentences={[
- t('agent.welcome.sentence.1'),
- t('agent.welcome.sentence.2'),
- ]}
+ sentences={[t('agent.welcome.sentence.1'), t('agent.welcome.sentence.2')]}
/>
- <Markdown fontSize={13} variant={'chat'}>
- {t('agent.welcome')}
- </Markdown>
</Flexbox>
</>
);
diff --git a/src/features/Onboarding/Agent/Welcome.tsx b/src/features/Onboarding/Agent/Welcome.tsx
index a6938403979..42a4f93897f 100644
--- a/src/features/Onboarding/Agent/Welcome.tsx
+++ b/src/features/Onboarding/Agent/Welcome.tsx
@@ -1,5 +1,4 @@
-import { Block, Flexbox, FluentEmoji, Grid, Markdown, Text } from '@lobehub/ui';
-import { Divider } from 'antd';
+import { Flexbox } from '@lobehub/ui';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,23 +9,6 @@ import { staticStyle } from './staticStyle';
const Welcome = memo(() => {
const { t } = useTranslation('onboarding');
- const guids = [
- {
- avatar: '👋',
- title: t('agent.welcome.guide.name.title'),
- desc: t('agent.welcome.guide.name.desc'),
- },
- {
- avatar: '💬',
- title: t('agent.welcome.guide.knowYou.title'),
- desc: t('agent.welcome.guide.knowYou.desc'),
- },
- {
- avatar: '🌱',
- title: t('agent.welcome.guide.growTogether.title'),
- desc: t('agent.welcome.guide.growTogether.desc'),
- },
- ];
return (
<>
<Flexbox flex={1} />
@@ -42,40 +24,8 @@ const Welcome = memo(() => {
avatarSize={72}
fontSize={32}
gap={16}
- sentences={[
- t('agent.welcome.sentence.1'),
- t('agent.welcome.sentence.2'),
- ]}
+ sentences={[t('agent.welcome.sentence.1'), t('agent.welcome.sentence.2')]}
/>
- <Divider dashed style={{ margin: 0 }} />
- <Markdown fontSize={16} variant={'chat'}>
- {t('agent.welcome')}
- </Markdown>
- <Grid>
- {guids.map((item, i) => (
- <Block
- shadow
- gap={12}
- key={i}
- padding={16}
- variant={'outlined'}
- style={{
- boxShadow: '0 8px 16px -8px rgba(0,0,0,0.06)',
- }}
- >
- <FluentEmoji emoji={item.avatar} size={24} type={'anim'} />
- <Flexbox gap={8}>
- <Text fontSize={16} weight={500}>
- {item.title}
- </Text>
- <Text type={'secondary'}>{item.desc}</Text>
- </Flexbox>
- </Block>
- ))}
- </Grid>
- <Text italic style={{ marginBlock: 8 }} type={'secondary'}>
- {t('agent.welcome.footer')}
- </Text>
</Flexbox>
</>
);
diff --git a/src/features/Onboarding/Agent/context.ts b/src/features/Onboarding/Agent/context.ts
index 6733168a846..b2a945d30a4 100644
--- a/src/features/Onboarding/Agent/context.ts
+++ b/src/features/Onboarding/Agent/context.ts
@@ -3,7 +3,7 @@ import type { UserAgentOnboarding, UserAgentOnboardingContext } from '@/types/us
export interface AgentOnboardingBootstrapContext {
agentOnboarding: UserAgentOnboarding;
context: UserAgentOnboardingContext;
- topicId: string;
+ topicId: string | null;
}
interface ResolveAgentOnboardingContextParams {
diff --git a/src/features/Onboarding/Agent/index.tsx b/src/features/Onboarding/Agent/index.tsx
index c11d416a54c..6ababc3f43c 100644
--- a/src/features/Onboarding/Agent/index.tsx
+++ b/src/features/Onboarding/Agent/index.tsx
@@ -8,7 +8,7 @@ import { RequestTrigger } from '@lobechat/types';
import { Button, ErrorBoundary, Flexbox } from '@lobehub/ui';
import { Drawer } from 'antd';
import { History } from 'lucide-react';
-import { memo, useCallback, useEffect, useMemo, useState } from 'react';
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
@@ -19,7 +19,6 @@ import { useOnboardingAgentTemplates } from '@/hooks/useOnboardingAgentTemplates
import { useClientDataSWR, useOnlyFetchOnceSWR } from '@/libs/swr';
import OnboardingContainer from '@/routes/onboarding/_layout';
import { fetchOnboardingAgentTemplates } from '@/services/agentMarketplace';
-import { messageService } from '@/services/message';
import { topicService } from '@/services/topic';
import { userService } from '@/services/user';
import { useAgentStore } from '@/store/agent';
@@ -89,7 +88,7 @@ const AgentOnboardingPage = memo(() => {
const { data, error, isLoading, mutate } = useOnlyFetchOnceSWR(
'agent-onboarding-bootstrap',
- () => userService.getOrCreateOnboardingState(),
+ () => userService.getOnboardingBootstrapState(),
{
onSuccess: async () => {
await refreshUserState();
@@ -106,7 +105,11 @@ const AgentOnboardingPage = memo(() => {
}),
[agentOnboarding, data],
);
- const activeTopicId = currentContext.topicId || data?.topicId;
+ // bootstrap topicId is now `string | null` for fresh users — coerce null to
+ // undefined so the rest of the code's optional-chaining behavior is preserved.
+ const bootstrapTopicId = data?.topicId ?? undefined;
+ const activeTopicId = currentContext.topicId || bootstrapTopicId;
+ const hasMessages = !!data?.hasMessages;
const historyTopics = historyData?.items || [];
const effectiveTopicId = selectedTopicId || activeTopicId;
const onboardingFinished = !!agentOnboarding?.finishedAt;
@@ -145,42 +148,77 @@ const AgentOnboardingPage = memo(() => {
});
const { onBeforeSendMessage, triggerExtract } = onboardingFollowUp;
+ // Re-entry latch for the fresh-state first-send orchestration. The combination
+ // of advisory lock + this ref ensures rapid double-submit cannot create two
+ // user messages: the second invocation awaits the same in-flight promise
+ // instead of dispatching its own sendMessage. See spec Revision 3.
+ const firstSendInFlightRef = useRef<Promise<void> | null>(null);
+
const composedOnBeforeSendMessage = useCallback(
- async (params: SendMessageParams) => {
+ async (params: SendMessageParams): Promise<boolean> => {
params.metadata = { ...params.metadata, trigger: RequestTrigger.Onboarding };
-
- const welcomeContent = t('agent.welcome');
await onBeforeSendMessage();
- if (!onboardingAgentId || !effectiveTopicId) return;
-
- const currentMessages = useChatStore.getState().dbMessagesMap[onboardingChatKey];
- if (currentMessages && currentMessages.length > 0) return;
-
- const result = await messageService.createMessage({
- agentId: onboardingAgentId,
- content: welcomeContent,
- role: 'assistant',
- topicId: effectiveTopicId,
- });
-
- // Sync the local cache so any subsequent reads see the welcome.
- useChatStore.setState((state) => ({
- dbMessagesMap: {
- ...state.dbMessagesMap,
- [onboardingChatKey]: result.messages,
- },
- }));
-
- // Force the in-flight sendMessage to use the welcome as LLM history,
- // since its `displayMessages` snapshot was captured before this hook ran.
- params.messages = result.messages;
+ if (!onboardingAgentId) {
+ // ChatInput is gated by `isInputReady`; this branch should be unreachable.
+ return false;
+ }
+
+ // Returning / edge: topic exists — let the normal sendMessage path proceed.
+ if (effectiveTopicId) return true;
+
+ // Fresh: orchestrate first-send ourselves and block the wrapping path.
+ if (firstSendInFlightRef.current) {
+ await firstSendInFlightRef.current;
+ return false;
+ }
+
+ const orchestration = (async () => {
+ try {
+ const welcomeContent = t('agent.welcome');
+ const { topicId: serverTopicId, messages } = await userService.sendOnboardingFirstMessage(
+ {
+ agentId: onboardingAgentId,
+ welcomeContent,
+ },
+ );
+
+ const key = messageMapKey({ agentId: onboardingAgentId, topicId: serverTopicId });
+ useChatStore.setState((state) => ({
+ dbMessagesMap: { ...state.dbMessagesMap, [key]: messages },
+ }));
+
+ // Update the page's own topic pointer + the SWR cache so subsequent
+ // renders route through the returning / edge branch.
+ setSelectedTopicId(serverTopicId);
+ await mutate(
+ (prev) => (prev ? { ...prev, hasMessages: true, topicId: serverTopicId } : prev),
+ { revalidate: false },
+ );
+
+ // Dispatch the real send directly into useChatStore.sendMessage with an
+ // EXPLICIT context, bypassing the conversation-store wrapper whose
+ // context still points at the (now-stale) undefined topicId. This avoids
+ // accidentally entering sendMessageInServer's new-topic creation branch.
+ await useChatStore.getState().sendMessage({
+ ...params,
+ context: { agentId: onboardingAgentId, topicId: serverTopicId },
+ messages,
+ });
+ } finally {
+ firstSendInFlightRef.current = null;
+ }
+ })();
+
+ firstSendInFlightRef.current = orchestration;
+ await orchestration;
+ return false;
},
- [effectiveTopicId, onBeforeSendMessage, onboardingAgentId, onboardingChatKey, t],
+ [effectiveTopicId, mutate, onBeforeSendMessage, onboardingAgentId, t],
);
const syncOnboardingContext = useCallback(async () => {
- const nextContext = await userService.getOrCreateOnboardingState();
+ const nextContext = await userService.getOnboardingBootstrapState();
await mutate(nextContext, { revalidate: false });
if (isDev && onboardingAgentId) await mutateHistoryTopics();
@@ -233,17 +271,25 @@ const AgentOnboardingPage = memo(() => {
);
}
- if (isLoading || !activeTopicId || !onboardingAgentId || !effectiveTopicId) {
+ // The builtin agent's slug must resolve before the page renders anything
+ // useful. This is a short, in-process hydration (the builtin agent table is
+ // usually warm); during this brief window we still show the brand loader.
+ // Once `onboardingAgentId` is present, render the static Welcome shell
+ // immediately — the bootstrap query keeps loading the rest in the background
+ // while ChatInput is gated via `isInputReady`.
+ if (!onboardingAgentId) {
return <Loading debugId="AgentOnboarding" />;
}
+ const isInputReady = !isLoading;
+
const handleReset = async () => {
setIsResetting(true);
try {
await resetAgentOnboarding();
const nextContext = await syncOnboardingContext();
- setSelectedTopicId(nextContext.topicId);
+ setSelectedTopicId(nextContext.topicId ?? undefined);
} finally {
setIsResetting(false);
}
@@ -264,6 +310,8 @@ const AgentOnboardingPage = memo(() => {
discoveryUserMessageCount={data?.context?.discoveryUserMessageCount}
feedbackSubmitted={!!data?.feedbackSubmitted}
finishTargetUrl={finishTargetUrl}
+ hasMessages={hasMessages}
+ isInputReady={isInputReady}
onboardingFinished={onboardingFinished}
phase={data?.context?.phase}
readOnly={viewingHistoricalTopic}
diff --git a/src/locales/default/onboarding.ts b/src/locales/default/onboarding.ts
index 3638b273d24..cffa78bd6d3 100644
--- a/src/locales/default/onboarding.ts
+++ b/src/locales/default/onboarding.ts
@@ -56,21 +56,12 @@ export default {
'agent.wrapUp.confirm.ok': 'Finish now',
'agent.wrapUp.confirm.title': 'Finish onboarding now?',
'agent.welcome': 'Start by choosing my name and avatar. You can change them any time.',
- 'agent.welcome.guide.growTogether.desc':
- "With each chat, I'll understand you better and become a stronger teammate over time.",
- 'agent.welcome.guide.growTogether.title': 'Grow with You',
- 'agent.welcome.guide.knowYou.desc':
- "What's on your plate these days? A little context helps me support you better.",
- 'agent.welcome.guide.knowYou.title': 'Get to Know You',
- 'agent.welcome.guide.name.desc': 'Give me a name so this feels more personal from the start.',
- 'agent.welcome.guide.name.title': 'Name Me',
'agent.welcome.suggestion.avatarHint': 'Use {{emoji}} as the avatar.',
'agent.welcome.suggestion.switch': 'Try another set',
'agent.welcome.suggestion.title': 'Need a starting point? Pick one and we can refine it later.',
'agent.welcome.sentence.1': "...hm? I just woke up — my mind's a blank.",
'agent.welcome.sentence.2': 'What kind of partner should I become?',
- 'agent.welcome.footer':
- 'Configure your Lobe AI Agent. It learns from every interaction, and the longer it runs, the better it gets to know you.',
+ 'agent.input.preparing': 'Getting ready…',
'agent.greeting.prompt': 'Give me a name, a vibe, and an emoji',
'agent.greeting.nameLabel': 'Name',
'agent.greeting.namePlaceholder': 'e.g. Lumi, Atlas, Neko...',
diff --git a/src/server/routers/lambda/user.ts b/src/server/routers/lambda/user.ts
index 57f988b11e5..d7158d75b30 100644
--- a/src/server/routers/lambda/user.ts
+++ b/src/server/routers/lambda/user.ts
@@ -255,6 +255,20 @@ export const userRouter = router({
return onboardingService.getOrCreateState();
}),
+ getOnboardingBootstrapState: userProcedure.query(async ({ ctx }) => {
+ const onboardingService = new OnboardingService(ctx.serverDB, ctx.userId);
+
+ return onboardingService.getBootstrapState();
+ }),
+
+ sendOnboardingFirstMessage: userProcedure
+ .input(z.object({ agentId: z.string().min(1), welcomeContent: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ const onboardingService = new OnboardingService(ctx.serverDB, ctx.userId);
+
+ return onboardingService.sendOnboardingFirstMessage(input);
+ }),
+
getOnboardingAgentContext: userProcedure.query(async ({ ctx }) => {
const onboardingService = new OnboardingService(ctx.serverDB, ctx.userId);
const docService = new AgentDocumentsService(ctx.serverDB, ctx.userId);
diff --git a/src/server/services/onboarding/index.test.ts b/src/server/services/onboarding/index.test.ts
index d3c41f1b691..e00a017679c 100644
--- a/src/server/services/onboarding/index.test.ts
+++ b/src/server/services/onboarding/index.test.ts
@@ -55,6 +55,8 @@ describe('OnboardingService', () => {
let mockDb: any;
let mockMessageModel: {
create: ReturnType<typeof vi.fn>;
+ findFirstAssistantInTopic: ReturnType<typeof vi.fn>;
+ hasTopicMessages: ReturnType<typeof vi.fn>;
listMessagePluginsByTopic: ReturnType<typeof vi.fn>;
query: ReturnType<typeof vi.fn>;
};
@@ -91,6 +93,7 @@ describe('OnboardingService', () => {
mockDb = {
delete: vi.fn(() => ({ where: vi.fn(async () => undefined) })),
+ execute: vi.fn(async () => undefined),
select: vi.fn(() => ({
from: vi.fn(() => ({
where: vi.fn(async () => [{ count: 0 }]),
@@ -98,6 +101,7 @@ describe('OnboardingService', () => {
})),
transaction: vi.fn(async (callback) =>
callback({
+ execute: vi.fn(async () => undefined),
update: vi.fn((table) => {
const where = vi.fn(async () => undefined);
const set = vi.fn(() => ({ where }));
@@ -131,7 +135,15 @@ describe('OnboardingService', () => {
}),
};
mockMessageModel = {
- create: vi.fn(async () => ({ id: 'message-1' })),
+ create: vi.fn(async () => ({
+ agentId: 'builtin-agent-1',
+ content: 'welcome',
+ id: 'message-1',
+ role: 'assistant',
+ topicId: 'topic-1',
+ })),
+ findFirstAssistantInTopic: vi.fn(async () => undefined),
+ hasTopicMessages: vi.fn(async () => false),
listMessagePluginsByTopic: vi.fn(async () => []),
query: vi.fn(async () => []),
};
@@ -624,4 +636,148 @@ describe('OnboardingService', () => {
// Baseline should remain 3, not updated to 6
expect(persistedUserState.agentOnboarding.discoveryStartUserMessageCount).toBe(3);
});
+
+ describe('getBootstrapState', () => {
+ it('returns fresh state (topicId=null, hasMessages=false) when no topic exists', async () => {
+ const service = new OnboardingService(mockDb, userId);
+ const result = await service.getBootstrapState();
+
+ expect(result.topicId).toBeNull();
+ expect(result.hasMessages).toBe(false);
+ expect(mockMessageModel.hasTopicMessages).not.toHaveBeenCalled();
+ // Must NOT create a topic on a read-only call.
+ expect(mockTopicModel.create).not.toHaveBeenCalled();
+ });
+
+ it('returns returning state with hasMessages=true when topic has messages', async () => {
+ persistedUserState.agentOnboarding = {
+ activeTopicId: 'topic-1',
+ version: CURRENT_ONBOARDING_VERSION,
+ };
+ persistedTopics['topic-1'] = { agentId: 'builtin-agent-1', id: 'topic-1', metadata: {} };
+ mockMessageModel.hasTopicMessages.mockResolvedValue(true);
+
+ const service = new OnboardingService(mockDb, userId);
+ const result = await service.getBootstrapState();
+
+ expect(result.topicId).toBe('topic-1');
+ expect(result.hasMessages).toBe(true);
+ expect(mockMessageModel.hasTopicMessages).toHaveBeenCalledWith('topic-1');
+ });
+
+ it('does not expose stale activeTopicId when the topic no longer exists', async () => {
+ persistedUserState.agentOnboarding = {
+ activeTopicId: 'missing-topic',
+ version: CURRENT_ONBOARDING_VERSION,
+ };
+
+ const service = new OnboardingService(mockDb, userId);
+ const result = await service.getBootstrapState();
+
+ expect(result.topicId).toBeNull();
+ expect(result.context.topicId).toBeUndefined();
+ expect(result.hasMessages).toBe(false);
+ expect(mockTopicModel.findById).toHaveBeenCalledWith('missing-topic');
+ expect(mockMessageModel.hasTopicMessages).not.toHaveBeenCalled();
+ expect(mockTopicModel.create).not.toHaveBeenCalled();
+ expect(mockUserModel.updateUser).not.toHaveBeenCalled();
+ });
+
+ it('does not write the discovery baseline (read-only semantics)', async () => {
+ persistedUserState.agentOnboarding = {
+ activeTopicId: 'topic-1',
+ version: CURRENT_ONBOARDING_VERSION,
+ };
+ persistedTopics['topic-1'] = { agentId: 'builtin-agent-1', id: 'topic-1', metadata: {} };
+ persistedUserState.fullName = 'Ada';
+ mockAgentModel.getBuiltinAgent.mockResolvedValue({
+ avatar: '😀',
+ id: 'inbox-agent-1',
+ title: 'Inbox',
+ });
+ mockDb.select.mockReturnValue({
+ from: vi.fn(() => ({
+ where: vi.fn(async () => [{ count: 4 }]),
+ })),
+ });
+
+ const service = new OnboardingService(mockDb, userId);
+ await service.getBootstrapState();
+
+ // Baseline must remain undefined — read-only getBootstrapState never writes.
+ expect(persistedUserState.agentOnboarding.discoveryStartUserMessageCount).toBeUndefined();
+ expect(mockUserModel.updateUser).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('sendOnboardingFirstMessage', () => {
+ it('creates topic + welcome on first call (happy path)', async () => {
+ const service = new OnboardingService(mockDb, userId);
+ mockMessageModel.query.mockResolvedValueOnce([
+ { content: 'welcome', id: 'message-1', role: 'assistant' },
+ ]);
+
+ const result = await service.sendOnboardingFirstMessage({
+ agentId: 'builtin-agent-1',
+ welcomeContent: 'welcome',
+ });
+
+ expect(mockTopicModel.create).toHaveBeenCalledTimes(1);
+ expect(mockMessageModel.findFirstAssistantInTopic).toHaveBeenCalledWith('topic-1');
+ expect(mockMessageModel.create).toHaveBeenCalledWith(
+ expect.objectContaining({ content: 'welcome', role: 'assistant', topicId: 'topic-1' }),
+ );
+ expect(persistedUserState.agentOnboarding.activeTopicId).toBe('topic-1');
+ expect(result.topicId).toBe('topic-1');
+ expect(result.messages).toHaveLength(1);
+ });
+
+ it('is idempotent — does not double-insert welcome when one already exists', async () => {
+ persistedUserState.agentOnboarding = {
+ activeTopicId: 'topic-1',
+ version: CURRENT_ONBOARDING_VERSION,
+ };
+ persistedTopics['topic-1'] = { agentId: 'builtin-agent-1', id: 'topic-1', metadata: {} };
+ mockMessageModel.findFirstAssistantInTopic.mockResolvedValueOnce({
+ content: 'welcome-old',
+ id: 'welcome-old',
+ role: 'assistant',
+ });
+ mockMessageModel.query.mockResolvedValueOnce([
+ { content: 'welcome-old', id: 'welcome-old', role: 'assistant' },
+ ]);
+
+ const service = new OnboardingService(mockDb, userId);
+ const result = await service.sendOnboardingFirstMessage({
+ agentId: 'builtin-agent-1',
+ welcomeContent: 'welcome-new',
+ });
+
+ expect(mockTopicModel.create).not.toHaveBeenCalled();
+ expect(mockMessageModel.create).not.toHaveBeenCalled();
+ expect(result.topicId).toBe('topic-1');
+ });
+
+ it('acquires the advisory lock before mutating', async () => {
+ const executeSpy = vi.fn(async () => undefined);
+ mockDb.transaction = vi.fn(async (callback: any) =>
+ callback({
+ execute: executeSpy,
+ update: vi.fn(() => ({ set: vi.fn(() => ({ where: vi.fn(async () => undefined) })) })),
+ }),
+ );
+ mockMessageModel.query.mockResolvedValueOnce([]);
+
+ const service = new OnboardingService(mockDb, userId);
+ await service.sendOnboardingFirstMessage({
+ agentId: 'builtin-agent-1',
+ welcomeContent: 'welcome',
+ });
+
+ expect(executeSpy).toHaveBeenCalledTimes(1);
+ // The first (only) execute call inside the transaction is the advisory lock.
+ // We assert structurally rather than on the exact SQL fragment.
+ expect(executeSpy).toHaveBeenCalled();
+ });
+ });
});
diff --git a/src/server/services/onboarding/index.ts b/src/server/services/onboarding/index.ts
index 6e01f293285..7a07de82f57 100644
--- a/src/server/services/onboarding/index.ts
+++ b/src/server/services/onboarding/index.ts
@@ -20,7 +20,7 @@ import {
SAVE_USER_QUESTION_FIELDS,
} from '@lobechat/types';
import { merge } from '@lobechat/utils';
-import { and, count, eq } from 'drizzle-orm';
+import { and, count, eq, sql } from 'drizzle-orm';
import { AgentModel } from '@/database/models/agent';
import { MessageModel } from '@/database/models/message';
@@ -499,6 +499,157 @@ export class OnboardingService {
};
};
+ // Read-only bootstrap. Unlike getOrCreateState, this never creates a topic and
+ // never writes the discoveryStartUserMessageCount baseline. The baseline write
+ // is deferred to the next mutation path (e.g. getOnboardingAgentContext or
+ // a message-send context resolution), which is acceptable because the baseline
+ // is only consulted once the user is past pre-discovery anyway.
+ getBootstrapState = async () => {
+ const builtinAgent = await this.agentService.getBuiltinAgent(BUILTIN_AGENT_SLUGS.webOnboarding);
+
+ if (!builtinAgent?.id) {
+ throw new Error('Failed to initialize onboarding agent');
+ }
+
+ const userState = await this.getUserState();
+ const state = this.ensureState(userState.agentOnboarding);
+ const missingStructuredFields = await this.getMissingStructuredFields();
+ const activeTopicId = state.activeTopicId;
+ const topic = activeTopicId ? await this.topicModel.findById(activeTopicId) : undefined;
+ const topicId = activeTopicId && topic ? activeTopicId : null;
+
+ const hasMessages = topicId ? await this.messageModel.hasTopicMessages(topicId) : false;
+
+ let context: UserAgentOnboardingContext;
+ if (state.finishedAt) {
+ context = {
+ finished: true,
+ missingStructuredFields,
+ phase: 'summary',
+ topicId: topicId ?? undefined,
+ version: state.version,
+ };
+ } else {
+ let discoveryContext:
+ | { currentUserMessageCount: number; startUserMessageCount: number }
+ | undefined;
+
+ if (topicId) {
+ const pastPreDiscovery =
+ !missingStructuredFields.includes('agentName') &&
+ !missingStructuredFields.includes('fullName');
+ if (pastPreDiscovery) {
+ const currentUserMessageCount = await this.countTopicUserMessages(topicId);
+ // If baseline is not yet persisted, treat current count as the baseline
+ // for read-only derivation; the next mutation path will persist it.
+ const startUserMessageCount =
+ state.discoveryStartUserMessageCount ?? currentUserMessageCount;
+ discoveryContext = { currentUserMessageCount, startUserMessageCount };
+ }
+ }
+
+ const phase = await this.derivePhase(missingStructuredFields, discoveryContext);
+
+ let discoveryUserMessageCount: number | undefined;
+ let remainingDiscoveryExchanges: number | undefined;
+ if (discoveryContext) {
+ discoveryUserMessageCount = Math.max(
+ 0,
+ discoveryContext.currentUserMessageCount - discoveryContext.startUserMessageCount,
+ );
+ remainingDiscoveryExchanges = Math.max(
+ 0,
+ RECOMMENDED_DISCOVERY_USER_MESSAGES - discoveryUserMessageCount,
+ );
+ }
+
+ context = {
+ ...(discoveryUserMessageCount !== undefined && { discoveryUserMessageCount }),
+ finished: false,
+ missingStructuredFields,
+ phase,
+ ...(remainingDiscoveryExchanges !== undefined && { remainingDiscoveryExchanges }),
+ topicId: topicId ?? undefined,
+ version: state.version,
+ };
+ }
+
+ return {
+ agentId: builtinAgent.id,
+ agentOnboarding: state,
+ context,
+ feedbackSubmitted: !!topic?.metadata?.onboardingFeedback,
+ hasMessages,
+ topicId,
+ };
+ };
+
+ // Atomically create the onboarding topic (if absent) and persist the welcome
+ // assistant opener message. Idempotent under concurrent invocation:
+ // - pg_advisory_xact_lock serializes per (userId, agentId)
+ // - existing assistant message in the topic short-circuits the welcome insert
+ // The user message and assistant response are created by the existing
+ // sendMessage pipeline on the client immediately after this resolves.
+ sendOnboardingFirstMessage = async (input: { agentId: string; welcomeContent: string }) => {
+ const { topicId } = await this.db.transaction(async (trx) => {
+ // Serialize concurrent first-send per (userId, agentId). hashtext returns int4;
+ // pg_advisory_xact_lock takes bigint, so we cast.
+ await trx.execute(
+ sql`SELECT pg_advisory_xact_lock(hashtext(${this.userId + ':' + input.agentId})::bigint)`,
+ );
+
+ const trxDb = trx as unknown as LobeChatDatabase;
+ const trxTopicModel = new TopicModel(trxDb, this.userId);
+ const trxMessageModel = new MessageModel(trxDb, this.userId);
+ const trxUserModel = new UserModel(trxDb, this.userId);
+
+ const userState = await trxUserModel.getUserState(KeyVaultsGateKeeper.getUserKeyVaults);
+ const state = this.ensureState(userState.agentOnboarding);
+
+ let nextTopicId = state.activeTopicId;
+ if (nextTopicId) {
+ const existing = await trxTopicModel.findById(nextTopicId);
+ if (!existing) nextTopicId = undefined;
+ }
+ if (!nextTopicId) {
+ const topic = await trxTopicModel.create({
+ agentId: input.agentId,
+ title: 'Onboarding',
+ trigger: 'chat',
+ });
+ nextTopicId = topic.id;
+ }
+
+ const existingAssistant = await trxMessageModel.findFirstAssistantInTopic(nextTopicId);
+ if (!existingAssistant) {
+ await trxMessageModel.create({
+ agentId: input.agentId,
+ content: input.welcomeContent,
+ role: 'assistant',
+ topicId: nextTopicId,
+ });
+ }
+
+ if (state.activeTopicId !== nextTopicId) {
+ const nextState = this.ensureState({ ...state, activeTopicId: nextTopicId });
+ await trxUserModel.updateUser({ agentOnboarding: nextState });
+ }
+
+ return { topicId: nextTopicId };
+ });
+
+ // Run the UI-shape query outside the lock so the response mirrors
+ // messageService.createMessage's grouping behavior.
+ const messages = await this.messageModel.query({
+ agentId: input.agentId,
+ current: 0,
+ pageSize: 9999,
+ topicId,
+ });
+
+ return { messages, topicId };
+ };
+
getState = async (): Promise<UserAgentOnboardingContext> => {
const userState = await this.getUserState();
const state = this.ensureState(userState.agentOnboarding);
diff --git a/src/services/user/index.ts b/src/services/user/index.ts
index fd8f10b7a1d..c43745fb9df 100644
--- a/src/services/user/index.ts
+++ b/src/services/user/index.ts
@@ -42,6 +42,21 @@ export class UserService {
return lambdaClient.user.getOrCreateOnboardingState.query();
};
+ getOnboardingBootstrapState = async (): Promise<{
+ agentId: string;
+ agentOnboarding: UserAgentOnboarding;
+ context: UserAgentOnboardingContext;
+ feedbackSubmitted: boolean;
+ hasMessages: boolean;
+ topicId: string | null;
+ }> => {
+ return lambdaClient.user.getOnboardingBootstrapState.query();
+ };
+
+ sendOnboardingFirstMessage = async (input: { agentId: string; welcomeContent: string }) => {
+ return lambdaClient.user.sendOnboardingFirstMessage.mutate(input);
+ };
+
getOnboardingAgentContext = async (): Promise<{
personaContent: string | null;
phaseGuidance: string;