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(agent): stop background config fetch from hijacking the active agent (#15862)

Arvin Xu2df87284cbad
diff --git a/src/features/AgentHome/AgentInfo.tsx b/src/features/AgentHome/AgentInfo.tsx
index 8feb27fd220..76878b2746c 100644
--- a/src/features/AgentHome/AgentInfo.tsx
+++ b/src/features/AgentHome/AgentInfo.tsx
@@ -6,17 +6,26 @@ import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { DEFAULT_AVATAR, DEFAULT_INBOX_AVATAR } from '@/const/meta';
+import { contextSelectors, useConversationStore } from '@/features/Conversation/store';
import { useAgentStore } from '@/store/agent';
-import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
+import { agentByIdSelectors, agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
import { useUserStore } from '@/store/user';
import { userGeneralSettingsSelectors } from '@/store/user/slices/settings/selectors';
const AgentInfo = memo(() => {
const { t } = useTranslation(['chat', 'welcome']);
- const isLoading = useAgentStore(agentSelectors.isAgentConfigLoading);
- const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);
- const meta = useAgentStore(agentSelectors.currentAgentMeta, isEqual);
- const openingMessage = useAgentStore(agentSelectors.openingMessage);
+ // Scope the welcome to the conversation's agent, not the global
+ // `activeAgentId`. In the multi-tab desktop app `activeAgentId` is shared and
+ // can momentarily point at another tab's agent (or the inbox), which used to
+ // flash this card back to the inbox "Lobe AI" identity.
+ const agentId = useConversationStore(contextSelectors.agentId) || '';
+ const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
+ const isInbox = !!inboxAgentId && agentId === inboxAgentId;
+ const isLoading = useAgentStore(agentByIdSelectors.isAgentConfigLoadingById(agentId));
+ const meta = useAgentStore(agentSelectors.getAgentMetaById(agentId), isEqual);
+ const openingMessage = useAgentStore(
+ (s) => agentSelectors.getAgentConfigById(agentId)(s)?.openingMessage || '',
+ );
const fontSize = useUserStore(userGeneralSettingsSelectors.fontSize);
const displayTitle = isInbox
diff --git a/src/routes/(main)/agent/features/Conversation/AgentWelcome/OpeningQuestions.tsx b/src/routes/(main)/agent/features/Conversation/AgentWelcome/OpeningQuestions.tsx
deleted file mode 100644
index 14861d38592..00000000000
--- a/src/routes/(main)/agent/features/Conversation/AgentWelcome/OpeningQuestions.tsx
+++ /dev/null
@@ -1,67 +0,0 @@
-'use client';
-
-import { Block, Flexbox } from '@lobehub/ui';
-import { createStaticStyles, responsive } from 'antd-style';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { useConversationStore } from '@/features/Conversation';
-
-const styles = createStaticStyles(({ css, cssVar }) => ({
- card: css`
- padding-block: 8px;
- padding-inline: 16px;
- border-radius: 48px;
-
- ${responsive.sm} {
- padding-block: 8px;
- padding-inline: 16px;
- }
- `,
-
- container: css`
- padding-block: 0;
- padding-inline: 0;
- `,
-
- title: css`
- color: ${cssVar.colorTextDescription};
- `,
-}));
-
-interface OpeningQuestionsProps {
- mobile?: boolean;
- questions: string[];
-}
-
-const OpeningQuestions = memo<OpeningQuestionsProps>(({ mobile, questions }) => {
- const { t } = useTranslation('welcome');
- const [sendMessage] = useConversationStore((s) => [s.sendMessage]);
-
- return (
- <div className={styles.container}>
- <p className={styles.title}>{t('guide.questions.title')}</p>
- <Flexbox horizontal gap={8} wrap={'wrap'}>
- {questions.slice(0, mobile ? 2 : 5).map((question) => {
- return (
- <Block
- clickable
- className={styles.card}
- key={question}
- paddingBlock={8}
- paddingInline={12}
- variant={'filled'}
- onClick={() => {
- sendMessage({ message: question });
- }}
- >
- {question}
- </Block>
- );
- })}
- </Flexbox>
- </div>
- );
-});
-
-export default OpeningQuestions;
diff --git a/src/routes/(main)/agent/features/Conversation/AgentWelcome/index.tsx b/src/routes/(main)/agent/features/Conversation/AgentWelcome/index.tsx
deleted file mode 100644
index a14e684360d..00000000000
--- a/src/routes/(main)/agent/features/Conversation/AgentWelcome/index.tsx
+++ /dev/null
@@ -1,73 +0,0 @@
-'use client';
-
-import { Avatar, Flexbox, Markdown, Text } from '@lobehub/ui';
-import isEqual from 'fast-deep-equal';
-import React, { memo, useMemo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { DEFAULT_AVATAR, DEFAULT_INBOX_AVATAR } from '@/const/meta';
-import { useIsMobile } from '@/hooks/useIsMobile';
-import { useAgentStore } from '@/store/agent';
-import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
-import { useUserStore } from '@/store/user';
-import { userGeneralSettingsSelectors } from '@/store/user/selectors';
-
-import OpeningQuestions from './OpeningQuestions';
-import ToolAuthAlert from './ToolAuthAlert';
-
-const InboxWelcome = memo(() => {
- const { t } = useTranslation(['welcome', 'chat']);
- const mobile = useIsMobile();
- const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);
- const openingQuestions = useAgentStore(agentSelectors.openingQuestions, isEqual);
- const fontSize = useUserStore(userGeneralSettingsSelectors.fontSize);
- const meta = useAgentStore(agentSelectors.currentAgentMeta, isEqual);
-
- const agentSystemRoleMsg = t('agentDefaultMessageWithSystemRole', {
- name: meta.title || t('defaultAgent', { ns: 'chat' }),
- ns: 'chat',
- });
- const openingMessage = useAgentStore(agentSelectors.openingMessage);
-
- const message = useMemo(() => {
- if (openingMessage) return openingMessage;
- return agentSystemRoleMsg;
- }, [openingMessage, agentSystemRoleMsg, meta.description]);
-
- const inboxTitle = meta.title || 'Lobe AI';
- const displayTitle = isInbox ? inboxTitle : meta.title || t('defaultSession', { ns: 'common' });
-
- return (
- <>
- <Flexbox flex={1} />
- <Flexbox
- gap={12}
- width={'100%'}
- style={{
- paddingBottom: 'max(10vh, 32px)',
- }}
- >
- <Avatar
- avatar={isInbox ? meta.avatar || DEFAULT_INBOX_AVATAR : meta.avatar || DEFAULT_AVATAR}
- background={meta.backgroundColor}
- shape={'square'}
- size={78}
- />
- <Text fontSize={32} weight={'bold'}>
- {displayTitle}
- </Text>
- <Flexbox width={'min(100%, 640px)'}>
- <Markdown fontSize={fontSize} variant={'chat'}>
- {isInbox ? t('guide.defaultMessageWithoutCreate', { appName: inboxTitle }) : message}
- </Markdown>
- </Flexbox>
- {openingQuestions.length > 0 && (
- <OpeningQuestions mobile={mobile} questions={openingQuestions} />
- )}
- <ToolAuthAlert />
- </Flexbox>
- </>
- );
-});
-
-export default InboxWelcome;
diff --git a/src/store/agent/slices/agent/action.test.ts b/src/store/agent/slices/agent/action.test.ts
index fea6ef3b7ac..151c397955b 100644
--- a/src/store/agent/slices/agent/action.test.ts
+++ b/src/store/agent/slices/agent/action.test.ts
@@ -155,6 +155,48 @@ describe('AgentSlice Actions', () => {
});
});
+ describe('useFetchAgentConfig', () => {
+ it('adopts the fetched agent as active when none is active yet', async () => {
+ vi.mocked(agentService.getAgentConfigById).mockResolvedValue({
+ id: 'agent-1',
+ title: 'Setup',
+ } as any);
+
+ const { result } = renderHook(() => useAgentStore(), { wrapper: withSWR });
+
+ renderHook(() => result.current.useFetchAgentConfig(true, 'agent-1'), { wrapper: withSWR });
+
+ await waitFor(() => {
+ expect(result.current.agentMap['agent-1']).toMatchObject({ id: 'agent-1', title: 'Setup' });
+ });
+ expect(result.current.activeAgentId).toBe('agent-1');
+ });
+
+ it('does not hijack activeAgentId when another agent is already active', async () => {
+ // The active agent is owned by the route-level sync; simulate the routed agent.
+ useAgentStore.setState({ activeAgentId: 'routed-agent' });
+
+ vi.mocked(agentService.getAgentConfigById).mockResolvedValue({
+ id: 'inbox-agent',
+ title: 'Lobe AI',
+ } as any);
+
+ const { result } = renderHook(() => useAgentStore(), { wrapper: withSWR });
+
+ // A background / secondary config fetch for a different agent (e.g. the
+ // inbox config requested by the home input or another open tab).
+ renderHook(() => result.current.useFetchAgentConfig(true, 'inbox-agent'), {
+ wrapper: withSWR,
+ });
+
+ await waitFor(() => {
+ expect(result.current.agentMap['inbox-agent']).toMatchObject({ id: 'inbox-agent' });
+ });
+ // The background fetch only populates agentMap; it must not steal the active agent.
+ expect(result.current.activeAgentId).toBe('routed-agent');
+ });
+ });
+
describe('invalidateAvailableAgents', () => {
it('should clear cached available agents', () => {
const { result } = renderHook(() => useAgentStore());
diff --git a/src/store/agent/slices/agent/action.ts b/src/store/agent/slices/agent/action.ts
index 93fa0424421..9121c686982 100644
--- a/src/store/agent/slices/agent/action.ts
+++ b/src/store/agent/slices/agent/action.ts
@@ -299,7 +299,17 @@ export class AgentSliceActionImpl {
onData: (data) => {
if (!data) return;
this.#get().internal_dispatchAgentMap(agentId, data);
- this.#set({ activeAgentId: data.id }, false, 'fetchAgentConfig');
+ // Only adopt the fetched agent as the active one when nothing is
+ // active yet. The active agent is owned by the route-level sync
+ // (AgentIdSync on desktop/mobile, the popup pages' own setState).
+ // A background or secondary config fetch β€” e.g. the inbox config
+ // requested by the home input, a side-panel copilot, or another
+ // open tab β€” must NOT hijack `activeAgentId` away from the routed
+ // agent, which would otherwise flash the conversation header/welcome
+ // back to the inbox ("Lobe AI") agent.
+ if (!this.#get().activeAgentId) {
+ this.#set({ activeAgentId: data.id }, false, 'fetchAgentConfig');
+ }
this.#clearAgentConfigError(agentId);
},
onError: (error) => {