π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(chat): judge the chat input model notice against the topic-pinned model (#19764)
Arvin Xua2b8368e795c
diff --git a/src/features/ChatInput/ChatInputNotice/useChatInputNotice.test.tsx b/src/features/ChatInput/ChatInputNotice/useChatInputNotice.test.tsxindex 3134f4322ca..2ac118c829a 100644--- a/src/features/ChatInput/ChatInputNotice/useChatInputNotice.test.tsx+++ b/src/features/ChatInput/ChatInputNotice/useChatInputNotice.test.tsx@@ -40,6 +40,16 @@ const testState = vi.hoisted(() => ({selectModel: vi.fn(async () => {}),selectionPolicy: 'fixed' as 'fixed' | 'member',},+ /** What the host composer published about its own conversation. */+ chatInput: {+ topicId: undefined as string | null | undefined,+ },+ /** Chat store slice the notice reads for the topic-scoped model pin. */+ chat: {+ activeTopicId: undefined as string | undefined,+ topics: {} as Record<string, { model?: string; provider?: string }>,+ updateTopicModel: vi.fn(async () => {}),+ },aiInfra: {builtinAiModelList: [] as TestBuiltinModel[],enabledChatModelList: [] as TestProviderWithModels[],@@ -94,6 +104,11 @@ vi.mock('@/features/ChatInput/hooks/useAgentModelSelection', () => ({}),}));+vi.mock('@/features/ChatInput/store', () => ({+ useChatInputStore: <T,>(selector: StoreSelector<T, typeof testState.chatInput>) =>+ selector(testState.chatInput),+}));+vi.mock('@/features/ChatInput/hooks/useChatInputResourceAccess', () => ({useChatInputResourceAccess: () => testState.resourceAccess,}));@@ -122,6 +137,22 @@ vi.mock('@/store/agent/selectors', () => ({},}));+vi.mock('@/store/chat', () => ({+ useChatStore: <T,>(selector: StoreSelector<T, typeof testState.chat>) => selector(testState.chat),+}));++vi.mock('@/store/chat/slices/topic/selectors', () => ({+ topicSelectors: {+ getTopicById: (id: string) => (s: typeof testState.chat) => s.topics[id],+ getTopicModelById: (id: string) => (s: typeof testState.chat) => {+ const topic = s.topics[id];+ if (!topic?.model) return undefined;++ return { model: topic.model, provider: topic.provider || '' };+ },+ },+}));+vi.mock('@/store/aiInfra', () => ({aiProviderSelectors: {isInitAiProviderRuntimeState: (s: typeof testState.aiInfra) => s.isInitAiProviderRuntimeState,@@ -148,6 +179,12 @@ describe('useChatInputNotice', () => {};testState.agent.model = 'gpt-4o';testState.agent.provider = 'openai';+ testState.chatInput = { topicId: undefined };+ testState.chat = {+ activeTopicId: undefined,+ topics: {},+ updateTopicModel: vi.fn(async () => {}),+ };testState.aiInfra.builtinAiModelList = [];testState.aiInfra.enabledChatModelList = [];testState.aiInfra.enabledAiProviders = [];@@ -488,6 +525,147 @@ describe('useChatInputNotice', () => {expect(result.current).toBeUndefined();});+ it('judges the topic-pinned model rather than the disabled agent default', () => {+ // A topic pins its own model (`topics.model`), and that pin is what runs β+ // a retired agent default behind it must not raise a notice.+ testState.aiInfra.isInitAiProviderRuntimeState = true;+ testState.agent.model = 'gpt-4-32k';+ testState.chat.activeTopicId = 'topic-1';+ testState.chat.topics = { 'topic-1': { model: 'gpt-4o', provider: 'openai' } };+ testState.aiInfra.builtinAiModelList = [+ { id: 'gpt-4-32k', providerId: 'openai', type: 'chat' },+ ];+ testState.aiInfra.enabledAiProviders = [{ id: 'openai' }];+ testState.aiInfra.enabledChatModelList = [+ { children: [{ abilities: { functionCall: true }, id: 'gpt-4o' }], id: 'openai' },+ ];++ const { result } = renderHook(() => useChatInputNotice());++ expect(result.current).toBeUndefined();+ });++ it('offers to enable the disabled model a topic pinned over a live agent default', () => {+ testState.aiInfra.isInitAiProviderRuntimeState = true;+ testState.chat.activeTopicId = 'topic-1';+ testState.chat.topics = { 'topic-1': { model: 'gpt-4-32k', provider: 'openai' } };+ testState.aiInfra.builtinAiModelList = [+ { id: 'gpt-4-32k', providerId: 'openai', type: 'chat' },+ ];+ testState.aiInfra.enabledAiProviders = [{ id: 'openai' }];+ // The agent default is perfectly fine β only the topic pin is disabled.+ testState.aiInfra.enabledChatModelList = [+ { children: [{ abilities: { functionCall: true }, id: 'gpt-4o' }], id: 'openai' },+ ];++ const { result } = renderHook(() => useChatInputNotice());++ expect(result.current).toMatchObject({ action: 'enableModel', key: 'input.modelDisabled' });+ });++ it('repairs the active topic instead of the agent when the fallback provider differs', async () => {+ testState.aiInfra.isInitAiProviderRuntimeState = true;+ testState.chat.activeTopicId = 'topic-1';+ testState.chat.topics = { 'topic-1': { model: 'gpt-4o', provider: 'removed-provider' } };+ testState.aiInfra.builtinAiModelList = [{ id: 'gpt-4o', providerId: 'openai', type: 'chat' }];++ const { result } = renderHook(() => useChatInputNotice());++ await act(async () => result.current?.onAction?.());++ expect(testState.aiInfra.toggleProviderModelEnabled).toHaveBeenCalledWith({+ enabled: true,+ id: 'gpt-4o',+ providerId: 'openai',+ type: 'chat',+ });+ expect(testState.chat.updateTopicModel).toHaveBeenCalledWith('topic-1', {+ model: 'gpt-4o',+ provider: 'openai',+ });+ expect(testState.agentModelSelection.selectModel).not.toHaveBeenCalled();+ });++ it('does not warn while the active topic row has not loaded yet', () => {+ // Cold load with a topic in the URL: the pin is unknown, so the agent+ // default must not be judged in its place.+ testState.aiInfra.isInitAiProviderRuntimeState = true;+ testState.agent.model = 'gpt-4-32k';+ testState.chat.activeTopicId = 'topic-1';+ testState.chat.topics = {};++ const { result } = renderHook(() => useChatInputNotice());++ expect(result.current).toBeUndefined();+ });++ it('ignores the global active topic when its own conversation has none', () => {+ // A page copilot embedded next to another chat runs with `topicId: null`+ // while the outer chat's topic is still the global one β judging that topic+ // would warn about a model this composer never runs.+ testState.aiInfra.isInitAiProviderRuntimeState = true;+ testState.chatInput.topicId = null;+ testState.chat.activeTopicId = 'outer-topic';+ testState.chat.topics = { 'outer-topic': { model: 'gpt-4-32k', provider: 'openai' } };+ testState.aiInfra.builtinAiModelList = [+ { id: 'gpt-4-32k', providerId: 'openai', type: 'chat' },+ ];+ testState.aiInfra.enabledAiProviders = [{ id: 'openai' }];+ testState.aiInfra.enabledChatModelList = [+ { children: [{ abilities: { functionCall: true }, id: 'gpt-4o' }], id: 'openai' },+ ];++ const { result } = renderHook(() => useChatInputNotice());++ expect(result.current).toBeUndefined();+ });++ it('repairs its own conversation topic rather than the global active one', async () => {+ testState.aiInfra.isInitAiProviderRuntimeState = true;+ testState.chatInput.topicId = 'own-topic';+ testState.chat.activeTopicId = 'outer-topic';+ testState.chat.topics = {+ 'outer-topic': { model: 'gpt-4o', provider: 'openai' },+ 'own-topic': { model: 'gpt-4o', provider: 'removed-provider' },+ };+ testState.aiInfra.builtinAiModelList = [{ id: 'gpt-4o', providerId: 'openai', type: 'chat' }];++ const { result } = renderHook(() => useChatInputNotice());++ await act(async () => result.current?.onAction?.());++ expect(testState.chat.updateTopicModel).toHaveBeenCalledWith('own-topic', {+ model: 'gpt-4o',+ provider: 'openai',+ });+ });++ it('judges an unlisted conversation topic by its agent default instead of waiting on it', async () => {+ // A document's chat panel runs on a system topic the sidebar never lists,+ // so its row never lands in the store β waiting on it would hide the notice+ // forever, even with the agent default genuinely disabled.+ testState.aiInfra.isInitAiProviderRuntimeState = true;+ testState.chatInput.topicId = 'doc-topic';+ testState.chat.activeTopicId = 'outer-topic';+ testState.chat.topics = { 'outer-topic': { model: 'gpt-4o', provider: 'openai' } };+ testState.agent.provider = 'removed-provider';+ testState.aiInfra.builtinAiModelList = [{ id: 'gpt-4o', providerId: 'openai', type: 'chat' }];++ const { result } = renderHook(() => useChatInputNotice());++ expect(result.current).toMatchObject({ action: 'enableModel', key: 'input.modelDisabled' });++ await act(async () => result.current?.onAction?.());++ // It judged the agent default, so the repair lands on the agent, not on a+ // topic pin it never saw.+ expect(testState.agentModelSelection.selectModel).toHaveBeenCalledWith({+ model: 'gpt-4o',+ provider: 'openai',+ });+ expect(testState.chat.updateTopicModel).not.toHaveBeenCalled();+ });+it('does not return a model notice for heterogeneous agents', () => {testState.agent.agencyConfig = { heterogeneousProvider: { type: 'codex' } };testState.aiInfra.isInitAiProviderRuntimeState = true;diff --git a/src/features/ChatInput/ChatInputNotice/useChatInputNotice.ts b/src/features/ChatInput/ChatInputNotice/useChatInputNotice.tsindex 5d11bc1cc3a..ae345f4aa5e 100644--- a/src/features/ChatInput/ChatInputNotice/useChatInputNotice.ts+++ b/src/features/ChatInput/ChatInputNotice/useChatInputNotice.ts@@ -5,6 +5,7 @@ import { useTranslation } from 'react-i18next';import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';import { useAgentModelSelection } from '@/features/ChatInput/hooks/useAgentModelSelection';import { useChatInputResourceAccess } from '@/features/ChatInput/hooks/useChatInputResourceAccess';+import { useTopicId } from '@/features/ChatInput/hooks/useTopicId';import {resolveEnableTargetProviderId,resolveStaleModelState,@@ -14,11 +15,13 @@ import { usePermission } from '@/hooks/usePermission';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';import { aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';+import { useChatStore } from '@/store/chat';+import { topicSelectors } from '@/store/chat/slices/topic/selectors';import { type EnabledProviderWithModels } from '@/types/aiProvider';interface ResolveChatInputNoticeParams {currentChatModel?: unknown;- isAgentModelPending: boolean;+ isEffectiveModelPending: boolean;isGroupContext?: boolean;isHeterogeneousAgent: boolean;isModelConfigReady: boolean;@@ -38,7 +41,7 @@ const findEnabledChatModel = (export const resolveChatInputNotice = ({currentChatModel,- isAgentModelPending,+ isEffectiveModelPending,isGroupContext,isHeterogeneousAgent,isModelDisabled,@@ -55,17 +58,18 @@ export const resolveChatInputNotice = ({} as const;// Model-config notices don't apply to heterogeneous agents (own toolchain),- // before the model runtime config is ready, or before the agent's effective- // model is settled. The last one matters on a cold page load: until- // `agentMap` has the agent (and, for a member-selection workspace agent,- // until the member override is fetched), the model resolves to the- // DEFAULT_MODEL/DEFAULT_PROVIDER fallback, which is often absent from the- // user's enabled list β that used to flash the "model offline" warning for a- // frame before the real config resolved.+ // before the model runtime config is ready, or before the effective model is+ // settled. The last one matters on a cold page load: until `agentMap` has the+ // agent (and, for a member-selection workspace agent, until the member+ // override is fetched, and for a topic-pinned model until the topic row is+ // loaded), the model resolves to the DEFAULT_MODEL/DEFAULT_PROVIDER fallback+ // or the agent default, which is often absent from the user's enabled list β+ // that used to flash the "model offline" warning for a frame before the real+ // config resolved.if (!isHeterogeneousAgent &&isModelConfigReady &&- !isAgentModelPending && // Example: an agent still references `gpt-4-32k`, or a model reclassified to+ !isEffectiveModelPending && // Example: an agent still references `gpt-4-32k`, or a model reclassified to// image/video; once absent from the chat selector, it should read as unavailable.!currentChatModel) {@@ -108,8 +112,39 @@ export const useChatInputNotice = (): ChatInputNotice | undefined => {// Same source as the model trigger renders, so the notice can never judge a// different model than the one the user sees (member overrides included).- const { canSelectModel, isPreferenceLoading, model, provider, selectModel, selectionPolicy } =- useAgentModelSelection(agentId);+ const {+ canSelectModel,+ isPreferenceLoading,+ model: agentModel,+ provider: agentProvider,+ selectModel,+ selectionPolicy,+ } = useAgentModelSelection(agentId);++ // β¦and the trigger resolves topic-first: a topic pins its own model+ // (`topics.model`), which outranks the agent default for everything that+ // actually runs (see `useEffectiveModel`). Judging the agent model here+ // warned "the current model is disabled" over a perfectly usable topic model,+ // and its Enable action then repaired the agent row nobody was using.+ // The topic comes from this composer's own conversation, never the global+ // active topic β see `useTopicId`.+ const topicId = useTopicId();+ const topicModel = useChatStore((s) =>+ topicId ? topicSelectors.getTopicModelById(topicId)(s) : undefined,+ );+ const hasTopicRow = useChatStore((s) => !!topicId && !!topicSelectors.getTopicById(topicId)(s));+ const updateTopicModel = useChatStore((s) => s.updateTopicModel);+ // The main chat's topic row arrives with the sidebar list (or its detail+ // fetch) a beat after the route makes it active; until then it reads as "no+ // pin" and would fall back to the agent default β the same cold-load flash as+ // above. Only that topic is worth waiting on: a host-owned topic that is never+ // listed (a document's chat panel is a system topic) would otherwise suppress+ // the notice for good, so it is judged by its agent default instead.+ const isActiveTopicPending = useChatStore(+ (s) => !!topicId && topicId === s.activeTopicId && !topicSelectors.getTopicById(topicId)(s),+ );+ const model = topicModel?.model ?? agentModel;+ const provider = topicModel?.model ? topicModel.provider : agentProvider;// `isPreferenceLoading` is true for every workspace agent while the shared// preferences request is in flight, but the override only feeds the@@ -164,7 +199,8 @@ export const useChatInputNotice = (): ChatInputNotice | undefined => {const notice = resolveChatInputNotice({currentChatModel,- isAgentModelPending: isAgentConfigLoading || isMemberOverridePending,+ isEffectiveModelPending:+ isAgentConfigLoading || isMemberOverridePending || isActiveTopicPending,isGroupContext,isHeterogeneousAgent,isModelDisabled,@@ -189,7 +225,13 @@ export const useChatInputNotice = (): ChatInputNotice | undefined => {});if (providerId !== provider) {try {- await selectModel({ model, provider: providerId });+ // Re-point the row the judged model came from, the way the model+ // trigger's own switch routes: this conversation's topic when its row+ // is known, the agent (or member override) otherwise β an unlisted+ // topic was judged by its agent default, so that is what gets fixed.+ if (topicId && hasTopicRow)+ await updateTopicModel(topicId, { model, provider: providerId });+ else await selectModel({ model, provider: providerId });} catch (error) {console.error('Failed to select the enabled chat model provider:', error);toast.error(t('input.modelDisabled.selectionFailed'));@@ -204,12 +246,15 @@ export const useChatInputNotice = (): ChatInputNotice | undefined => {}, [enableTargetProviderId,enabledChatModelList,+ hasTopicRow,model,provider,selectModel,t,toggleProviderEnabled,toggleProviderModelEnabled,+ topicId,+ updateTopicModel,]);if (notice?.action !== 'enableModel') return notice;diff --git a/src/features/ChatInput/ChatInputProvider.tsx b/src/features/ChatInput/ChatInputProvider.tsxindex 721b7270700..7d5abd8add6 100644--- a/src/features/ChatInput/ChatInputProvider.tsx+++ b/src/features/ChatInput/ChatInputProvider.tsx@@ -35,6 +35,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(slashPlacement,getMessages,resolveSendBlocked,+ topicId,}) => {const editor = useEditor();const slashMenuRef = useRef<HTMLDivElement>(null);@@ -59,6 +60,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(sendMenu,slashMenuRef,slashPlacement,+ topicId,})}>@@ -80,6 +82,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(sendButtonProps={sendButtonProps}sendMenu={sendMenu}slashPlacement={slashPlacement}+ topicId={topicId}onMarkdownContentChange={onMarkdownContentChange}onSend={onSend}onVoiceMessageSend={onVoiceMessageSend}diff --git a/src/features/ChatInput/StoreUpdater.tsx b/src/features/ChatInput/StoreUpdater.tsxindex 6df8a785638..c37052b9ee5 100644--- a/src/features/ChatInput/StoreUpdater.tsx+++ b/src/features/ChatInput/StoreUpdater.tsx@@ -36,12 +36,14 @@ const StoreUpdater = memo<StoreUpdaterProps>(slashPlacement,getMessages,resolveSendBlocked,+ topicId,}) => {const storeApi = useStoreApi();const useStoreUpdater = createStoreUpdater(storeApi);const editor = useChatInputEditor();useStoreUpdater('agentId', agentId);+ useStoreUpdater('topicId', topicId);useStoreUpdater('canRecordVoiceMessage', canRecordVoiceMessage);useStoreUpdater('contextSelectionKey', contextSelectionKey);useStoreUpdater('contextWindowMessages', contextWindowMessages);diff --git a/src/features/ChatInput/hooks/useTopicId.ts b/src/features/ChatInput/hooks/useTopicId.tsnew file mode 100644index 00000000000..230ca43756f--- /dev/null+++ b/src/features/ChatInput/hooks/useTopicId.ts@@ -0,0 +1,28 @@+'use client';++import { useChatStore } from '@/store/chat';++import { useChatInputStore } from '../store';++/**+ * The topic this ChatInput belongs to.+ *+ * Hosts that own a conversation publish their own topic into the ChatInput+ * store (see `Conversation/ChatInput`), including `null` when that conversation+ * deliberately has no topic β a page copilot embedded beside another chat keeps+ * `topicId: null` while the outer chat's topic is still the global+ * `activeTopicId`, so reading the global id there would bind the composer to an+ * unrelated topic and let its controls write to it.+ *+ * Hosts without a conversation of their own (the Home composer, standalone+ * editors) provide nothing, and fall back to the global active topic the way+ * they always have.+ */+export const useTopicId = (): string | null => {+ const topicIdFromChatInput = useChatInputStore((s) => s.topicId);+ const activeTopicId = useChatStore((s) => s.activeTopicId);++ // `null` is a valid value ("this conversation has no topic") and must NOT+ // fall back, the same distinction `useAgentId` makes for an empty agentId.+ return topicIdFromChatInput !== undefined ? topicIdFromChatInput : (activeTopicId ?? null);+};diff --git a/src/features/ChatInput/store/initialState.ts b/src/features/ChatInput/store/initialState.tsindex 360a05c90be..43b800624b5 100644--- a/src/features/ChatInput/store/initialState.ts+++ b/src/features/ChatInput/store/initialState.ts@@ -89,6 +89,16 @@ export interface PublicState {* Slash menu placement: 'bottom' for home page (input in center), 'top' for page input (at bottom)*/slashPlacement?: SlashPlacement;+ /**+ * The topic this composer belongs to, as its host conversation resolves it β+ * `null` when the host has a conversation with no topic (a page copilot+ * embedded beside another chat, a not-yet-created topic). Left `undefined` by+ * hosts that have no conversation of their own, which fall back to the global+ * `activeTopicId` (see `useTopicId`). Never read the global id directly from+ * a composer control: an embedded conversation can run against a different+ * topic than the surrounding page.+ */+ topicId?: string | null;}export interface State extends PublicState {diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsxindex 71d813c32a4..ff7f031353b 100644--- a/src/features/Conversation/ChatInput/index.tsx+++ b/src/features/Conversation/ChatInput/index.tsx@@ -191,12 +191,20 @@ const ChatInput = memo<ChatInputProps>(const context = useConversationStore((s) => s.context);const contextKey = useMemo(() => messageMapKey(context), [context]);const canRecordVoiceMessage = useCanSendVoiceMessage(context);- const [agentId, inputMessage, sendMessage, stopGenerating] = useConversationStore((s) => [- s.context.agentId,- s.inputMessage,- s.sendMessage,- s.stopGenerating,- ]);+ // The composer's controls must resolve their topic from THIS conversation,+ // not the global `activeTopicId`: a page copilot embedded next to another+ // chat runs with `topicId: null` while the outer chat's topic is still the+ // global one (see PageAgentProvider). `null` is meaningful β it means "this+ // conversation has no topic" β so it is passed through as-is.+ const [agentId, topicId, inputMessage, sendMessage, stopGenerating] = useConversationStore(+ (s) => [+ s.context.agentId,+ s.context.topicId ?? null,+ s.inputMessage,+ s.sendMessage,+ s.stopGenerating,+ ],+ );const [enableHistoryCount, historyCount] = useAgentStore((s) => [chatConfigByIdSelectors.getEnableHistoryCountById(agentId || '')(s),chatConfigByIdSelectors.getHistoryCountById(agentId || '')(s),@@ -515,6 +523,7 @@ const ChatInput = memo<ChatInputProps>(sendButtonProps={sendButtonProps}sendMenu={showSendMenu ? sendMenu : undefined}slashPlacement="top"+ topicId={topicId}chatInputEditorRef={(instance) => {if (instance) {setEditor(instance);