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(home): switch new-model shortcuts through member model selection (#21570)

YuTengjingcc38dc9aba64
diff --git a/eslint.config.mjs b/eslint.config.mjs
index 45dd9a477db..3fe5fec3a31 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -604,8 +604,10 @@ export default eslint(
{
message:
'Home cold-path modules must not statically import ChatInput. Load an isolated editor entry with import().',
+ // `hooks/useAgentModelSelection` reaches the store only through the
+ // editor-free `store/apiContext`; Home model switches share its path.
regex:
- '^@/features/ChatInput(?:$|/(?!(?:store/initialState|utils/contextSelections)$).+)',
+ '^@/features/ChatInput(?:$|/(?!(?:hooks/useAgentModelSelection|store/initialState|utils/contextSelections)$).+)',
},
],
}),
diff --git a/src/features/ChatInput/hooks/useAgentModelSelection.test.ts b/src/features/ChatInput/hooks/useAgentModelSelection.test.ts
index b96d5fc49d2..65b21259569 100644
--- a/src/features/ChatInput/hooks/useAgentModelSelection.test.ts
+++ b/src/features/ChatInput/hooks/useAgentModelSelection.test.ts
@@ -113,10 +113,40 @@ describe('useAgentModelSelection', () => {
provider: 'shared-provider',
usesWorkspaceMemberSelection: false,
});
- expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-1', {
- model: 'next-model',
- provider: 'next-provider',
- });
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(
+ 'agent-1',
+ { model: 'next-model', provider: 'next-provider' },
+ undefined,
+ );
+ expect(testState.user.updateWorkspaceUserPreference).not.toHaveBeenCalled();
+ });
+
+ it('forwards write options and resolves true once the Agent row is written', async () => {
+ const { result } = renderHook(() => useAgentModelSelection('agent-1'));
+
+ await expect(
+ result.current.selectModel(
+ { model: 'next-model', provider: 'next-provider' },
+ { rethrow: true, showErrorMessage: false },
+ ),
+ ).resolves.toBe(true);
+
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(
+ 'agent-1',
+ { model: 'next-model', provider: 'next-provider' },
+ { rethrow: true, showErrorMessage: false },
+ );
+ });
+
+ it('resolves false without writing when the model cannot be switched', async () => {
+ testState.resource.canConfigureResource = false;
+ const { result } = renderHook(() => useAgentModelSelection('agent-1'));
+
+ await expect(
+ result.current.selectModel({ model: 'next-model', provider: 'next-provider' }),
+ ).resolves.toBe(false);
+
+ expect(testState.agent.updateAgentConfigById).not.toHaveBeenCalled();
expect(testState.user.updateWorkspaceUserPreference).not.toHaveBeenCalled();
});
@@ -293,10 +323,11 @@ describe('useAgentModelSelection', () => {
selectionPolicy: 'fixed',
usesWorkspaceMemberSelection: false,
});
- expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-1', {
- model: 'next-model',
- provider: 'next-provider',
- });
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(
+ 'agent-1',
+ { model: 'next-model', provider: 'next-provider' },
+ undefined,
+ );
expect(testState.user.updateWorkspaceUserPreference).not.toHaveBeenCalled();
});
@@ -323,10 +354,11 @@ describe('useAgentModelSelection', () => {
selectionPolicy: 'fixed',
usesWorkspaceMemberSelection: false,
});
- expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-1', {
- model: 'next-model',
- provider: 'next-provider',
- });
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(
+ 'agent-1',
+ { model: 'next-model', provider: 'next-provider' },
+ undefined,
+ );
expect(testState.user.updateWorkspaceUserPreference).not.toHaveBeenCalled();
});
diff --git a/src/features/ChatInput/hooks/useAgentModelSelection.ts b/src/features/ChatInput/hooks/useAgentModelSelection.ts
index 29b53ff1a08..0bd1d515ed7 100644
--- a/src/features/ChatInput/hooks/useAgentModelSelection.ts
+++ b/src/features/ChatInput/hooks/useAgentModelSelection.ts
@@ -19,6 +19,17 @@ interface ModelSelection {
provider: string;
}
+interface SelectModelOptions {
+ /**
+ * Throw when the write fails instead of only reporting it, so a caller can
+ * confirm success (e.g. a "model switched" toast). The member-override path
+ * always throws on failure.
+ */
+ rethrow?: boolean;
+ /** Keep the agent store's generic save-failure toast. @default true */
+ showErrorMessage?: boolean;
+}
+
/**
* Why the model trigger is shown but not switchable, so the trigger can say so
* instead of silently going inert.
@@ -36,7 +47,11 @@ export interface UseAgentModelSelectionResult extends ModelSelection {
/** Set only while the model is displayed but locked (see the type doc). */
selectionLockReason?: AgentModelSelectionLockReason;
selectionPolicy: AgentModelSelectionPolicy;
- selectModel: (selection: ModelSelection) => Promise<void>;
+ /**
+ * Resolves `false` when the caller may not switch right now (locked, or
+ * access/preference still loading), so nothing was written.
+ */
+ selectModel: (selection: ModelSelection, options?: SelectModelOptions) => Promise<boolean>;
usesWorkspaceMemberSelection: boolean;
}
@@ -115,11 +130,11 @@ export const useAgentModelSelection = (agentId: string): UseAgentModelSelectionR
: undefined;
const selectModel = useCallback(
- async (selection: ModelSelection) => {
- if (!canSelectModel) return;
+ async (selection: ModelSelection, options?: SelectModelOptions) => {
+ if (!canSelectModel) return false;
if (usesWorkspaceMemberSelection) {
- if (selectionPolicy !== 'member' || isLoading) return;
+ if (selectionPolicy !== 'member' || isLoading) return false;
await updateWorkspaceUserPreference({
agentModelOverrides: {
@@ -127,10 +142,11 @@ export const useAgentModelSelection = (agentId: string): UseAgentModelSelectionR
[agentId]: selection,
},
});
- return;
+ return true;
}
- await updateAgentConfigById(agentId, applyBusinessModelModeConfig(selection));
+ await updateAgentConfigById(agentId, applyBusinessModelModeConfig(selection), options);
+ return true;
},
[
agentId,
diff --git a/src/features/ChatInput/hooks/useChatInputResourceAccess.ts b/src/features/ChatInput/hooks/useChatInputResourceAccess.ts
index 29c5313e574..a1ecf27fa1f 100644
--- a/src/features/ChatInput/hooks/useChatInputResourceAccess.ts
+++ b/src/features/ChatInput/hooks/useChatInputResourceAccess.ts
@@ -10,7 +10,8 @@ import { builtinAgentSelectors } from '@/store/agent/selectors';
import { useAgentGroupStore } from '@/store/agentGroup';
import { agentGroupSelectors } from '@/store/agentGroup/selectors';
-import { type State, useChatInputStoreApiOptional } from '../store';
+import { type State } from '../store';
+import { useChatInputStoreApiOptional } from '../store/apiContext';
const EMPTY_SUBSCRIBE = () => () => {};
diff --git a/src/features/ChatInput/store/apiContext.ts b/src/features/ChatInput/store/apiContext.ts
new file mode 100644
index 00000000000..b256e37a063
--- /dev/null
+++ b/src/features/ChatInput/store/apiContext.ts
@@ -0,0 +1,24 @@
+'use client';
+
+import { type StoreApiWithSelector } from '@lobechat/types';
+import { createContext, useContext } from 'react';
+
+import { type Store } from './action';
+
+// Kept apart from `./index` (which pulls the store actions, and with them the
+// editor) so Home cold-path hooks such as `useAgentModelSelection` can read it.
+
+/**
+ * Parallel context that mirrors the ChatInput store api. zustand-utils' own
+ * context throws ("...used zustand provider as an ancestor.") when read without
+ * a Provider, so it cannot answer "is there a store here?". Components reused
+ * outside a chat input β€” e.g. the image/video generation prompt reuses
+ * ChatInput's <Action> β€” read this to degrade gracefully instead of crashing.
+ */
+export const ChatInputStoreApiContext = createContext<StoreApiWithSelector<Store> | undefined>(
+ undefined,
+);
+
+/** The ChatInput store api, or `undefined` when rendered outside a Provider. */
+export const useChatInputStoreApiOptional = (): StoreApiWithSelector<Store> | undefined =>
+ useContext(ChatInputStoreApiContext);
diff --git a/src/features/ChatInput/store/index.ts b/src/features/ChatInput/store/index.ts
index 08d218f61dd..08b759a409e 100644
--- a/src/features/ChatInput/store/index.ts
+++ b/src/features/ChatInput/store/index.ts
@@ -1,13 +1,7 @@
'use client';
import { type StoreApiWithSelector } from '@lobechat/types';
-import {
- createContext as createReactContext,
- createElement,
- type ReactNode,
- useContext,
- useRef,
-} from 'react';
+import { createElement, type ReactNode, useRef } from 'react';
import { subscribeWithSelector } from 'zustand/middleware';
import { shallow } from 'zustand/shallow';
import { createWithEqualityFn } from 'zustand/traditional';
@@ -15,6 +9,7 @@ import { createContext } from 'zustand-utils';
import { type Store } from './action';
import { store } from './action';
+import { ChatInputStoreApiContext } from './apiContext';
import { type State } from './initialState';
export type { PublicState, State } from './initialState';
@@ -30,20 +25,7 @@ const {
export { useChatInputStore, useStoreApi };
-/**
- * Parallel context that mirrors the ChatInput store api. zustand-utils' own
- * context throws ("...used zustand provider as an ancestor.") when read without
- * a Provider, so it cannot answer "is there a store here?". Components reused
- * outside a chat input β€” e.g. the image/video generation prompt reuses
- * ChatInput's <Action> β€” read this to degrade gracefully instead of crashing.
- */
-const ChatInputStoreApiContext = createReactContext<StoreApiWithSelector<Store> | undefined>(
- undefined,
-);
-
-/** The ChatInput store api, or `undefined` when rendered outside a Provider. */
-export const useChatInputStoreApiOptional = (): StoreApiWithSelector<Store> | undefined =>
- useContext(ChatInputStoreApiContext);
+export { useChatInputStoreApiOptional } from './apiContext';
/**
* Wraps zustand-utils' Provider and additionally publishes the same store
diff --git a/src/features/Home/NewModelShortcuts/index.tsx b/src/features/Home/NewModelShortcuts/index.tsx
index dfe5bf1b98a..8cdfce5e5d8 100644
--- a/src/features/Home/NewModelShortcuts/index.tsx
+++ b/src/features/Home/NewModelShortcuts/index.tsx
@@ -8,22 +8,18 @@ import {
Text,
toast,
} from '@lobehub/ui';
-import { useCallback, useState } from 'react';
+import { useState } from 'react';
import { useTranslation } from 'react-i18next';
-import type { BusinessModelModeConfig } from '@/business/client/hooks/useBusinessAgentMode';
-import { useBusinessModelModeConfig } from '@/business/client/hooks/useBusinessAgentMode';
import type { HomeNewModelItem } from '@/business/client/hooks/useHomeNewModels';
import { useHomeNewModels } from '@/business/client/hooks/useHomeNewModels';
import { ModelIcon } from '@/components/LobeIcons';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { usePermission } from '@/hooks/usePermission';
-import { agentService } from '@/services/agent';
-import { useAgentStore } from '@/store/agent';
-import { agentByIdSelectors } from '@/store/agent/selectors';
import { useResolvedHomeAgentId } from '../AgentSelect/useResolvedHomeAgentId';
import { InputBanner } from '../InputArea/InputBanner';
+import { useHomeModelSwitch } from '../useHomeModelSwitch';
import { trackHomeModelShortcutClicked } from './analytics';
import { getShortcutIconModelId } from './getShortcutIconModelId';
import { useStarterModelDefaults } from './useStarterModelDefaults';
@@ -75,87 +71,51 @@ export const NewModelShortcuts = () => {
const navigate = useWorkspaceAwareNavigate();
const { agentId: activeAgentId } = useResolvedHomeAgentId();
const { allowed: canCreateContent } = usePermission('create_content');
- const updateAgentConfigById = useAgentStore((state) => state.updateAgentConfigById);
- const currentModel = useAgentStore((state) =>
- agentByIdSelectors.getAgentModelById(activeAgentId ?? '')(state),
- );
- const currentProvider = useAgentStore((state) =>
- agentByIdSelectors.getAgentModelProviderById(activeAgentId ?? '')(state),
- );
+ const {
+ isReady,
+ lockTip,
+ model: currentModel,
+ provider: currentProvider,
+ switchModel,
+ } = useHomeModelSwitch(activeAgentId);
const [switchingKey, setSwitchingKey] = useState<string | null>(null);
const { defaultHomeNewModels, fallbackChatProvider } = useStarterModelDefaults();
const { isLoading, items } = useHomeNewModels([...defaultHomeNewModels]);
- const applyBusinessModelModeConfig = useBusinessModelModeConfig();
-
- const handleClick = useCallback(
- async (item: HomeNewModelItem) => {
- if (!canCreateContent) return;
-
- const key = getShortcutKey(item);
- const selectedProvider =
- item.type === 'chat' ? getShortcutProvider(item, fallbackChatProvider) : item.provider;
- void trackHomeModelShortcutClicked({ item, provider: selectedProvider });
-
- if (item.type === 'video') {
- navigate(`/video?model=${item.model}`);
- return;
- }
-
- if (item.type === 'image') {
- navigate(`/image?model=${item.model}`);
- return;
- }
-
- if (!activeAgentId || switchingKey) return;
-
- setSwitchingKey(key);
- const provider = getShortcutProvider(item, fallbackChatProvider);
- try {
- // Hydrate before the optimistic write so updating the selected model
- // cannot drop fields the Home surface has not loaded yet.
- let agentState = useAgentStore.getState();
- if (!agentState.agentMap[activeAgentId]) {
- const config = await agentService.getAgentConfigById(activeAgentId);
- if (config) agentState.internal_dispatchAgentMap(activeAgentId, config);
- agentState = useAgentStore.getState();
- }
-
- const nextConfig: BusinessModelModeConfig = applyBusinessModelModeConfig({
- model: item.model,
- provider,
- });
- const shouldUpdateAgentMode =
- nextConfig.chatConfig?.enableAgentMode === false &&
- agentByIdSelectors.getAgentEnableModeById(activeAgentId)(agentState);
-
- if (currentModel === item.model && currentProvider === provider && !shouldUpdateAgentMode) {
- toast.info(t('starter.modelInUse', { name: item.title }));
- return;
- }
-
- try {
- await updateAgentConfigById(activeAgentId, nextConfig, { rethrow: true });
- toast.success(t('starter.modelSwitched', { name: item.title }));
- } catch {
- // The agent store reports persistence failures at the action boundary.
- }
- } finally {
- setSwitchingKey(null);
- }
- },
- [
- activeAgentId,
- applyBusinessModelModeConfig,
- canCreateContent,
- currentModel,
- currentProvider,
- fallbackChatProvider,
- navigate,
- switchingKey,
- t,
- updateAgentConfigById,
- ],
- );
+
+ const handleClick = async (item: HomeNewModelItem) => {
+ if (!canCreateContent) return;
+
+ const key = getShortcutKey(item);
+ const selectedProvider =
+ item.type === 'chat' ? getShortcutProvider(item, fallbackChatProvider) : item.provider;
+ void trackHomeModelShortcutClicked({ item, provider: selectedProvider });
+
+ if (item.type === 'video') {
+ navigate(`/video?model=${item.model}`);
+ return;
+ }
+
+ if (item.type === 'image') {
+ navigate(`/image?model=${item.model}`);
+ return;
+ }
+
+ if (!activeAgentId || switchingKey) return;
+
+ setSwitchingKey(key);
+ try {
+ const result = await switchModel({
+ model: item.model,
+ provider: getShortcutProvider(item, fallbackChatProvider),
+ });
+ if (result === 'inUse') toast.info(t('starter.modelInUse', { name: item.title }));
+ if (result === 'switched') toast.success(t('starter.modelSwitched', { name: item.title }));
+ if (result === 'locked' && lockTip) toast.info(lockTip);
+ if (result === 'failed') toast.error(t('saveAgentConfigFail', { ns: 'common' }));
+ } finally {
+ setSwitchingKey(null);
+ }
+ };
if (!canCreateContent || (!isLoading && items.length === 0)) return null;
@@ -187,7 +147,8 @@ export const NewModelShortcuts = () => {
<Button
aria-pressed={item.type === 'chat' ? isCurrent : undefined}
className={cx(styles.button, isCurrent && styles.active)}
- disabled={!!switchingKey && !isSwitching}
+ // Chat shortcuts wait for the Agent's model selection to load.
+ disabled={(!!switchingKey && !isSwitching) || (item.type === 'chat' && !isReady)}
key={key}
loading={isSwitching}
type={'text'}
diff --git a/src/features/Home/useHomeModelSwitch.test.ts b/src/features/Home/useHomeModelSwitch.test.ts
new file mode 100644
index 00000000000..f47c9b6404b
--- /dev/null
+++ b/src/features/Home/useHomeModelSwitch.test.ts
@@ -0,0 +1,148 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useHomeModelSwitch } from './useHomeModelSwitch';
+
+const testState = vi.hoisted(() => ({
+ agent: {
+ agentMap: { 'agent-1': {} } as Record<string, object>,
+ enableAgentMode: false,
+ updateAgentConfigById: vi.fn(),
+ },
+ modeConfig: {} as { chatConfig?: { enableAgentMode?: boolean } },
+ selection: {
+ canDisplayModel: true,
+ canSelectModel: true,
+ model: 'shared-model',
+ provider: 'lobehub',
+ selectModel: vi.fn(),
+ selectionLockReason: undefined as 'fixedByAgent' | 'useOnly' | undefined,
+ usesWorkspaceMemberSelection: false,
+ },
+}));
+
+vi.mock('@/business/client/hooks/useBusinessAgentMode', () => ({
+ useBusinessModelModeConfig: () => (config: object) => ({ ...config, ...testState.modeConfig }),
+}));
+
+vi.mock('@/features/ChatInput/hooks/useAgentModelSelection', () => ({
+ useAgentModelSelection: () => testState.selection,
+}));
+
+vi.mock('@/store/agent', () => {
+ const useAgentStore = (selector: (s: typeof testState.agent) => unknown) =>
+ selector(testState.agent);
+ useAgentStore.getState = () => testState.agent;
+ return { useAgentStore };
+});
+
+vi.mock('@/store/agent/selectors', () => ({
+ agentByIdSelectors: {
+ getAgentEnableModeById: () => (s: typeof testState.agent) => s.enableAgentMode,
+ },
+}));
+
+const target = { model: 'minimax-m3.1-flash', provider: 'lobehub' };
+
+describe('useHomeModelSwitch', () => {
+ beforeEach(() => {
+ testState.agent.agentMap = { 'agent-1': {} };
+ testState.agent.enableAgentMode = false;
+ testState.agent.updateAgentConfigById = vi.fn();
+ testState.modeConfig = {};
+ testState.selection = {
+ canDisplayModel: true,
+ canSelectModel: true,
+ model: 'shared-model',
+ provider: 'lobehub',
+ selectModel: vi.fn().mockResolvedValue(true),
+ selectionLockReason: undefined,
+ usesWorkspaceMemberSelection: false,
+ };
+ });
+
+ it('reads and writes the member override on a shared Workspace Agent', async () => {
+ // The Workspace Inbox: the input trigger shows the member's own pick, not
+ // the Agent row's model.
+ testState.selection.model = 'gemini-4-argon';
+ testState.selection.usesWorkspaceMemberSelection = true;
+
+ const { result } = renderHook(() => useHomeModelSwitch('agent-1'));
+ expect(result.current.model).toBe('gemini-4-argon');
+
+ let outcome: string | undefined;
+ await act(async () => {
+ outcome = await result.current.switchModel(target);
+ });
+
+ expect(outcome).toBe('switched');
+ expect(testState.selection.selectModel).toHaveBeenCalledWith(target, {
+ rethrow: true,
+ showErrorMessage: false,
+ });
+ expect(testState.agent.updateAgentConfigById).not.toHaveBeenCalled();
+ });
+
+ it('reports the model in use against the member override', async () => {
+ testState.selection.model = target.model;
+ testState.selection.usesWorkspaceMemberSelection = true;
+ // Leaving Agent mode never applies to a member override.
+ testState.modeConfig = { chatConfig: { enableAgentMode: false } };
+ testState.agent.enableAgentMode = true;
+
+ const { result } = renderHook(() => useHomeModelSwitch('agent-1'));
+
+ await expect(result.current.switchModel(target)).resolves.toBe('inUse');
+ expect(testState.selection.selectModel).not.toHaveBeenCalled();
+ });
+
+ it('still switches the Agent row out of Agent mode for the same model', async () => {
+ testState.selection.model = target.model;
+ testState.modeConfig = { chatConfig: { enableAgentMode: false } };
+ testState.agent.enableAgentMode = true;
+
+ const { result } = renderHook(() => useHomeModelSwitch('agent-1'));
+
+ await expect(result.current.switchModel(target)).resolves.toBe('switched');
+ });
+
+ it('waits for the Agent config before switching', async () => {
+ testState.agent.agentMap = {};
+
+ const { result } = renderHook(() => useHomeModelSwitch('agent-1'));
+
+ expect(result.current.isReady).toBe(false);
+ await expect(result.current.switchModel(target)).resolves.toBe('loading');
+ expect(testState.selection.selectModel).not.toHaveBeenCalled();
+ });
+
+ it('waits for access and the member preference before switching', async () => {
+ testState.selection.canDisplayModel = false;
+ testState.selection.canSelectModel = false;
+
+ const { result } = renderHook(() => useHomeModelSwitch('agent-1'));
+
+ expect(result.current.isReady).toBe(false);
+ await expect(result.current.switchModel(target)).resolves.toBe('loading');
+ expect(testState.selection.selectModel).not.toHaveBeenCalled();
+ });
+
+ it('reports a locked model with the reason the input trigger shows', async () => {
+ testState.selection.canSelectModel = false;
+ testState.selection.selectionLockReason = 'fixedByAgent';
+
+ const { result } = renderHook(() => useHomeModelSwitch('agent-1'));
+
+ expect(result.current.lockTip).toBe('chat:input.modelFixedTip');
+ await expect(result.current.switchModel(target)).resolves.toBe('locked');
+ expect(testState.selection.selectModel).not.toHaveBeenCalled();
+ });
+
+ it('reports a rejected write as failed', async () => {
+ testState.selection.selectModel = vi.fn().mockRejectedValue(new Error('denied'));
+
+ const { result } = renderHook(() => useHomeModelSwitch('agent-1'));
+
+ await expect(result.current.switchModel(target)).resolves.toBe('failed');
+ });
+});
diff --git a/src/features/Home/useHomeModelSwitch.ts b/src/features/Home/useHomeModelSwitch.ts
new file mode 100644
index 00000000000..a28bdfae0f5
--- /dev/null
+++ b/src/features/Home/useHomeModelSwitch.ts
@@ -0,0 +1,88 @@
+import { useTranslation } from 'react-i18next';
+
+import type { BusinessModelModeConfig } from '@/business/client/hooks/useBusinessAgentMode';
+import { useBusinessModelModeConfig } from '@/business/client/hooks/useBusinessAgentMode';
+import { useAgentModelSelection } from '@/features/ChatInput/hooks/useAgentModelSelection';
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+
+interface ModelTarget {
+ model: string;
+ provider: string;
+}
+
+/**
+ * - `inUse`: already the caller's model, nothing written.
+ * - `switched`: the caller's model now is the target.
+ * - `loading`: the Agent, its access or the caller's preference is still
+ * loading (see `isReady`), nothing written.
+ * - `locked`: the caller may not switch this Agent's model (see `lockTip`).
+ * - `failed`: the write was rejected.
+ */
+export type HomeModelSwitchResult = 'failed' | 'inUse' | 'loading' | 'locked' | 'switched';
+
+/**
+ * Switch the Home Agent's model from a Home entry point (new-model shortcuts,
+ * model promos) through the same read/write path as the input's model trigger.
+ *
+ * A shared Workspace Agent such as the Workspace Inbox keeps a per-member model
+ * override. Writing its Agent row instead would leave the trigger (and the chat
+ * page) on the member's old model and repoint every other member's default.
+ */
+export const useHomeModelSwitch = (agentId: string | undefined) => {
+ const selection = useAgentModelSelection(agentId ?? '');
+ const isAgentLoaded = useAgentStore((s) => !!agentId && !!s.agentMap[agentId]);
+ const applyBusinessModelModeConfig = useBusinessModelModeConfig();
+ const { t } = useTranslation(['chat', 'setting']);
+
+ // `selection` resolves from the loaded Agent row (whether the caller edits
+ // the row or their own override); acting before it loads would pick the
+ // wrong target. `canDisplayModel` settles once access and preference load.
+ const isReady = !!agentId && isAgentLoaded && selection.canDisplayModel;
+ // Same wording as the input's locked model trigger (`useModelLockTooltip`).
+ const lockTip =
+ selection.selectionLockReason === 'fixedByAgent'
+ ? t('chat:input.modelFixedTip')
+ : selection.selectionLockReason === 'useOnly'
+ ? t('setting:permission.accessTag.useOnlyTip')
+ : undefined;
+
+ const switchModel = async (target: ModelTarget): Promise<HomeModelSwitchResult> => {
+ if (!agentId || !isReady) return 'loading';
+ if (!selection.canSelectModel) return 'locked';
+
+ // The model-mode side effect (e.g. leaving Agent mode) only applies to the
+ // Agent row; a member override stores the model alone.
+ const nextConfig: BusinessModelModeConfig = applyBusinessModelModeConfig(target);
+ const shouldUpdateAgentMode =
+ !selection.usesWorkspaceMemberSelection &&
+ nextConfig.chatConfig?.enableAgentMode === false &&
+ agentByIdSelectors.getAgentEnableModeById(agentId)(useAgentStore.getState());
+
+ if (
+ selection.model === target.model &&
+ selection.provider === target.provider &&
+ !shouldUpdateAgentMode
+ )
+ return 'inUse';
+
+ try {
+ const switched = await selection.selectModel(target, {
+ rethrow: true,
+ showErrorMessage: false,
+ });
+ // `false` only when the preference was still settling.
+ return switched ? 'switched' : 'loading';
+ } catch {
+ return 'failed';
+ }
+ };
+
+ return {
+ isReady,
+ lockTip,
+ model: selection.model,
+ provider: selection.provider,
+ switchModel,
+ };
+};