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(chat-input): judge the context window ring and agent mode by the topic-pinned model (#20933)

Mocha8b816a41c1d9
diff --git a/src/features/AgentTasks/features/TaskExecutionControls.tsx b/src/features/AgentTasks/features/TaskExecutionControls.tsx
index ff203b89caa..ab261be5595 100644
--- a/src/features/AgentTasks/features/TaskExecutionControls.tsx
+++ b/src/features/AgentTasks/features/TaskExecutionControls.tsx
@@ -13,18 +13,16 @@ import { FolderIcon } from 'lucide-react';
import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { useEffectiveAgentMode } from '@/features/ChatInput/hooks/useEffectiveAgentMode';
import {
getWorkingDirectoryName,
getWorkingDirectoryPathString,
} from '@/helpers/workingDirectoryPath';
-import { useAgentStore } from '@/store/agent';
-import { agentByIdSelectors } from '@/store/agent/selectors';
import TaskDeviceChip from './TaskDeviceChip';
import { taskExecutionStyles as styles } from './taskExecutionStyles';
import TaskRepoChip from './TaskRepoChip';
import TaskWorkingDirectoryChip from './TaskWorkingDirectoryChip';
+import { useTaskExecutionAvailability } from './useTaskExecutionAvailability';
import { useTaskRunTarget } from './useTaskRunTarget';
interface TaskExecutionControlsProps {
@@ -65,12 +63,7 @@ const TaskExecutionControlsInner = memo<
Omit<TaskExecutionControlsProps, 'assigneeAgentId'> & { assigneeAgentId: string }
>(({ assigneeAgentId, disabled, onChange, value }) => {
const { t } = useTranslation('chat');
- const isHetero = useAgentStore(agentByIdSelectors.isAgentHeterogeneousById(assigneeAgentId));
- const { isAgentRuntimeMode, isPreferenceLoading } = useEffectiveAgentMode(assigneeAgentId);
- // Heterogeneous agents always execute somewhere; a plain agent only has an
- // execution environment in agent mode (chat mode means "no tools, no device").
- // Same gate the chat composer uses for this cluster.
- const canExecuteSomewhere = isHetero || isAgentRuntimeMode;
+ const canExecuteSomewhere = useTaskExecutionAvailability(assigneeAgentId);
const target = useTaskRunTarget(assigneeAgentId, value?.boundDeviceId);
@@ -113,7 +106,7 @@ const TaskExecutionControlsInner = memo<
[emit, target.deviceId, value],
);
- if (isPreferenceLoading || !canExecuteSomewhere) return null;
+ if (!canExecuteSomewhere) return null;
// What the run actually starts in: the task's own choice first, then the
// chain the runtime falls back to. Shown as the muted hint so "inherit" is
diff --git a/src/features/AgentTasks/features/useTaskExecutionAvailability.test.ts b/src/features/AgentTasks/features/useTaskExecutionAvailability.test.ts
new file mode 100644
index 00000000000..be3288f5f69
--- /dev/null
+++ b/src/features/AgentTasks/features/useTaskExecutionAvailability.test.ts
@@ -0,0 +1,103 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useTaskExecutionAvailability } from './useTaskExecutionAvailability';
+
+interface ModelPin {
+ model: string;
+ provider: string;
+}
+
+const state = vi.hoisted(() => ({
+ agentModel: { model: 'agent-model', provider: 'agent-provider' } as ModelPin,
+ isPreferenceLoading: false,
+ toolUseModels: [] as ModelPin[],
+ topicModel: undefined as ModelPin | undefined,
+}));
+
+vi.mock('@/features/ChatInput/hooks/effectiveAgentModePreference', () => ({
+ useEffectiveAgentModePreference: () => ({
+ enableAgentMode: true,
+ isPreferenceLoading: state.isPreferenceLoading,
+ usesWorkspaceMemberMode: false,
+ }),
+}));
+
+// Store boundary: the real agent, topic and model selectors run against these states.
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (s: object) => unknown) =>
+ selector({
+ activeAgentId: 'agent-1',
+ agentMap: { 'agent-1': { ...state.agentModel } },
+ }),
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (s: object) => unknown) =>
+ selector({
+ activeTopicId: state.topicModel ? 'topic-1' : undefined,
+ topicDataMap: {},
+ topicDetailMap: state.topicModel ? { 'topic-1': { id: 'topic-1', ...state.topicModel } } : {},
+ }),
+}));
+
+vi.mock('@/store/aiInfra', async () => {
+ const { aiModelSelectors, aiProviderSelectors } = await import('@/store/aiInfra/selectors');
+
+ return {
+ aiModelSelectors,
+ aiProviderSelectors,
+ useAiInfraStore: (selector: (s: object) => unknown) =>
+ selector({
+ enabledAiModels: state.toolUseModels.map(({ model, provider }) => ({
+ abilities: { functionCall: true },
+ id: model,
+ providerId: provider,
+ })),
+ isInitAiProviderRuntimeState: true,
+ }),
+ };
+});
+
+const topicModel = { model: 'topic-model', provider: 'topic-provider' };
+
+const renderAvailability = () =>
+ renderHook(() => useTaskExecutionAvailability('agent-1')).result.current;
+
+beforeEach(() => {
+ state.agentModel = { model: 'agent-model', provider: 'agent-provider' };
+ state.isPreferenceLoading = false;
+ state.toolUseModels = [];
+ state.topicModel = undefined;
+});
+
+// A task runs on its assignee's default model; whatever topic the chat page has
+// active must not decide whether the task gets an execution environment.
+describe('useTaskExecutionAvailability', () => {
+ it('is available when the assignee default model supports tool use', () => {
+ state.toolUseModels = [state.agentModel];
+
+ expect(renderAvailability()).toBe(true);
+ });
+
+ it('is unavailable while the agent mode preference is loading', () => {
+ state.isPreferenceLoading = true;
+ state.toolUseModels = [state.agentModel];
+
+ expect(renderAvailability()).toBe(false);
+ });
+
+ it('is unavailable when only the active chat topic model supports tool use', () => {
+ state.topicModel = topicModel;
+ state.toolUseModels = [topicModel];
+
+ expect(renderAvailability()).toBe(false);
+ });
+
+ it('is available when the assignee default model supports tool use even if the active topic model does not', () => {
+ state.topicModel = topicModel;
+ state.toolUseModels = [state.agentModel];
+
+ expect(renderAvailability()).toBe(true);
+ });
+});
diff --git a/src/features/AgentTasks/features/useTaskExecutionAvailability.ts b/src/features/AgentTasks/features/useTaskExecutionAvailability.ts
new file mode 100644
index 00000000000..b4d060847f7
--- /dev/null
+++ b/src/features/AgentTasks/features/useTaskExecutionAvailability.ts
@@ -0,0 +1,20 @@
+import { useAgentDefaultModelAgentMode } from '@/features/ChatInput/hooks/useEffectiveAgentMode';
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+
+/**
+ * Whether a task assigned to this agent has an execution environment to pick.
+ *
+ * Heterogeneous agents always execute somewhere; a plain agent only has one in
+ * agent mode (chat mode means "no tools, no device") — the same gate the chat
+ * composer uses for this cluster. There is no topic context here: the assignee
+ * is judged by its own default model, never the chat page's active topic pin.
+ * `false` while the mode preference is still loading.
+ */
+export const useTaskExecutionAvailability = (assigneeAgentId: string): boolean => {
+ const isHetero = useAgentStore(agentByIdSelectors.isAgentHeterogeneousById(assigneeAgentId));
+ const { isAgentRuntimeMode, isPreferenceLoading } =
+ useAgentDefaultModelAgentMode(assigneeAgentId);
+
+ return !isPreferenceLoading && (isHetero || isAgentRuntimeMode);
+};
diff --git a/src/features/ChatInput/ActionBar/Model/index.tsx b/src/features/ChatInput/ActionBar/Model/index.tsx
index 19e3c96255f..a8feab31a0f 100644
--- a/src/features/ChatInput/ActionBar/Model/index.tsx
+++ b/src/features/ChatInput/ActionBar/Model/index.tsx
@@ -1,6 +1,6 @@
import { Tooltip } from '@lobehub/ui';
import { Alert } from '@lobehub/ui/base-ui';
-import { memo, useCallback } from 'react';
+import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { AGENT_SHARE_ALLOWED_PROVIDERS } from '@/business/agent-share';
@@ -8,8 +8,6 @@ import { useAgentShareSupported } from '@/business/client/useAgentShareSupported
import ModelSwitchPanel from '@/features/ModelSwitchPanel';
import { useEnabledChatModels } from '@/hooks/useEnabledChatModels';
import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
-import { useChatStore } from '@/store/chat';
-import { topicSelectors } from '@/store/chat/slices/topic/selectors';
import SelectorTrigger from '../../components/SelectorTrigger';
import { useAgentId } from '../../hooks/useAgentId';
@@ -18,28 +16,26 @@ import { useModelLockTooltip } from '../../hooks/useModelLockTooltip';
import { useReasoningEffortControl } from '../../hooks/useReasoningEffortControl';
import { useActionBarContext } from '../context';
import SelectorMenu from './SelectorMenu';
+import { useTopicModelSwitch } from './useTopicModelSwitch';
const ModelSwitch = memo(() => {
const { t } = useTranslation(['chat', 'agent']);
const { dropdownPlacement } = useActionBarContext();
const agentId = useAgentId();
+ const selection = useAgentModelSelection(agentId);
+ const { canDisplayModel, canSelectModel, selectionLockReason } = selection;
+ // The composer topic's pin when present, else the agent selection; a switch
+ // pins that topic, otherwise updates the agent.
const {
- canDisplayModel,
- canSelectModel,
- model: agentModel,
- provider: agentProvider,
- selectionLockReason,
- selectModel,
- } = useAgentModelSelection(agentId);
- // Topic-scoped model: a topic pins its own model (top-level `topics.model`
- // column). Display the topic's pinned model when present, else the agent
- // default; a switch pins to the active topic, otherwise updates the agent
- // (via selectModel, which honors workspace member overrides).
- const activeTopicId = useChatStore((s) => s.activeTopicId);
+ model,
+ provider,
+ switchModel: handleModelChange,
+ topicId,
+ } = useTopicModelSwitch(selection);
const { isShared } = useAgentShareSupported(agentId);
const chatModels = useEnabledChatModels();
const enabledList =
- !activeTopicId && isShared && AGENT_SHARE_ALLOWED_PROVIDERS
+ !topicId && isShared && AGENT_SHARE_ALLOWED_PROVIDERS
? chatModels.filter((item) => AGENT_SHARE_ALLOWED_PROVIDERS?.includes(item.id))
: undefined;
const modelNotice = enabledList ? (
@@ -50,31 +46,16 @@ const ModelSwitch = memo(() => {
type={'info'}
/>
) : undefined;
- const topicModel = useChatStore(topicSelectors.activeTopicModel);
- const updateTopicModel = useChatStore((s) => s.updateTopicModel);
- const model = topicModel?.model ?? agentModel;
- const provider = topicModel?.model ? topicModel.provider : agentProvider;
-
const enabledModel = useAiInfraStore(aiModelSelectors.getEnabledModelById(model, provider));
const displayName = enabledModel?.displayName || model;
const lockTooltip = useModelLockTooltip(displayName, selectionLockReason);
// Reasoning effort rides along with the model trigger instead of claiming a
- // second action slot. Like the model, it pins to the active topic when there
- // is one and edits the user's per-model default otherwise.
- const effort = useReasoningEffortControl(model, provider, activeTopicId ?? undefined);
+ // second action slot. Like the model, it pins to the composer's topic when
+ // there is one and edits the user's per-model default otherwise.
+ const effort = useReasoningEffortControl(model, provider, topicId ?? undefined);
// A pinned model still opens the menu when there is an effort to pick there.
const interactive = canSelectModel || effort.hasReasoningParams;
- const handleModelChange = useCallback(
- async (params: { model: string; provider: string }) => {
- if (!canSelectModel) return;
-
- if (activeTopicId) await updateTopicModel(activeTopicId, params);
- else await selectModel(params);
- },
- [activeTopicId, canSelectModel, selectModel, updateTopicModel],
- );
-
// Both current values on one chip, the way the heterogeneous selector reads:
// "GPT-5.6 Sol 中". The effort half is dropped for models without one; the
// chip keeps the two halves apart so the effort is never ellipsised away.
diff --git a/src/features/ChatInput/ActionBar/Model/useTopicModelSwitch.test.ts b/src/features/ChatInput/ActionBar/Model/useTopicModelSwitch.test.ts
new file mode 100644
index 00000000000..e4272037f38
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Model/useTopicModelSwitch.test.ts
@@ -0,0 +1,104 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useTopicModelSwitch } from './useTopicModelSwitch';
+
+interface ModelPin {
+ model: string;
+ provider: string;
+}
+
+const state = vi.hoisted(() => ({
+ /** `undefined`: the host publishes no topic; `null`: its conversation has none. */
+ composerTopicId: undefined as string | null | undefined,
+ globalActiveTopicId: undefined as string | undefined,
+ selectModel: vi.fn(),
+ topicModels: {} as Record<string, ModelPin>,
+ updateTopicModel: vi.fn(),
+}));
+
+vi.mock('../../store', () => ({
+ useChatInputStore: (selector: (s: object) => unknown) =>
+ selector({ topicId: state.composerTopicId }),
+}));
+
+// Store boundary: the real topic selectors run against this state.
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (s: object) => unknown) =>
+ selector({
+ activeTopicId: state.globalActiveTopicId,
+ topicDataMap: {},
+ topicDetailMap: Object.fromEntries(
+ Object.entries(state.topicModels).map(([id, pin]) => [id, { id, ...pin }]),
+ ),
+ updateTopicModel: state.updateTopicModel,
+ }),
+}));
+
+const picked = { model: 'picked-model', provider: 'picked' };
+
+const renderSwitch = (canSelectModel = true) =>
+ renderHook(() =>
+ useTopicModelSwitch({
+ canSelectModel,
+ model: 'agent-model',
+ provider: 'agent-provider',
+ selectModel: state.selectModel,
+ }),
+ );
+
+beforeEach(() => {
+ state.composerTopicId = undefined;
+ state.globalActiveTopicId = 'outer-topic';
+ state.topicModels = {
+ 'outer-topic': { model: 'outer-model', provider: 'outer-provider' },
+ 'own-topic': { model: 'own-model', provider: 'own-provider' },
+ };
+ state.selectModel.mockReset();
+ state.updateTopicModel.mockReset();
+});
+
+describe('useTopicModelSwitch', () => {
+ // A page copilot embedded beside a chat runs with `topicId: null` while the
+ // outer chat's topic is still the global active one.
+ it('shows and switches the agent model when the composer conversation has no topic', async () => {
+ state.composerTopicId = null;
+ const { result } = renderSwitch();
+
+ expect(result.current).toMatchObject({ model: 'agent-model', provider: 'agent-provider' });
+ await act(() => result.current.switchModel(picked));
+
+ expect(state.selectModel).toHaveBeenCalledWith(picked);
+ expect(state.updateTopicModel).not.toHaveBeenCalled();
+ });
+
+ it("shows and pins the composer's own topic, not the global active topic", async () => {
+ state.composerTopicId = 'own-topic';
+ const { result } = renderSwitch();
+
+ expect(result.current).toMatchObject({ model: 'own-model', provider: 'own-provider' });
+ await act(() => result.current.switchModel(picked));
+
+ expect(state.updateTopicModel).toHaveBeenCalledWith('own-topic', picked);
+ expect(state.selectModel).not.toHaveBeenCalled();
+ });
+
+ it('follows the global active topic when the host publishes no topic', async () => {
+ const { result } = renderSwitch();
+
+ expect(result.current).toMatchObject({ model: 'outer-model', provider: 'outer-provider' });
+ await act(() => result.current.switchModel(picked));
+
+ expect(state.updateTopicModel).toHaveBeenCalledWith('outer-topic', picked);
+ });
+
+ it('ignores a switch when the model cannot be selected', async () => {
+ state.composerTopicId = 'own-topic';
+ const { result } = renderSwitch(false);
+
+ await act(() => result.current.switchModel(picked));
+
+ expect(state.updateTopicModel).not.toHaveBeenCalled();
+ expect(state.selectModel).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/ChatInput/ActionBar/Model/useTopicModelSwitch.ts b/src/features/ChatInput/ActionBar/Model/useTopicModelSwitch.ts
new file mode 100644
index 00000000000..f2d87e2a24c
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Model/useTopicModelSwitch.ts
@@ -0,0 +1,52 @@
+import { useCallback } from 'react';
+
+import { useChatStore } from '@/store/chat';
+
+import { useTopicModel } from '../../hooks/useEffectiveModel';
+import { useTopicId } from '../../hooks/useTopicId';
+
+interface ModelAndProvider {
+ model: string;
+ provider: string;
+}
+
+interface UseTopicModelSwitchOptions {
+ canSelectModel: boolean;
+ /** The agent-level selection (see `useAgentModelSelection`). */
+ model: string;
+ provider: string;
+ selectModel: (params: ModelAndProvider) => Promise<unknown> | unknown;
+}
+
+/**
+ * Topic-scoped model for the Model control: a topic pins its own model
+ * (top-level `topics.model` column). Shows the pin of this composer's topic
+ * (see `useTopicId`) when present, else the agent selection; a switch pins that
+ * topic, otherwise updates the agent (via `selectModel`, which honors workspace
+ * member overrides). Never the global active topic: a page copilot beside a
+ * chat has `topicId: null` and must neither show nor write the outer pin.
+ */
+export const useTopicModelSwitch = ({
+ canSelectModel,
+ model: agentModel,
+ provider: agentProvider,
+ selectModel,
+}: UseTopicModelSwitchOptions) => {
+ const topicId = useTopicId();
+ const topicModel = useTopicModel();
+ const updateTopicModel = useChatStore((s) => s.updateTopicModel);
+ const model = topicModel?.model ?? agentModel;
+ const provider = topicModel?.model ? topicModel.provider : agentProvider;
+
+ const switchModel = useCallback(
+ async (params: ModelAndProvider) => {
+ if (!canSelectModel) return;
+
+ if (topicId) await updateTopicModel(topicId, params);
+ else await selectModel(params);
+ },
+ [canSelectModel, selectModel, topicId, updateTopicModel],
+ );
+
+ return { model, provider, switchModel, topicId };
+};
diff --git a/src/features/ChatInput/ActionBar/Params/useParamsModelConfig.test.ts b/src/features/ChatInput/ActionBar/Params/useParamsModelConfig.test.ts
index 5176fad92ec..60932992107 100644
--- a/src/features/ChatInput/ActionBar/Params/useParamsModelConfig.test.ts
+++ b/src/features/ChatInput/ActionBar/Params/useParamsModelConfig.test.ts
@@ -22,22 +22,32 @@ const testState = vi.hoisted(() => ({
modelConfigs: {} as Record<string, ModelConfig>,
},
chat: {
- topicModel: undefined as ModelSelection | undefined,
+ activeTopicId: undefined as string | undefined,
+ topicModels: {} as Record<string, ModelSelection>,
},
+ /** `undefined`: the host publishes no topic; `null`: its conversation has none. */
+ composerTopicId: undefined as string | null | undefined,
}));
vi.mock('../../hooks/useAgentModelSelection', () => ({
useAgentModelSelection: () => testState.agentSelection,
}));
-vi.mock('@/store/chat', () => ({
- useChatStore: <T>(selector: (state: typeof testState.chat) => T) => selector(testState.chat),
+vi.mock('../../store', () => ({
+ useChatInputStore: (selector: (state: object) => unknown) =>
+ selector({ topicId: testState.composerTopicId }),
}));
-vi.mock('@/store/chat/slices/topic/selectors', () => ({
- topicSelectors: {
- activeTopicModel: (state: typeof testState.chat) => state.topicModel,
- },
+// Store boundary: the real topic selectors run against this state.
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (state: object) => unknown) =>
+ selector({
+ activeTopicId: testState.chat.activeTopicId,
+ topicDataMap: {},
+ topicDetailMap: Object.fromEntries(
+ Object.entries(testState.chat.topicModels).map(([id, pin]) => [id, { id, ...pin }]),
+ ),
+ }),
}));
vi.mock('@/store/aiInfra', () => ({
@@ -56,7 +66,9 @@ describe('useParamsModelConfig', () => {
model: 'agent-model',
provider: 'agent-provider',
};
- testState.chat.topicModel = undefined;
+ testState.chat.activeTopicId = undefined;
+ testState.chat.topicModels = {};
+ testState.composerTopicId = undefined;
testState.ai.modelConfigs = {
'agent-provider:agent-model': {
disabledParams: ['temperature'],
@@ -69,9 +81,9 @@ describe('useParamsModelConfig', () => {
});
it('uses the active topic model for parameter capabilities', () => {
- testState.chat.topicModel = {
- model: 'topic-model',
- provider: 'topic-provider',
+ testState.chat.activeTopicId = 'topic-1';
+ testState.chat.topicModels = {
+ 'topic-1': { model: 'topic-model', provider: 'topic-provider' },
};
const { result } = renderHook(() => useParamsModelConfig('agent-1'));
@@ -94,4 +106,18 @@ describe('useParamsModelConfig', () => {
provider: 'agent-provider',
});
});
+
+ // A page copilot embedded beside a chat runs with `topicId: null` while the
+ // outer chat's topic is still the global active one.
+ it('ignores the global active topic pin when the composer conversation has no topic', () => {
+ testState.chat.activeTopicId = 'topic-1';
+ testState.chat.topicModels = {
+ 'topic-1': { model: 'topic-model', provider: 'topic-provider' },
+ };
+ testState.composerTopicId = null;
+
+ const { result } = renderHook(() => useParamsModelConfig('agent-1'));
+
+ expect(result.current).toMatchObject({ model: 'agent-model', provider: 'agent-provider' });
+ });
});
diff --git a/src/features/ChatInput/ActionBar/Params/useParamsModelConfig.ts b/src/features/ChatInput/ActionBar/Params/useParamsModelConfig.ts
index 00f44e00c36..5a74ba569c9 100644
--- a/src/features/ChatInput/ActionBar/Params/useParamsModelConfig.ts
+++ b/src/features/ChatInput/ActionBar/Params/useParamsModelConfig.ts
@@ -1,13 +1,12 @@
import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
-import { useChatStore } from '@/store/chat';
-import { topicSelectors } from '@/store/chat/slices/topic/selectors';
import { useAgentModelSelection } from '../../hooks/useAgentModelSelection';
+import { useTopicModel } from '../../hooks/useEffectiveModel';
export const useParamsModelConfig = (agentId: string) => {
const { model: selectedAgentModel, provider: selectedAgentProvider } =
useAgentModelSelection(agentId);
- const topicModel = useChatStore(topicSelectors.activeTopicModel);
+ const topicModel = useTopicModel();
const model = topicModel?.model ?? selectedAgentModel;
const provider = topicModel?.model ? topicModel.provider : selectedAgentProvider;
diff --git a/src/features/ChatInput/ActionBar/Token/index.tsx b/src/features/ChatInput/ActionBar/Token/index.tsx
index 3fab6babbdc..e3a2b475efc 100644
--- a/src/features/ChatInput/ActionBar/Token/index.tsx
+++ b/src/features/ChatInput/ActionBar/Token/index.tsx
@@ -1,13 +1,14 @@
import { type PropsWithChildren } from 'react';
import { memo } from 'react';
-import { useModelHasContextWindowToken } from '@/hooks/useModelHasContextWindowToken';
import dynamic from '@/libs/next/dynamic';
+import { useShowContextWindow } from './useShowContextWindow';
+
const LargeTokenContent = dynamic(() => import('./TokenTag'), { ssr: false });
const Token = memo<PropsWithChildren>(({ children }) => {
- const showTag = useModelHasContextWindowToken();
+ const showTag = useShowContextWindow();
return showTag && children;
});
diff --git a/src/features/ChatInput/ActionBar/Token/useShowContextWindow.test.ts b/src/features/ChatInput/ActionBar/Token/useShowContextWindow.test.ts
new file mode 100644
index 00000000000..f3d0043f093
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Token/useShowContextWindow.test.ts
@@ -0,0 +1,95 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useShowContextWindow } from './useShowContextWindow';
+
+interface ModelPin {
+ model: string;
+ provider: string;
+}
+
+interface EnabledAiModel extends ModelPin {
+ contextWindowTokens?: number;
+}
+
+const state = vi.hoisted(() => ({
+ enabledAiModels: [] as { contextWindowTokens?: number; id: string; providerId: string }[],
+ topicModel: undefined as ModelPin | undefined,
+}));
+
+vi.mock('../../hooks/useAgentId', () => ({ useAgentId: () => 'agent-1' }));
+
+// The host publishes no topic of its own, so the composer follows the global active topic.
+vi.mock('../../store', () => ({
+ useChatInputStore: (selector: (s: object) => unknown) => selector({ topicId: undefined }),
+}));
+
+// Store boundary: the real `useEffectiveModel` and `aiModelSelectors` run against these states.
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (s: object) => unknown) =>
+ selector({
+ agentMap: { 'agent-1': { model: 'agent-model', provider: 'agent-provider' } },
+ }),
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (s: object) => unknown) =>
+ selector({
+ activeTopicId: state.topicModel ? 'topic-1' : undefined,
+ topicDataMap: {},
+ topicDetailMap: state.topicModel ? { 'topic-1': { id: 'topic-1', ...state.topicModel } } : {},
+ }),
+}));
+
+vi.mock('@/store/aiInfra', async () => ({
+ aiModelSelectors: (await import('@/store/aiInfra/selectors')).aiModelSelectors,
+ useAiInfraStore: (selector: (s: object) => unknown) =>
+ selector({ enabledAiModels: state.enabledAiModels }),
+}));
+
+const setEnabledModels = (...models: EnabledAiModel[]) => {
+ state.enabledAiModels = models.map(({ contextWindowTokens, model, provider }) => ({
+ contextWindowTokens,
+ id: model,
+ providerId: provider,
+ }));
+};
+
+const topicModel = { model: 'topic-model', provider: 'topic-provider' };
+
+beforeEach(() => {
+ state.topicModel = undefined;
+ setEnabledModels({ contextWindowTokens: 8000, model: 'agent-model', provider: 'agent-provider' });
+});
+
+describe('useShowContextWindow', () => {
+ it('shows the ring when the agent default model has a context window', () => {
+ expect(renderHook(() => useShowContextWindow()).result.current).toBe(true);
+ });
+
+ it('hides the ring for models without a context window', () => {
+ setEnabledModels({ model: 'agent-model', provider: 'agent-provider' });
+
+ expect(renderHook(() => useShowContextWindow()).result.current).toBe(false);
+ });
+
+ it('shows the ring when the topic pinned model has a context window but the agent default does not', () => {
+ state.topicModel = topicModel;
+ setEnabledModels(
+ { model: 'agent-model', provider: 'agent-provider' },
+ { contextWindowTokens: 16_000, ...topicModel },
+ );
+
+ expect(renderHook(() => useShowContextWindow()).result.current).toBe(true);
+ });
+
+ it('hides the ring when the agent default has a context window but the topic pinned model does not', () => {
+ state.topicModel = topicModel;
+ setEnabledModels(
+ { contextWindowTokens: 8000, model: 'agent-model', provider: 'agent-provider' },
+ topicModel,
+ );
+
+ expect(renderHook(() => useShowContextWindow()).result.current).toBe(false);
+ });
+});
diff --git a/src/features/ChatInput/ActionBar/Token/useShowContextWindow.ts b/src/features/ChatInput/ActionBar/Token/useShowContextWindow.ts
new file mode 100644
index 00000000000..78566d3f1c8
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Token/useShowContextWindow.ts
@@ -0,0 +1,16 @@
+import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
+
+import { useAgentId } from '../../hooks/useAgentId';
+import { useEffectiveModel } from '../../hooks/useEffectiveModel';
+
+/**
+ * Whether the context-window ring can be computed: judged on the model this
+ * composer actually runs (see `useEffectiveModel`), the same one
+ * `useTokenBreakdown` counts against — not the agent default.
+ */
+export const useShowContextWindow = (): boolean => {
+ const agentId = useAgentId();
+ const { model, provider } = useEffectiveModel(agentId);
+
+ return useAiInfraStore(aiModelSelectors.isModelHasContextWindowToken(model, provider));
+};
diff --git a/src/features/ChatInput/ActionBar/Token/useTokenBreakdown.test.ts b/src/features/ChatInput/ActionBar/Token/useTokenBreakdown.test.ts
new file mode 100644
index 00000000000..599e2e5df6b
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Token/useTokenBreakdown.test.ts
@@ -0,0 +1,159 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useTokenBreakdown } from './useTokenBreakdown';
+
+const state = vi.hoisted(() => ({
+ activeTopicId: undefined as string | undefined,
+ /** `undefined`: the host publishes no topic; `null`: its conversation has none. */
+ composerTopicId: undefined as string | null | undefined,
+ summaries: {} as Record<string, string>,
+ useFetchTopicDetail: vi.fn(),
+}));
+
+// One token per character, so a count names the text it was taken from.
+vi.mock('@/hooks/useTokenCount', () => ({ useTokenCount: (text = '') => text.length }));
+vi.mock('@/hooks/useModelContextWindowTokens', () => ({ useModelContextWindowTokens: () => 8000 }));
+vi.mock('@/hooks/useModelSupportToolUse', () => ({ useModelSupportToolUse: () => false }));
+vi.mock('@/helpers/toolEngineering', () => ({
+ createAgentToolsEngine: () => ({
+ generateToolsDetailed: () => ({ enabledManifests: [], tools: [] }),
+ }),
+}));
+
+vi.mock('../../hooks/useAgentId', () => ({ useAgentId: () => 'agent-1' }));
+vi.mock('../../hooks/useEffectiveModel', () => ({
+ useEffectiveModel: () => ({ model: 'model-1', provider: 'provider-1' }),
+}));
+
+vi.mock('../../store', () => ({
+ useChatInputStore: (selector: (s: object) => unknown) =>
+ selector({ topicId: state.composerTopicId }),
+ useStoreApi: () => ({
+ getState: () => ({ contextWindowMessages: [], markdownContent: '' }),
+ subscribe: () => () => {},
+ }),
+}));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (s: object) => unknown) => selector({ activeAgentId: 'agent-1' }),
+}));
+vi.mock('@/store/agent/selectors', () => ({
+ agentByIdSelectors: {
+ getAgentKnowledgeBasesById: () => () => [],
+ getAgentPluginsById: () => () => [],
+ getAgentSystemRoleById: () => () => '',
+ },
+ chatConfigByIdSelectors: {
+ getChatConfigById: () => () => ({}),
+ getRuntimeModeById: () => () => undefined,
+ getSkillActivateModeById: () => () => undefined,
+ },
+}));
+vi.mock('@/store/aiInfra', () => ({
+ useAiInfraStore: (selector: (s: object) => unknown) => selector({}),
+}));
+vi.mock('@/store/aiInfra/selectors', () => ({
+ aiModelSelectors: {
+ isModelBuiltinSearchInternal: () => () => false,
+ isModelHasBuiltinSearch: () => () => false,
+ },
+ aiProviderSelectors: { isProviderHasBuiltinSearch: () => () => false },
+}));
+vi.mock('@/store/tool', () => ({
+ useToolStore: (selector: (s: object) => unknown) => selector({ installedPlugins: [] }),
+}));
+vi.mock('@/store/user', () => ({
+ useUserStore: (selector: (s: object) => unknown) => selector({}),
+}));
+vi.mock('@/store/user/selectors', () => ({ settingsSelectors: { memoryEnabled: () => false } }));
+
+// Store boundary: the real topic selectors run against this state.
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (s: object) => unknown) =>
+ selector({
+ activeTopicId: state.activeTopicId,
+ topicDataMap: {},
+ useFetchTopicDetail: state.useFetchTopicDetail,
+ topicDetailMap: Object.fromEntries(
+ Object.entries(state.summaries).map(([id, historySummary]) => [id, { historySummary, id }]),
+ ),
+ }),
+}));
+
+beforeEach(() => {
+ // The main column's topic stays globally active while another composer renders its own.
+ state.activeTopicId = 'main-topic';
+ state.composerTopicId = undefined;
+ state.summaries = { 'main-topic': 'main column summary', 'pane-topic': 'pane' };
+ state.useFetchTopicDetail.mockReset();
+});
+
+describe('useTokenBreakdown', () => {
+ it("counts the composer's own topic summary rather than the global active topic's", () => {
+ state.composerTopicId = 'pane-topic';
+
+ const { result } = renderHook(() => useTokenBreakdown());
+
+ expect(result.current.historySummaryToken).toBe('pane'.length);
+ });
+
+ it('counts no summary when the composer conversation has no topic, even with an active topic', () => {
+ state.composerTopicId = null;
+
+ const { result } = renderHook(() => useTokenBreakdown());
+
+ expect(result.current.historySummaryToken).toBe(0);
+ });
+
+ it('follows the global active topic when the host publishes no topic', () => {
+ const { result } = renderHook(() => useTokenBreakdown());
+
+ expect(result.current.historySummaryToken).toBe('main column summary'.length);
+ });
+
+ // A document's chat panel runs on a `trigger='document'` system topic that
+ // never reaches the loaded lists, yet the run includes its persisted summary.
+ it('loads an unlisted composer topic by id and counts its summary once it arrives', () => {
+ state.composerTopicId = 'doc-topic';
+
+ const { rerender, result } = renderHook(() => useTokenBreakdown());
+
+ expect(state.useFetchTopicDetail).toHaveBeenLastCalledWith('doc-topic');
+
+ state.summaries['doc-topic'] = 'doc summary';
+ rerender();
+
+ expect(result.current.historySummaryToken).toBe('doc summary'.length);
+ });
+
+ // `/goal/:goalId` makes a sidebar-excluded supervision topic globally active
+ // with no `useFetchActiveTopicDetail` mounted, so the composer must load it.
+ it('loads the global active topic by id when no list or detail holds it', () => {
+ state.composerTopicId = 'main-topic';
+ delete state.summaries['main-topic'];
+
+ const { rerender, result } = renderHook(() => useTokenBreakdown());
+
+ expect(state.useFetchTopicDetail).toHaveBeenLastCalledWith('main-topic');
+ expect(result.current.historySummaryToken).toBe(0);
+
+ state.summaries['main-topic'] = 'goal summary';
+ rerender();
+
+ expect(result.current.historySummaryToken).toBe('goal summary'.length);
+ });
+
+ it('requests no detail for a topic that is already loaded or when there is none', () => {
+ state.composerTopicId = 'pane-topic';
+ const { rerender } = renderHook(() => useTokenBreakdown());
+
+ state.composerTopicId = null;
+ rerender();
+
+ state.composerTopicId = undefined;
+ rerender();
+
+ for (const [id] of state.useFetchTopicDetail.mock.calls) expect(id).toBeUndefined();
+ });
+});
diff --git a/src/features/ChatInput/ActionBar/Token/useTokenBreakdown.ts b/src/features/ChatInput/ActionBar/Token/useTokenBreakdown.ts
index 18ce8b97729..7013dbed54f 100644
--- a/src/features/ChatInput/ActionBar/Token/useTokenBreakdown.ts
+++ b/src/features/ChatInput/ActionBar/Token/useTokenBreakdown.ts
@@ -20,6 +20,7 @@ import { settingsSelectors } from '@/store/user/selectors';
import { useAgentId } from '../../hooks/useAgentId';
import { useEffectiveModel } from '../../hooks/useEffectiveModel';
+import { useTopicId } from '../../hooks/useTopicId';
import { useStoreApi } from '../../store';
import { getToolContextRefreshKey, getToolExcludeDefaultToolIds } from './utils';
@@ -82,9 +83,21 @@ export interface TokenBreakdown {
export const useTokenBreakdown = (): TokenBreakdown => {
const { input, messages } = useComposerSource();
- const historySummary = useChatStore(
- (s) => topicSelectors.currentActiveTopicSummary(s)?.content || '',
- );
+ // The summary of this composer's own conversation (see `useTopicId`), never
+ // the global active topic's: an embedded composer would otherwise count the
+ // outer chat's history against its context window.
+ const topicId = useTopicId();
+ const [historySummary, isUnlistedTopic, useFetchTopicDetail] = useChatStore((s) => {
+ const topic = topicId ? topicSelectors.getTopicById(topicId)(s) : undefined;
+ return [topic?.historySummary || '', !!topicId && !topic, s.useFetchTopicDetail] as const;
+ });
+ // A topic that never reaches the loaded lists (a document's chat panel runs on
+ // a `trigger='document'` system topic, a goal's supervision topic is excluded
+ // from the sidebar) still has a persisted summary the run includes, so load it
+ // by id instead of counting it as empty. This holds for the global active topic
+ // too: not every route mounts `useFetchActiveTopicDetail`, and the by-id fetch
+ // dedupes with it where it does.
+ useFetchTopicDetail(isUnlistedTopic ? topicId : undefined);
const agentId = useAgentId();
const { model, provider } = useEffectiveModel(agentId);
diff --git a/src/features/ChatInput/hooks/useEffectiveAgentMode.test.ts b/src/features/ChatInput/hooks/useEffectiveAgentMode.test.ts
index 95315414fa9..14a9dacc766 100644
--- a/src/features/ChatInput/hooks/useEffectiveAgentMode.test.ts
+++ b/src/features/ChatInput/hooks/useEffectiveAgentMode.test.ts
@@ -1,7 +1,11 @@
import { renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { resolveEffectiveAgentMode, useEffectiveAgentMode } from './useEffectiveAgentMode';
+import {
+ resolveEffectiveAgentMode,
+ useAgentDefaultModelAgentMode,
+ useEffectiveAgentMode,
+} from './useEffectiveAgentMode';
const testState = vi.hoisted(() => ({
access: {
@@ -17,7 +21,11 @@ const testState = vi.hoisted(() => ({
aiInfra: {
isReady: true,
},
- supportToolUse: true,
+ /** Tool-use capability keyed by `provider/model`; unknown models lack tool use. */
+ toolUseByModel: {} as Record<string, boolean>,
+ topic: {
+ pinned: undefined as { model: string; provider: string } | undefined,
+ },
user: {
fetchedPreference: undefined as
{ agentModeOverrides?: Record<string, boolean> } | null | undefined,
@@ -35,7 +43,8 @@ vi.mock('@/features/ResourcePermission/useAgentManagementAccess', () => ({
}));
vi.mock('@/hooks/useModelSupportToolUse', () => ({
- useModelSupportToolUse: () => testState.supportToolUse,
+ useModelSupportToolUse: (model: string, provider: string) =>
+ testState.toolUseByModel[`${provider}/${model}`] ?? false,
}));
vi.mock('@/store/agent', () => ({
@@ -59,6 +68,21 @@ vi.mock('@/store/aiInfra', () => ({
selector(testState.aiInfra),
}));
+vi.mock('../store', () => ({
+ useChatInputStore: (selector: (s: { topicId: string }) => unknown) =>
+ selector({ topicId: 'topic-1' }),
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (s: typeof testState.topic) => unknown) => selector(testState.topic),
+}));
+
+vi.mock('@/store/chat/slices/topic/selectors', () => ({
+ topicSelectors: {
+ getTopicModelById: () => (s: typeof testState.topic) => s.pinned,
+ },
+}));
+
vi.mock('@/store/user', () => ({
useUserStore: (selector: (s: typeof testState.user) => unknown) => selector(testState.user),
}));
@@ -71,7 +95,8 @@ beforeEach(() => {
testState.agent.model = 'model-1';
testState.agent.provider = 'provider-1';
testState.aiInfra.isReady = true;
- testState.supportToolUse = true;
+ testState.toolUseByModel = { 'provider-1/model-1': true };
+ testState.topic.pinned = undefined;
testState.user.fetchedPreference = undefined;
testState.user.isLoading = false;
testState.user.workspaceUserPreference = {};
@@ -204,3 +229,70 @@ describe('useEffectiveAgentMode', () => {
expect(result.current.isPreferenceLoading).toBe(true);
});
});
+
+describe('model used for the tool-use capability', () => {
+ const topicModel = { model: 'topic-model', provider: 'topic-provider' };
+
+ describe('useEffectiveAgentMode', () => {
+ it('lets a tool-capable topic model unlock Agent mode when the agent default lacks tool use', () => {
+ testState.toolUseByModel = { 'topic-provider/topic-model': true };
+ testState.topic.pinned = topicModel;
+
+ const { result } = renderHook(() => useEffectiveAgentMode('agent-1'));
+
+ expect(result.current).toMatchObject({
+ canSelectAgentMode: true,
+ currentMode: 'agent',
+ isAgentModeUnavailable: false,
+ isAgentRuntimeMode: true,
+ });
+ });
+
+ it('marks Agent mode unavailable when the topic model lacks tool use although the agent default has it', () => {
+ testState.topic.pinned = topicModel;
+
+ const { result } = renderHook(() => useEffectiveAgentMode('agent-1'));
+
+ expect(result.current).toMatchObject({
+ canSelectAgentMode: false,
+ currentMode: 'chat',
+ isAgentModeUnavailable: true,
+ isAgentRuntimeMode: false,
+ });
+ });
+
+ it('falls back to the agent default model when the topic pins nothing', () => {
+ const { result } = renderHook(() => useEffectiveAgentMode('agent-1'));
+
+ expect(result.current).toMatchObject({ currentMode: 'agent', isAgentModeUnavailable: false });
+ });
+ });
+
+ describe('useAgentDefaultModelAgentMode', () => {
+ // Task execution has no topic context: the active chat topic must never leak in.
+ it('ignores the active topic pin and judges the agent default model', () => {
+ testState.toolUseByModel = {
+ 'provider-1/model-1': false,
+ 'topic-provider/topic-model': true,
+ };
+ testState.topic.pinned = topicModel;
+
+ const { result } = renderHook(() => useAgentDefaultModelAgentMode('agent-1'));
+
+ expect(result.current).toMatchObject({
+ canSelectAgentMode: false,
+ currentMode: 'chat',
+ isAgentModeUnavailable: true,
+ isAgentRuntimeMode: false,
+ });
+ });
+
+ it('keeps Agent mode when the agent default has tool use even if the active topic pin lacks it', () => {
+ testState.topic.pinned = topicModel;
+
+ const { result } = renderHook(() => useAgentDefaultModelAgentMode('agent-1'));
+
+ expect(result.current).toMatchObject({ currentMode: 'agent', isAgentRuntimeMode: true });
+ });
+ });
+});
diff --git a/src/features/ChatInput/hooks/useEffectiveAgentMode.ts b/src/features/ChatInput/hooks/useEffectiveAgentMode.ts
index 8030b71e5c8..4c55f8cae91 100644
--- a/src/features/ChatInput/hooks/useEffectiveAgentMode.ts
+++ b/src/features/ChatInput/hooks/useEffectiveAgentMode.ts
@@ -4,6 +4,7 @@ import { agentByIdSelectors } from '@/store/agent/selectors';
import { aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';
import { useEffectiveAgentModePreference } from './effectiveAgentModePreference';
+import { useEffectiveModel } from './useEffectiveModel';
export type ChatInputMode = 'agent' | 'chat';
@@ -44,11 +45,17 @@ export const resolveEffectiveAgentMode = ({
};
};
-export const useEffectiveAgentMode = (agentId: string) => {
- const [model, provider] = useAgentStore((s) => [
- agentByIdSelectors.getAgentModelById(agentId)(s),
- agentByIdSelectors.getAgentModelProviderById(agentId)(s),
- ]);
+interface ModelAndProvider {
+ model: string;
+ provider: string;
+}
+
+/**
+ * Shared core: resolve the agent mode for the given model's tool-use ability.
+ * Not exported on purpose — callers must pick which model applies by using
+ * `useEffectiveAgentMode` or `useAgentDefaultModelAgentMode`.
+ */
+const useAgentModeForModel = (agentId: string, { model, provider }: ModelAndProvider) => {
const { enableAgentMode, isPreferenceLoading, usesWorkspaceMemberMode } =
useEffectiveAgentModePreference(agentId);
const supportToolUse = useModelSupportToolUse(model, provider);
@@ -60,3 +67,25 @@ export const useEffectiveAgentMode = (agentId: string) => {
usesWorkspaceMemberMode,
};
};
+
+/**
+ * Agent mode for a chat composer: judged by the model that will actually run —
+ * the active topic's pinned model, otherwise the agent default
+ * (see `useEffectiveModel`).
+ */
+export const useEffectiveAgentMode = (agentId: string) =>
+ useAgentModeForModel(agentId, useEffectiveModel(agentId));
+
+/**
+ * Agent mode judged by the agent's own default model only. For surfaces that
+ * have no topic context (e.g. task execution settings, which target an assignee
+ * agent) and must not follow whatever topic the chat page currently has active.
+ */
+export const useAgentDefaultModelAgentMode = (agentId: string) => {
+ const [model, provider] = useAgentStore((s) => [
+ agentByIdSelectors.getAgentModelById(agentId)(s),
+ agentByIdSelectors.getAgentModelProviderById(agentId)(s),
+ ]);
+
+ return useAgentModeForModel(agentId, { model, provider });
+};
diff --git a/src/features/ChatInput/hooks/useEffectiveModel.test.ts b/src/features/ChatInput/hooks/useEffectiveModel.test.ts
new file mode 100644
index 00000000000..f8b7a2b27d1
--- /dev/null
+++ b/src/features/ChatInput/hooks/useEffectiveModel.test.ts
@@ -0,0 +1,83 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useEffectiveModel } from './useEffectiveModel';
+
+interface ModelPin {
+ model: string;
+ provider: string;
+}
+
+const testState = vi.hoisted(() => ({
+ /** `undefined`: the host publishes no topic; `null`: its conversation has none. */
+ composerTopicId: undefined as string | null | undefined,
+ globalActiveTopicId: undefined as string | undefined,
+ topicModels: {} as Record<string, ModelPin>,
+}));
+
+vi.mock('../store', () => ({
+ useChatInputStore: (selector: (state: object) => unknown) =>
+ selector({ topicId: testState.composerTopicId }),
+}));
+
+// Store boundary: the real agent and topic selectors run against these states.
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (state: object) => unknown) =>
+ selector({
+ agentMap: { 'agent-1': { model: 'agent-model', provider: 'agent-provider' } },
+ }),
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (state: object) => unknown) =>
+ selector({
+ activeTopicId: testState.globalActiveTopicId,
+ topicDataMap: {},
+ topicDetailMap: Object.fromEntries(
+ Object.entries(testState.topicModels).map(([id, pin]) => [id, { id, ...pin }]),
+ ),
+ }),
+}));
+
+const outerPin = { model: 'outer-model', provider: 'outer-provider' };
+const ownPin = { model: 'own-model', provider: 'own-provider' };
+
+beforeEach(() => {
+ testState.composerTopicId = undefined;
+ testState.globalActiveTopicId = 'outer-topic';
+ testState.topicModels = { 'outer-topic': outerPin, 'own-topic': ownPin };
+});
+
+describe('useEffectiveModel', () => {
+ // A page copilot embedded beside a chat runs with `topicId: null` while the
+ // outer chat's topic is still the global active one.
+ it('uses the agent default when the composer conversation has no topic, ignoring the global active topic pin', () => {
+ testState.composerTopicId = null;
+
+ const { result } = renderHook(() => useEffectiveModel('agent-1'));
+
+ expect(result.current).toEqual({ model: 'agent-model', provider: 'agent-provider' });
+ });
+
+ it("uses the composer's own topic pin rather than the global active topic pin", () => {
+ testState.composerTopicId = 'own-topic';
+
+ const { result } = renderHook(() => useEffectiveModel('agent-1'));
+
+ expect(result.current).toEqual(ownPin);
+ });
+
+ it('falls back to the global active topic pin when the host publishes no topic', () => {
+ const { result } = renderHook(() => useEffectiveModel('agent-1'));
+
+ expect(result.current).toEqual(outerPin);
+ });
+
+ it('uses the agent default when the composer topic pins no model', () => {
+ testState.composerTopicId = 'unpinned-topic';
+
+ const { result } = renderHook(() => useEffectiveModel('agent-1'));
+
+ expect(result.current).toEqual({ model: 'agent-model', provider: 'agent-provider' });
+ });
+});
diff --git a/src/features/ChatInput/hooks/useEffectiveModel.ts b/src/features/ChatInput/hooks/useEffectiveModel.ts
index baf0676e9b9..3e066c56ac3 100644
--- a/src/features/ChatInput/hooks/useEffectiveModel.ts
+++ b/src/features/ChatInput/hooks/useEffectiveModel.ts
@@ -8,13 +8,26 @@ import { useChatStore } from '@/store/chat';
// controls, and the barrel drags in unrelated slice selectors.
import { topicSelectors } from '@/store/chat/slices/topic/selectors';
+import { useTopicId } from './useTopicId';
+
interface ModelAndProvider {
model: string;
provider: string;
}
/**
- * The effective model/provider for ChatInput: the active topic's pinned model
+ * The model pinned to this composer's own topic (see `useTopicId`), never the
+ * global active topic's: a page copilot embedded beside another chat has
+ * `topicId: null` and must not pick up the outer chat's pin.
+ */
+export const useTopicModel = (): ModelAndProvider | undefined => {
+ const topicId = useTopicId();
+
+ return useChatStore((s) => (topicId ? topicSelectors.getTopicModelById(topicId)(s) : undefined));
+};
+
+/**
+ * The effective model/provider for ChatInput: the composer topic's pinned model
* when one exists, otherwise the agent default.
*
* Use this everywhere a capability is gated on the model that will actually run
@@ -29,7 +42,7 @@ export const useEffectiveModel = (agentId: string): ModelAndProvider => {
agentByIdSelectors.getAgentModelProviderById(agentId)(s),
]);
- const topicModel = useChatStore(topicSelectors.activeTopicModel);
+ const topicModel = useTopicModel();
return {
model: topicModel?.model || agentModel,
diff --git a/src/hooks/useModelHasContextWindowToken.ts b/src/hooks/useModelHasContextWindowToken.ts
deleted file mode 100644
index 3ccd3ea20cc..00000000000
--- a/src/hooks/useModelHasContextWindowToken.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { useAgentStore } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/selectors';
-import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
-
-export const useModelHasContextWindowToken = () => {
- const model = useAgentStore(agentSelectors.currentAgentModel);
- const provider = useAgentStore(agentSelectors.currentAgentModelProvider);
-
- return useAiInfraStore(aiModelSelectors.isModelHasContextWindowToken(model, provider));
-};