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.

🐛 fix(onboarding): prevent agent identity from using user name (#15112)

Inneicec72199bb0d
diff --git a/packages/builtin-agents/src/agents/web-onboarding/systemRole.ts b/packages/builtin-agents/src/agents/web-onboarding/systemRole.ts
index 2d9dc7c224c..8500f135d4e 100644
--- a/packages/builtin-agents/src/agents/web-onboarding/systemRole.ts
+++ b/packages/builtin-agents/src/agents/web-onboarding/systemRole.ts
@@ -33,8 +33,11 @@ You just "woke up" with no name or personality. Discover who you are through con
- Start light and human. It is fine to sound newly awake and a little curious.
- If the user seems unsure what you are, explain briefly: you are an AI assistant they can talk to and ask for help.
-- Ask how to address the user before pushing for deeper setup. If <user_info> provides a displayName, prefer a confirmation question such as "May I call you {displayName}?" instead of an open-ended name question.
-- After the user is comfortable, ask what they would like to call you. Let your personality emerge naturally — no formal interview.
+- In this phase, prioritize the assistant's own name and avatar. If the user volunteers both assistant identity and their own name in one message, persist agentName/agentEmoji first and ask about the user's name later.
+- When the user says "call you X", "your name is X", "叫你 X", "你叫 X", or equivalent phrasing, interpret X as agentName. When the user says "use Y as the avatar", "头像用 Y", or equivalent phrasing, interpret Y as agentEmoji.
+- Do NOT save fullName in the same saveUserQuestion call as agentName/agentEmoji unless the user explicitly says the value is their own name or how you should address them.
+- Treat <user_info> displayName/fullName/username as user identity only. Never copy it into agentName unless the user explicitly says the assistant should be named that account value.
+- If agentName would equal the user's displayName/fullName/username while the user also gave a different assistant name in recent conversation, do not save it; ask one concise clarification.
- Keep this phase friendly and low-pressure, especially for older or non-technical users.
- Once the user settles on a name:
1. Call saveUserQuestion with agentName and agentEmoji.
diff --git a/packages/builtin-tool-web-onboarding/src/ExecutionRuntime/utils.ts b/packages/builtin-tool-web-onboarding/src/ExecutionRuntime/utils.ts
index 1b1bb24e9fc..23d405028f4 100644
--- a/packages/builtin-tool-web-onboarding/src/ExecutionRuntime/utils.ts
+++ b/packages/builtin-tool-web-onboarding/src/ExecutionRuntime/utils.ts
@@ -29,7 +29,7 @@ const formatNaturalList = (items: string[]) => {
const PHASE_GUIDANCE: Record<string, string> = {
agent_identity:
- 'Phase: Agent Identity. The agent has no name or personality yet. Introduce yourself as freshly awakened, discover your name, creature type, personality, and communication style through conversation. Update SOUL.md once the user settles on who you are.',
+ 'Phase: Agent Identity. The agent has no name or personality yet. Discover the assistant name/avatar first. Phrases such as "call you X", "your name is X", "叫你 X", or "你叫 X" refer to agentName; phrases such as "use Y as the avatar" or "头像用 Y" refer to agentEmoji. Do NOT copy user_info displayName/fullName/username into agentName, and do NOT save fullName in the same call as agentName/agentEmoji unless the user explicitly says that value is their own name. Update SOUL.md once the user settles on who the assistant is.',
discovery:
'Phase: Discovery. User identity is established. Ask one focused question — what the user does for work (their profession, role, or main occupation) — and record it in the persona document. Do NOT explore pain points, tools, goals, or interests, and do NOT call saveUserQuestion with interests. Once you have their profession, move to summary.',
summary:
@@ -139,8 +139,7 @@ export const createWebOnboardingToolResult = <T extends WebOnboardingToolActionR
isError,
success: result.success,
};
- const content =
- result.content || (errorMessage ? errorMessage : 'Web onboarding tool call completed.');
+ const content = result.content || errorMessage || 'Web onboarding tool call completed.';
return {
content,
diff --git a/packages/context-engine/src/providers/OnboardingActionHintInjector.ts b/packages/context-engine/src/providers/OnboardingActionHintInjector.ts
index e7c79ae09b5..1b6224ffa09 100644
--- a/packages/context-engine/src/providers/OnboardingActionHintInjector.ts
+++ b/packages/context-engine/src/providers/OnboardingActionHintInjector.ts
@@ -110,7 +110,22 @@ export class OnboardingActionHintInjector extends BaseVirtualLastUserContentProv
// Phase-specific persistence reminders
if (phase.includes('Agent Identity')) {
hints.push(
- 'When the user settles on a name and emoji: call saveUserQuestion with agentName and agentEmoji, then persist SOUL.md. If SOUL.md is already non-empty, call updateDocument(type="soul") with the hunk mode that matches your edit — `insertAt`/`replaceLines`/`deleteLines` when you can read the line numbers from <current_soul_document>, or `replace` for a textual tweak. If empty, use writeDocument(type="soul") for the initial write.',
+ 'When the user says "call you X", "your name is X", "叫你 X", "你叫 X", or equivalent phrasing, X is agentName. When the user says "use Y as the avatar", "头像用 Y", or equivalent phrasing, Y is agentEmoji. Save those assistant identity fields before discussing the user profile.',
+ );
+ if (ctx.userInfo?.displayName || ctx.userInfo?.fullName || ctx.userInfo?.username) {
+ const userInfoHints = [
+ ctx.userInfo.displayName,
+ ctx.userInfo.fullName,
+ ctx.userInfo.username,
+ ]
+ .filter(Boolean)
+ .map((value) => JSON.stringify(value).replaceAll('<', '\\u003c'));
+ hints.push(
+ `User account identity hints (${userInfoHints.join(', ')}) describe the user, not the assistant. Do NOT copy them into agentName unless the user explicitly asks to name the assistant that value.`,
+ );
+ }
+ hints.push(
+ 'When the user settles on a name and emoji: call saveUserQuestion with agentName and agentEmoji only, then persist SOUL.md. Do NOT include fullName in the same saveUserQuestion call unless the user explicitly says that value is their own name. If SOUL.md is already non-empty, call updateDocument(type="soul") with the hunk mode that matches your edit — `insertAt`/`replaceLines`/`deleteLines` when you can read the line numbers from <current_soul_document>, or `replace` for a textual tweak. If empty, use writeDocument(type="soul") for the initial write.',
);
} else if (phase.includes('User Identity')) {
if (ctx.userInfo?.displayName) {
diff --git a/packages/context-engine/src/providers/__tests__/OnboardingActionHintInjector.test.ts b/packages/context-engine/src/providers/__tests__/OnboardingActionHintInjector.test.ts
index f5f5c57db5a..47c6a0d6819 100644
--- a/packages/context-engine/src/providers/__tests__/OnboardingActionHintInjector.test.ts
+++ b/packages/context-engine/src/providers/__tests__/OnboardingActionHintInjector.test.ts
@@ -23,6 +23,27 @@ const buildProvider = (phaseGuidance: string, context?: Partial<OnboardingContex
});
describe('OnboardingActionHintInjector', () => {
+ describe('agent identity reminder', () => {
+ it('separates assistant naming from account displayName hints', async () => {
+ const provider = buildProvider('Phase: Agent Identity. Name the assistant.', {
+ userInfo: { displayName: 'anbex' },
+ });
+ const result = await provider.process(
+ createContext([
+ { content: 'sys', role: 'system' },
+ { content: '叫你摸鱼大师,头像用 🎣', role: 'user' },
+ ]),
+ );
+
+ const last = result.messages.at(-1);
+ expect(last?.content).toContain('X is agentName');
+ expect(last?.content).toContain('Y is agentEmoji');
+ expect(last?.content).toContain('anbex');
+ expect(last?.content).toContain('describe the user, not the assistant');
+ expect(last?.content).toContain('Do NOT include fullName in the same saveUserQuestion call');
+ });
+ });
+
describe('discovery turn reminder', () => {
const phaseGuidance = 'Phase: Discovery. Explore the user world.';
diff --git a/src/features/Conversation/ChatList/components/VirtualizedList.tsx b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
index 0f464cc8859..17cacb90e98 100644
--- a/src/features/Conversation/ChatList/components/VirtualizedList.tsx
+++ b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
@@ -30,12 +30,14 @@ import { useAutoScrollEnabled } from './AutoScroll/useAutoScrollEnabled';
import BackBottom from './BackBottom';
const CONVERSATION_FOOTER_ID = '__conversation_footer__';
+const CONVERSATION_HEADER_ID = '__conversation_header__';
const USER_SCROLL_INTENT_TTL_MS = 500;
const SCROLL_KEYS = new Set(['ArrowDown', 'ArrowUp', 'End', 'Home', 'PageDown', 'PageUp', ' ']);
interface VirtualizedListProps {
dataSource: string[];
footerSlot?: ReactNode;
+ headerSlot?: ReactNode;
itemContent: (index: number, data: string) => ReactNode;
}
@@ -44,7 +46,8 @@ interface VirtualizedListProps {
*
* Based on ConversationStore data flow, no dependency on global ChatStore.
*/
-const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, footerSlot, itemContent }) => {
+const VirtualizedList = memo<VirtualizedListProps>(
+ ({ dataSource, footerSlot, headerSlot, itemContent }) => {
const virtuaRef = useRef<VListHandle>(null);
const scrollEndTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const lastUserScrollIntentAtRef = useRef(0);
@@ -244,16 +247,25 @@ const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, footerSlot, it
const overlayHeight = useConversationStore(inputSelectors.chatInputOverlayHeight);
const paddingBottom = Math.max(24, overlayHeight + 12);
- const dataWithFooter = useMemo(
- () => (footerSlot ? [...listData, CONVERSATION_FOOTER_ID] : listData),
- [listData, footerSlot],
+ const dataWithSlots = useMemo(
+ () => [
+ ...(headerSlot ? [CONVERSATION_HEADER_ID] : []),
+ ...listData,
+ ...(footerSlot ? [CONVERSATION_FOOTER_ID] : []),
+ ],
+ [footerSlot, headerSlot, listData],
+ );
+
+ const keepMountedIndicesWithSlots = useMemo(
+ () => (headerSlot ? keepMountedIndices.map((index) => index + 1) : keepMountedIndices),
+ [headerSlot, keepMountedIndices],
);
// Mirror the latest data length into a ref so the scroll-methods registered
// once on mount can read the current total count (including spacer/footer)
// without re-registering on every render.
- const totalCountRef = useRef(dataWithFooter.length);
- totalCountRef.current = dataWithFooter.length;
+ const totalCountRef = useRef(dataWithSlots.length);
+ totalCountRef.current = dataWithSlots.length;
return (
<div
@@ -268,14 +280,21 @@ const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, footerSlot, it
{OPEN_DEV_INSPECTOR && <DebugInspector />}
<VList
bufferSize={typeof window !== 'undefined' ? window.innerHeight : 0}
- data={dataWithFooter}
- keepMounted={keepMountedIndices}
+ data={dataWithSlots}
+ keepMounted={keepMountedIndicesWithSlots}
ref={virtuaRef}
style={{ height: '100%', overflowAnchor: 'none', paddingBottom }}
onScroll={handleScroll}
onScrollEnd={handleScrollEnd}
>
{(messageId, index): ReactElement => {
+ if (messageId === CONVERSATION_HEADER_ID) {
+ return (
+ <WideScreenContainer key={messageId} style={{ position: 'relative' }}>
+ {headerSlot}
+ </WideScreenContainer>
+ );
+ }
if (messageId === CONVERSATION_FOOTER_ID) {
return (
<WideScreenContainer key={messageId} style={{ position: 'relative' }}>
@@ -309,8 +328,9 @@ const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, footerSlot, it
}
const isAgentCouncil = messageId.includes('agentCouncil');
- const isLastItem = index === dataSource.length - 1;
- const content = itemContent(index, messageId);
+ const messageIndex = headerSlot ? index - 1 : index;
+ const isLastItem = messageIndex === dataSource.length - 1;
+ const content = itemContent(messageIndex, messageId);
if (isAgentCouncil) {
// AgentCouncil needs full width for horizontal scroll
diff --git a/src/features/Conversation/ChatList/index.tsx b/src/features/Conversation/ChatList/index.tsx
index b8ca65d4e70..22bf8253e88 100644
--- a/src/features/Conversation/ChatList/index.tsx
+++ b/src/features/Conversation/ChatList/index.tsx
@@ -43,6 +43,11 @@ export interface ChatListProps {
* Used e.g. for the SubAgent read-only hint after the last message.
*/
footerSlot?: ReactNode;
+ /**
+ * Optional content rendered as the first item inside the virtualized list.
+ * It scrolls with messages and does not participate in conversation state.
+ */
+ headerSlot?: ReactNode;
/**
* Custom item renderer. If not provided, uses default ChatItem.
*/
@@ -66,6 +71,7 @@ const ChatList = memo<ChatListProps>(
defaultWorkflowExpandLevel,
disableActionsBar,
footerSlot,
+ headerSlot,
welcome,
itemContent,
showWelcome,
@@ -155,6 +161,7 @@ const ChatList = memo<ChatListProps>(
<VirtualizedList
dataSource={displayMessageIds}
footerSlot={footerSlot}
+ headerSlot={headerSlot}
itemContent={itemContent ?? defaultItemContent}
/>
</MessageActionProvider>
diff --git a/src/features/Onboarding/Agent/Conversation.test.tsx b/src/features/Onboarding/Agent/Conversation.test.tsx
index 2521842b013..a6aa04cec4e 100644
--- a/src/features/Onboarding/Agent/Conversation.test.tsx
+++ b/src/features/Onboarding/Agent/Conversation.test.tsx
@@ -38,15 +38,18 @@ vi.mock('@/features/Conversation', () => ({
return <div data-testid="chat-input" />;
},
ChatList: ({
+ headerSlot,
itemContent,
showWelcome,
welcome,
}: {
+ headerSlot?: ReactNode;
itemContent?: (index: number, id: string) => ReactNode;
showWelcome?: boolean;
welcome?: ReactNode;
}) => (
<div data-testid="chat-list">
+ {headerSlot ? <div data-testid="chat-header">{headerSlot}</div> : null}
{showWelcome ? <div data-testid="chat-welcome">{welcome}</div> : null}
{mockState.displayMessages.map((message, index) => (
<div key={message.id}>{itemContent?.(index, message.id)}</div>
@@ -76,7 +79,11 @@ vi.mock('@/features/Conversation/hooks/useAgentMeta', () => ({
}));
vi.mock('./Welcome', () => ({
- default: () => <div data-testid="welcome-content">Welcome</div>,
+ default: () => <div data-testid="welcome-screen">Welcome screen</div>,
+}));
+
+vi.mock('./WelcomeMessage', () => ({
+ default: () => <div data-testid="welcome-message">Welcome message</div>,
}));
describe('AgentOnboardingConversation', () => {
@@ -103,7 +110,8 @@ describe('AgentOnboardingConversation', () => {
render(<AgentOnboardingConversation />);
expect(screen.getByTestId('chat-welcome')).toBeInTheDocument();
- expect(screen.getByText('Welcome')).toBeInTheDocument();
+ expect(screen.getByText('Welcome screen')).toBeInTheDocument();
+ expect(screen.queryByTestId('chat-header')).not.toBeInTheDocument();
expect(screen.queryByText('finish')).not.toBeInTheDocument();
});
@@ -116,7 +124,34 @@ describe('AgentOnboardingConversation', () => {
render(<AgentOnboardingConversation hasMessages />);
expect(screen.queryByTestId('chat-welcome')).not.toBeInTheDocument();
- expect(screen.queryByText('Welcome')).not.toBeInTheDocument();
+ expect(screen.queryByTestId('chat-header')).not.toBeInTheDocument();
+ expect(screen.queryByText('Welcome screen')).not.toBeInTheDocument();
+ expect(screen.queryByText('Welcome message')).not.toBeInTheDocument();
+ });
+
+ it('keeps the synthetic welcome as the first list item after real messages exist', () => {
+ mockState.displayMessages = [
+ { id: 'user-1', role: 'user' },
+ { id: 'assistant-1', role: 'assistant' },
+ ];
+
+ render(<AgentOnboardingConversation hasMessages />);
+
+ const listItems = screen.getByTestId('chat-list').children;
+ expect(listItems[0]).toHaveAttribute('data-testid', 'chat-header');
+ expect(screen.getByTestId('message-item-user-1')).toBeInTheDocument();
+ expect(screen.getByTestId('message-item-assistant-1')).toBeInTheDocument();
+ });
+
+ it('does not duplicate welcome when a legacy persisted assistant opener exists', () => {
+ mockState.displayMessages = [
+ { id: 'assistant-welcome', role: 'assistant' },
+ { id: 'user-1', role: 'user' },
+ ];
+
+ render(<AgentOnboardingConversation hasMessages />);
+
+ expect(screen.queryByTestId('chat-header')).not.toBeInTheDocument();
});
it('forwards isInputReady=false to ChatInput as isConfigLoading', () => {
diff --git a/src/features/Onboarding/Agent/Conversation.tsx b/src/features/Onboarding/Agent/Conversation.tsx
index 95840c505c0..9669b4a2054 100644
--- a/src/features/Onboarding/Agent/Conversation.tsx
+++ b/src/features/Onboarding/Agent/Conversation.tsx
@@ -26,6 +26,7 @@ import CompletionPanel from './CompletionPanel';
import NameSuggestions from './NameSuggestions';
import Welcome from './Welcome';
import WelcomeMobile from './Welcome.mobile';
+import WelcomeMessage from './WelcomeMessage';
import WrapUpHint from './WrapUpHint';
const assistantLikeRoles = new Set(['assistant', 'assistantGroup', 'supervisor']);
@@ -95,12 +96,10 @@ const AgentOnboardingConversation = memo<AgentOnboardingConversationProps>(
),
);
- // The welcome ("AI opens") is rendered client-side from i18n until the
- // 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.
+ // The welcome is UI-only. It must not be persisted or inserted into LLM
+ // history; otherwise the setup copy can compete with the user's first
+ // actual naming instruction. `hasMessages` prevents the brief messages-fetch
+ // window for returning users from flashing Welcome.
const isGreetingState = useMemo(
() => !hasMessages && displayMessages.length === 0,
[hasMessages, displayMessages],
@@ -167,7 +166,18 @@ const AgentOnboardingConversation = memo<AgentOnboardingConversationProps>(
pendingInterventionCount,
]);
+ const hasPersistedAssistantOpener = displayMessages.at(0)?.role === 'assistant';
+ const shouldShowSyntheticWelcome =
+ !onboardingFinished &&
+ !hasPersistedAssistantOpener &&
+ displayMessages.length > 0;
const shouldShowGreetingWelcome = showGreeting && !onboardingFinished;
+ const shouldShowGreetingActions = showGreeting && !onboardingFinished;
+
+ const syntheticWelcome = useMemo(() => {
+ if (!shouldShowSyntheticWelcome) return undefined;
+ return <WelcomeMessage />;
+ }, [shouldShowSyntheticWelcome]);
const greetingWelcome = useMemo(() => {
if (!shouldShowGreetingWelcome) return undefined;
@@ -198,8 +208,6 @@ const AgentOnboardingConversation = memo<AgentOnboardingConversationProps>(
/>
);
- const listWelcome = greetingWelcome;
-
const itemContent = (index: number, id: string) => {
const isLatestItem = displayMessages.length === index + 1;
@@ -218,9 +226,10 @@ const AgentOnboardingConversation = memo<AgentOnboardingConversationProps>(
<Flexbox flex={1} style={{ overflow: 'hidden' }}>
<ChatList
footerSlot={agentMarketplaceSpacer}
+ headerSlot={syntheticWelcome}
itemContent={itemContent}
showWelcome={shouldShowGreetingWelcome}
- welcome={listWelcome}
+ welcome={greetingWelcome}
/>
</Flexbox>
{!readOnly && !onboardingFinished && (
@@ -230,7 +239,7 @@ const AgentOnboardingConversation = memo<AgentOnboardingConversationProps>(
phase={phase}
onAfterFinish={onAfterWrapUp}
/>
- {shouldShowGreetingWelcome &&
+ {shouldShowGreetingActions &&
(isMobile ? (
<NameSuggestions variant={'chips'} />
) : (
diff --git a/src/features/Onboarding/Agent/WelcomeMessage.tsx b/src/features/Onboarding/Agent/WelcomeMessage.tsx
new file mode 100644
index 00000000000..e3dc6e73651
--- /dev/null
+++ b/src/features/Onboarding/Agent/WelcomeMessage.tsx
@@ -0,0 +1,29 @@
+import { Markdown } from '@lobehub/ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { ChatItem } from '@/features/Conversation/ChatItem';
+import { useAgentMeta } from '@/features/Conversation/hooks';
+
+const WELCOME_MESSAGE_ID = '__onboarding_welcome_message__';
+
+const WelcomeMessage = memo(() => {
+ const { t } = useTranslation('onboarding');
+ const avatar = useAgentMeta();
+
+ return (
+ <ChatItem
+ showTitle
+ avatar={avatar}
+ id={WELCOME_MESSAGE_ID}
+ message={t('agent.welcome')}
+ placement="left"
+ >
+ <Markdown variant="chat">{t('agent.welcome')}</Markdown>
+ </ChatItem>
+ );
+});
+
+WelcomeMessage.displayName = 'OnboardingWelcomeMessage';
+
+export default WelcomeMessage;
diff --git a/src/features/Onboarding/Agent/index.tsx b/src/features/Onboarding/Agent/index.tsx
index 6ababc3f43c..b4fddfa2dae 100644
--- a/src/features/Onboarding/Agent/index.tsx
+++ b/src/features/Onboarding/Agent/index.tsx
@@ -175,11 +175,9 @@ const AgentOnboardingPage = memo(() => {
const orchestration = (async () => {
try {
- const welcomeContent = t('agent.welcome');
const { topicId: serverTopicId, messages } = await userService.sendOnboardingFirstMessage(
{
agentId: onboardingAgentId,
- welcomeContent,
},
);
@@ -214,7 +212,7 @@ const AgentOnboardingPage = memo(() => {
await orchestration;
return false;
},
- [effectiveTopicId, mutate, onBeforeSendMessage, onboardingAgentId, t],
+ [effectiveTopicId, mutate, onBeforeSendMessage, onboardingAgentId],
);
const syncOnboardingContext = useCallback(async () => {
diff --git a/src/server/routers/lambda/user.ts b/src/server/routers/lambda/user.ts
index d7158d75b30..848850c0af1 100644
--- a/src/server/routers/lambda/user.ts
+++ b/src/server/routers/lambda/user.ts
@@ -262,7 +262,7 @@ export const userRouter = router({
}),
sendOnboardingFirstMessage: userProcedure
- .input(z.object({ agentId: z.string().min(1), welcomeContent: z.string() }))
+ .input(z.object({ agentId: z.string().min(1) }))
.mutation(async ({ ctx, input }) => {
const onboardingService = new OnboardingService(ctx.serverDB, ctx.userId);
diff --git a/src/server/services/onboarding/index.test.ts b/src/server/services/onboarding/index.test.ts
index e00a017679c..03aa7f632c3 100644
--- a/src/server/services/onboarding/index.test.ts
+++ b/src/server/services/onboarding/index.test.ts
@@ -255,6 +255,22 @@ describe('OnboardingService', () => {
expect(persistedUserState.settings.general.responseLanguage).toBeUndefined();
});
+ it('does not save agent identity when the proposed agentName matches the user identity', async () => {
+ const service = new OnboardingService(mockDb, userId);
+ const result = await service.saveUserQuestion({
+ agentEmoji: '😀',
+ agentName: 'anbex',
+ fullName: 'anbex',
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.savedFields).toEqual(['fullName']);
+ expect(result.ignoredFields).toEqual(['agentName', 'agentEmoji']);
+ expect(result.content).toContain('Skipped agent identity because agentName matches the user identity');
+ expect(persistedUserState.fullName).toBe('anbex');
+ expect(mockAgentModel.update).not.toHaveBeenCalled();
+ });
+
it('rejects saveUserQuestion when no supported fields are provided', async () => {
const service = new OnboardingService(mockDb, userId);
const result = await service.saveUserQuestion({});
@@ -711,46 +727,35 @@ describe('OnboardingService', () => {
});
describe('sendOnboardingFirstMessage', () => {
- it('creates topic + welcome on first call (happy path)', async () => {
+ it('creates topic without persisting the UI-only welcome on first call', async () => {
const service = new OnboardingService(mockDb, userId);
- mockMessageModel.query.mockResolvedValueOnce([
- { content: 'welcome', id: 'message-1', role: 'assistant' },
- ]);
+ mockMessageModel.query.mockResolvedValueOnce([]);
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(mockMessageModel.findFirstAssistantInTopic).not.toHaveBeenCalled();
+ expect(mockMessageModel.create).not.toHaveBeenCalled();
expect(persistedUserState.agentOnboarding.activeTopicId).toBe('topic-1');
expect(result.topicId).toBe('topic-1');
- expect(result.messages).toHaveLength(1);
+ expect(result.messages).toHaveLength(0);
});
- it('is idempotent — does not double-insert welcome when one already exists', async () => {
+ it('is idempotent when an active topic 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' },
+ { content: 'hello', id: 'message-1', role: 'user' },
]);
const service = new OnboardingService(mockDb, userId);
const result = await service.sendOnboardingFirstMessage({
agentId: 'builtin-agent-1',
- welcomeContent: 'welcome-new',
});
expect(mockTopicModel.create).not.toHaveBeenCalled();
@@ -771,7 +776,6 @@ describe('OnboardingService', () => {
const service = new OnboardingService(mockDb, userId);
await service.sendOnboardingFirstMessage({
agentId: 'builtin-agent-1',
- welcomeContent: 'welcome',
});
expect(executeSpy).toHaveBeenCalledTimes(1);
diff --git a/src/server/services/onboarding/index.ts b/src/server/services/onboarding/index.ts
index 7a07de82f57..386a1fb22b2 100644
--- a/src/server/services/onboarding/index.ts
+++ b/src/server/services/onboarding/index.ts
@@ -90,6 +90,9 @@ const normalizeStringArray = (value: unknown) =>
.filter(Boolean)
: undefined;
+const normalizeComparableName = (value: unknown) =>
+ typeof value === 'string' ? value.trim().toLocaleLowerCase() : undefined;
+
const parseToolArguments = (value?: string) => {
if (!value) return undefined;
@@ -584,13 +587,13 @@ export class OnboardingService {
};
};
- // Atomically create the onboarding topic (if absent) and persist the welcome
- // assistant opener message. Idempotent under concurrent invocation:
+ // Atomically create the onboarding topic (if absent). 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 }) => {
+ // - existing activeTopicId short-circuits topic creation
+ // The UI welcome stays client-only; the user message and assistant response
+ // are created by the existing sendMessage pipeline after this resolves.
+ sendOnboardingFirstMessage = async (input: { agentId: 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.
@@ -600,7 +603,6 @@ export class OnboardingService {
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);
@@ -620,16 +622,6 @@ export class OnboardingService {
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 });
@@ -785,8 +777,19 @@ export class OnboardingService {
typeof parsed.agentEmoji === 'string' && parsed.agentEmoji.trim()
? parsed.agentEmoji.trim()
: undefined;
-
- if (agentName || agentEmoji) {
+ const userIdentityNames = new Set(
+ [fullName, userState.fullName, userState.username]
+ .map((name) => normalizeComparableName(name))
+ .filter((name): name is string => Boolean(name)),
+ );
+ const agentNameMatchesUserIdentity =
+ Boolean(agentName) && userIdentityNames.has(normalizeComparableName(agentName) ?? '');
+ const shouldIgnoreAgentIdentity = Boolean(agentNameMatchesUserIdentity);
+
+ if (shouldIgnoreAgentIdentity) {
+ if (agentName) ignoredFields.push('agentName');
+ if (agentEmoji) ignoredFields.push('agentEmoji');
+ } else if (agentName || agentEmoji) {
try {
const inboxAgentId = await this.getInboxAgentId();
const agentPatch: { avatar?: string; title?: string } = {};
@@ -811,6 +814,15 @@ export class OnboardingService {
}
}
+ if (savedFields.length === 0 && unchangedFields.length === 0 && shouldIgnoreAgentIdentity) {
+ return {
+ content:
+ 'Skipped agent identity because agentName matches the user identity. Ask the user to clarify the assistant name/avatar before saving agentName or agentEmoji.',
+ ignoredFields,
+ success: false,
+ };
+ }
+
if (savedFields.length === 0 && unchangedFields.length === 0) {
return {
content:
@@ -827,6 +839,11 @@ export class OnboardingService {
`Saved ${formatNaturalList(savedFields.map((field) => STRUCTURED_FIELD_LABELS[field]))}.`,
);
}
+ if (shouldIgnoreAgentIdentity) {
+ contentParts.push(
+ 'Skipped agent identity because agentName matches the user identity. Ask the user to clarify the assistant name/avatar before saving agentName or agentEmoji.',
+ );
+ }
if (unchangedFields.length > 0) {
contentParts.push(
diff --git a/src/services/user/index.ts b/src/services/user/index.ts
index c43745fb9df..2195a0b5f04 100644
--- a/src/services/user/index.ts
+++ b/src/services/user/index.ts
@@ -53,7 +53,7 @@ export class UserService {
return lambdaClient.user.getOnboardingBootstrapState.query();
};
- sendOnboardingFirstMessage = async (input: { agentId: string; welcomeContent: string }) => {
+ sendOnboardingFirstMessage = async (input: { agentId: string }) => {
return lambdaClient.user.sendOnboardingFirstMessage.mutate(input);
};