🤯 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: enable disabled models from chat input (#18730)
YuTengjing32285e8f772a
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex e4c490a6382..8f84a9264a1 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -787,6 +787,10 @@"input.inputCompletionError.retry": "Retry","input.inputCompletionError.settings": "Settings","input.inputCompletionError.title": "Input suggestions paused",+ "input.modelDisabled": "The current model is disabled",+ "input.modelDisabled.action": "Enable",+ "input.modelDisabled.actionFailed": "Failed to enable the model. Please try again.",+ "input.modelDisabled.selectionFailed": "The model was enabled, but switching providers failed. Select it again to continue.","input.modelFixedTip": "The model is fixed in the Agent Profile and cannot be switched while chatting.","input.modelUnavailable": "The current model is no longer available. Choose another model to continue.","input.more": "More",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex fee77a0dd9e..dd43bacd399 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -787,6 +787,10 @@"input.inputCompletionError.retry": "重试","input.inputCompletionError.settings": "设置","input.inputCompletionError.title": "输入补全已暂停",+ "input.modelDisabled": "当前模型已禁用",+ "input.modelDisabled.action": "启用",+ "input.modelDisabled.actionFailed": "启用模型失败,请重试。",+ "input.modelDisabled.selectionFailed": "模型已启用,但切换服务商失败。请重新选择该模型后继续。","input.modelFixedTip": "模型已在助理档案中固定,聊天时不可切换。","input.modelUnavailable": "当前模型已下线。请选择其他模型后继续使用。","input.more": "更多",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex e82f6153cc7..7a787522c0b 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -630,6 +630,11 @@ export default {'input.inputCompletionError.title': 'Input suggestions paused','input.modelFixedTip':'The model is fixed in the Agent Profile and cannot be switched while chatting.',+ 'input.modelDisabled': 'The current model is disabled',+ 'input.modelDisabled.action': 'Enable',+ 'input.modelDisabled.actionFailed': 'Failed to enable the model. Please try again.',+ 'input.modelDisabled.selectionFailed':+ 'The model was enabled, but switching providers failed. Select it again to continue.','input.modelUnavailable':'The current model is no longer available. Choose another model to continue.','input.viewOnlyAgent': 'You can only view this agent',diff --git a/src/features/ChatInput/ChatInputNotice/index.tsx b/src/features/ChatInput/ChatInputNotice/index.tsxindex a1aca5ddb0a..a7d34a99921 100644--- a/src/features/ChatInput/ChatInputNotice/index.tsx+++ b/src/features/ChatInput/ChatInputNotice/index.tsx@@ -1,6 +1,7 @@'use client';-import { Alert } from '@lobehub/ui/base-ui';+import { Tooltip } from '@lobehub/ui';+import { Alert, Button } from '@lobehub/ui/base-ui';import { createStaticStyles, cx } from 'antd-style';import { memo } from 'react';import { useTranslation } from 'react-i18next';@@ -8,6 +9,14 @@ import { useTranslation } from 'react-i18next';import { useChatInputNotice } from './useChatInputNotice';const styles = createStaticStyles(({ css, cssVar }) => ({+ action: css`+ flex: none;+ height: 24px;+ padding-inline: 10px;+ `,+ actionWrapper: css`+ display: inline-flex;+ `,alert: css`flex: 0 1 auto;@@ -28,16 +37,6 @@ const styles = createStaticStyles(({ css, cssVar }) => ({min-width: 0;}- .ant-alert-message,- .ant-alert-title {- overflow: hidden;-- font-size: 12px;- line-height: 18px !important;- text-overflow: ellipsis;- white-space: nowrap;- }-.ant-alert-icon {flex: none;height: 18px !important;@@ -48,6 +47,16 @@ const styles = createStaticStyles(({ css, cssVar }) => ({max-width: 100%;}`,+ title: css`+ overflow: hidden;++ min-width: 0;++ font-size: 12px;+ line-height: 18px !important;+ text-overflow: ellipsis;+ white-space: nowrap;+ `,}));const ChatInputNotice = memo(() => {@@ -56,9 +65,32 @@ const ChatInputNotice = memo(() => {if (!notice) return null;+ const enableButton = notice.action === 'enableModel' && (+ <Button+ className={styles.action}+ disabled={notice.actionDisabled}+ loading={notice.actionLoading}+ size={'small'}+ type={'primary'}+ onClick={() => void notice.onAction?.()}+ >+ {t('input.modelDisabled.action')}+ </Button>+ );++ const action =+ enableButton && notice.actionDisabled ? (+ <Tooltip title={notice.actionDisabledReason}>+ <span className={styles.actionWrapper}>{enableButton}</span>+ </Tooltip>+ ) : (+ enableButton+ );+return (<Alert- classNames={{ alert: cx(styles.alert) }}+ action={action}+ classNames={{ alert: cx(styles.alert), title: styles.title }}style={{ fontSize: 12 }}title={t(notice.key)}type={notice.type}diff --git a/src/features/ChatInput/ChatInputNotice/useChatInputNotice.test.tsx b/src/features/ChatInput/ChatInputNotice/useChatInputNotice.test.tsxindex 05ca9c3b933..27da52ab322 100644--- a/src/features/ChatInput/ChatInputNotice/useChatInputNotice.test.tsx+++ b/src/features/ChatInput/ChatInputNotice/useChatInputNotice.test.tsx@@ -1,8 +1,10 @@-import { renderHook } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { useChatInputNotice } from './useChatInputNotice';+const { toastError } = vi.hoisted(() => ({ toastError: vi.fn() }));+interface TestModel {abilities?: {functionCall?: boolean;@@ -15,27 +17,43 @@ interface TestProviderWithModels {id: string;}+interface TestBuiltinModel {+ id: string;+ providerId: string;+ type: 'chat';+}+const testState = vi.hoisted(() => ({agent: {agencyConfig: undefined as- | { executionTarget?: string; heterogeneousProvider?: { type: string } }- | undefined,+ { executionTarget?: string; heterogeneousProvider?: { type: string } } | undefined,isConfigLoading: false,model: 'gpt-4o',provider: 'openai',},/** Effective (override-resolved) selection, as `useAgentModelSelection` returns it. */agentModelSelection: {+ canSelectModel: true,isPreferenceLoading: false,model: undefined as string | undefined,provider: undefined as string | undefined,+ selectModel: vi.fn(async () => {}),selectionPolicy: 'fixed' as 'fixed' | 'member',},aiInfra: {+ builtinAiModelList: [] as TestBuiltinModel[],enabledChatModelList: [] as TestProviderWithModels[],+ enabledAiProviders: [] as { id: string }[],isInitAiProviderRuntimeState: false,+ modelRedirects: {} as Record<string, string>,+ toggleProviderEnabled: vi.fn(async () => {}),+ toggleProviderModelEnabled: vi.fn(async () => {}),},isDesktop: false,+ permission: {+ canManageAiInfra: true,+ reason: undefined as string | undefined,+ },resourceAccess: {canConfigureResource: true,isAccessLoading: false,@@ -54,17 +72,21 @@ vi.mock('@lobechat/const', () => ({},}));+vi.mock('@lobehub/ui/base-ui', () => ({ toast: { error: toastError } }));+vi.mock('@/features/ChatInput/hooks/useAgentId', () => ({useAgentId: () => 'agent-id',}));vi.mock('@/features/ChatInput/hooks/useAgentModelSelection', () => ({useAgentModelSelection: () => ({+ canSelectModel: testState.agentModelSelection.canSelectModel,isPreferenceLoading: testState.agentModelSelection.isPreferenceLoading,// Default to the shared agent config, matching `resolveAgentModelConfig`// when there is no member override.model: testState.agentModelSelection.model ?? testState.agent.model,provider: testState.agentModelSelection.provider ?? testState.agent.provider,+ selectModel: testState.agentModelSelection.selectModel,selectionPolicy: testState.agentModelSelection.selectionPolicy,}),}));@@ -77,6 +99,13 @@ vi.mock('@/hooks/useEnabledChatModels', () => ({useEnabledChatModels: () => testState.aiInfra.enabledChatModelList,}));+vi.mock('@/hooks/usePermission', () => ({+ usePermission: () => ({+ allowed: testState.permission.canManageAiInfra,+ reason: testState.permission.reason,+ }),+}));+vi.mock('@/store/agent', () => ({useAgentStore: <T,>(selector: StoreSelector<T, typeof testState.agent>) =>selector(testState.agent),@@ -99,20 +128,34 @@ vi.mock('@/store/aiInfra', () => ({}));describe('useChatInputNotice', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });+beforeEach(() => {testState.agent.agencyConfig = undefined;testState.agent.isConfigLoading = false;testState.agentModelSelection = {+ canSelectModel: true,isPreferenceLoading: false,model: undefined,provider: undefined,+ selectModel: vi.fn(async () => {}),selectionPolicy: 'fixed',};testState.agent.model = 'gpt-4o';testState.agent.provider = 'openai';+ testState.aiInfra.builtinAiModelList = [];testState.aiInfra.enabledChatModelList = [];+ testState.aiInfra.enabledAiProviders = [];testState.aiInfra.isInitAiProviderRuntimeState = false;+ testState.aiInfra.modelRedirects = {};+ testState.aiInfra.toggleProviderEnabled.mockReset();+ testState.aiInfra.toggleProviderModelEnabled.mockReset();+ toastError.mockReset();testState.isDesktop = false;+ testState.permission.canManageAiInfra = true;+ testState.permission.reason = undefined;testState.resourceAccess = {canConfigureResource: true,isAccessLoading: false,@@ -226,6 +269,132 @@ describe('useChatInputNotice', () => {expect(result.current).toEqual({ key: 'input.modelUnavailable', type: 'warning' });});+ it('offers to enable a model that still exists but is disabled', async () => {+ testState.aiInfra.isInitAiProviderRuntimeState = true;+ testState.aiInfra.builtinAiModelList = [{ id: 'gpt-4o', providerId: 'openai', type: 'chat' }];+ testState.aiInfra.enabledChatModelList = [{ children: [{ id: 'gpt-4.1' }], id: 'openai' }];+ testState.aiInfra.enabledAiProviders = [{ id: 'openai' }];++ const { result } = renderHook(() => useChatInputNotice());++ expect(result.current).toMatchObject({+ action: 'enableModel',+ actionLoading: false,+ key: 'input.modelDisabled',+ type: 'warning',+ });++ await act(async () => result.current?.onAction?.());++ expect(testState.aiInfra.toggleProviderEnabled).not.toHaveBeenCalled();+ expect(testState.aiInfra.toggleProviderModelEnabled).toHaveBeenCalledWith({+ enabled: true,+ id: 'gpt-4o',+ providerId: 'openai',+ type: 'chat',+ });+ });++ it('disables Enable with the permission reason when the member cannot manage AI infrastructure', () => {+ testState.permission.canManageAiInfra = false;+ testState.permission.reason = 'Requires admin permission';+ testState.aiInfra.isInitAiProviderRuntimeState = true;+ testState.aiInfra.builtinAiModelList = [{ id: 'gpt-4o', providerId: 'openai', type: 'chat' }];+ testState.aiInfra.enabledChatModelList = [{ children: [{ id: 'gpt-4.1' }], id: 'openai' }];+ testState.aiInfra.enabledAiProviders = [{ id: 'openai' }];++ const { result } = renderHook(() => useChatInputNotice());++ expect(result.current).toEqual({+ action: 'enableModel',+ actionDisabled: true,+ actionDisabledReason: 'Requires admin permission',+ actionLoading: false,+ key: 'input.modelDisabled',+ onAction: undefined,+ type: 'warning',+ });+ });++ it('enables the owning provider before enabling its disabled model', async () => {+ testState.aiInfra.isInitAiProviderRuntimeState = true;+ testState.aiInfra.builtinAiModelList = [{ id: 'gpt-4o', providerId: 'openai', type: 'chat' }];++ const { result } = renderHook(() => useChatInputNotice());++ await act(async () => result.current?.onAction?.());++ expect(testState.aiInfra.toggleProviderEnabled).toHaveBeenCalledWith('openai', true);+ expect(testState.aiInfra.toggleProviderModelEnabled).toHaveBeenCalledWith({+ enabled: true,+ id: 'gpt-4o',+ providerId: 'openai',+ type: 'chat',+ });+ });++ it('treats a disabled model as unavailable when a locked selection would require a provider fallback', () => {+ testState.agent.provider = 'removed-provider';+ testState.agentModelSelection.canSelectModel = false;+ testState.aiInfra.isInitAiProviderRuntimeState = true;+ testState.aiInfra.builtinAiModelList = [{ id: 'gpt-4o', providerId: 'openai', type: 'chat' }];++ const { result } = renderHook(() => useChatInputNotice());++ expect(result.current).toEqual({ key: 'input.modelUnavailable', type: 'warning' });+ });++ it('enables and selects a fallback provider when the selection is editable', async () => {+ testState.agent.provider = 'removed-provider';+ testState.aiInfra.isInitAiProviderRuntimeState = true;+ testState.aiInfra.builtinAiModelList = [{ id: 'gpt-4o', providerId: 'openai', type: 'chat' }];++ const { result } = renderHook(() => useChatInputNotice());++ await act(async () => result.current?.onAction?.());++ expect(testState.aiInfra.toggleProviderEnabled).toHaveBeenCalledWith('openai', true);+ expect(testState.aiInfra.toggleProviderModelEnabled).toHaveBeenCalledWith({+ enabled: true,+ id: 'gpt-4o',+ providerId: 'openai',+ type: 'chat',+ });+ expect(testState.agentModelSelection.selectModel).toHaveBeenCalledWith({+ model: 'gpt-4o',+ provider: 'openai',+ });+ });++ it('reports a provider selection failure separately after enabling the fallback model', async () => {+ const selectionError = new Error('selection failed');+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ testState.agent.provider = 'removed-provider';+ testState.agentModelSelection.selectModel = vi.fn(async () => {+ throw selectionError;+ });+ testState.aiInfra.isInitAiProviderRuntimeState = true;+ 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(toastError).toHaveBeenCalledWith(+ expect.stringMatching(/selectionFailed|switching providers failed/),+ );+ expect(consoleError).toHaveBeenCalledWith(+ 'Failed to select the enabled chat model provider:',+ selectionError,+ );+ });+it('does not return unavailable model copy while the agent config is still loading', () => {// Cold page load: runtime config is ready but `agentMap` has no entry yet,// so the model selectors still report the DEFAULT_MODEL fallback.diff --git a/src/features/ChatInput/ChatInputNotice/useChatInputNotice.ts b/src/features/ChatInput/ChatInputNotice/useChatInputNotice.tsindex ee9d96672ac..5d11bc1cc3a 100644--- a/src/features/ChatInput/ChatInputNotice/useChatInputNotice.ts+++ b/src/features/ChatInput/ChatInputNotice/useChatInputNotice.ts@@ -1,7 +1,16 @@+import { toast } from '@lobehub/ui/base-ui';+import { useCallback, useMemo, useState } from 'react';+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 {+ resolveEnableTargetProviderId,+ resolveStaleModelState,+} from '@/features/ModelSelect/resolveStaleModelState';import { useEnabledChatModels } from '@/hooks/useEnabledChatModels';+import { usePermission } from '@/hooks/usePermission';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';import { aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';@@ -13,6 +22,7 @@ interface ResolveChatInputNoticeParams {isGroupContext?: boolean;isHeterogeneousAgent: boolean;isModelConfigReady: boolean;+ isModelDisabled?: boolean;isResourceViewOnly?: boolean;}@@ -31,6 +41,7 @@ export const resolveChatInputNotice = ({isAgentModelPending,isGroupContext,isHeterogeneousAgent,+ isModelDisabled,isModelConfigReady,isResourceViewOnly,}: ResolveChatInputNoticeParams) => {@@ -57,8 +68,16 @@ export const resolveChatInputNotice = ({!isAgentModelPending && // 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- )+ ) {+ if (isModelDisabled)+ return {+ action: 'enableModel' as const,+ key: 'input.modelDisabled',+ type: 'warning',+ } as const;+return { action: undefined, key: 'input.modelUnavailable', type: 'warning' } as const;+ }// Use-level General access (can chat, can't edit the shared config) is// deliberately NOT a notice: a standing "you can only use this agent" banner@@ -68,10 +87,19 @@ export const resolveChatInputNotice = ({};/** Union of every notice shape `resolveChatInputNotice` can return. */-export type ChatInputNotice = NonNullable<ReturnType<typeof resolveChatInputNotice>>;+export type ChatInputNotice = NonNullable<ReturnType<typeof resolveChatInputNotice>> & {+ actionDisabled?: boolean;+ actionDisabledReason?: string;+ actionLoading?: boolean;+ onAction?: () => Promise<void>;+};export const useChatInputNotice = (): ChatInputNotice | undefined => {+ const { t } = useTranslation('chat');+ const { allowed: canManageAiInfra, reason: aiInfraPermissionReason } =+ usePermission('manage_provider_key');const agentId = useAgentId();+ const [actionLoading, setActionLoading] = useState(false);const [isAgentConfigLoading, isHeterogeneousAgent] = useAgentStore((s) => [agentByIdSelectors.isAgentConfigLoadingById(agentId)(s),@@ -80,7 +108,8 @@ 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 { isPreferenceLoading, model, provider, selectionPolicy } = useAgentModelSelection(agentId);+ const { canSelectModel, isPreferenceLoading, model, provider, selectModel, selectionPolicy } =+ useAgentModelSelection(agentId);// `isPreferenceLoading` is true for every workspace agent while the shared// preferences request is in flight, but the override only feeds the@@ -89,18 +118,107 @@ export const useChatInputNotice = (): ChatInputNotice | undefined => {const isMemberOverridePending = selectionPolicy === 'member' && isPreferenceLoading;const enabledChatModelList = useEnabledChatModels();+ const builtinAiModelList = useAiInfraStore((s) => s.builtinAiModelList);+ const enabledAiProviders = useAiInfraStore((s) => s.enabledAiProviders);+ const modelRedirects = useAiInfraStore((s) => s.modelRedirects);+ const toggleProviderEnabled = useAiInfraStore((s) => s.toggleProviderEnabled);+ const toggleProviderModelEnabled = useAiInfraStore((s) => s.toggleProviderModelEnabled);const isModelConfigReady = useAiInfraStore((s) =>aiProviderSelectors.isInitAiProviderRuntimeState(s),);const currentChatModel = findEnabledChatModel(enabledChatModelList, model, provider);+ const staleModelState = useMemo(+ () =>+ isModelConfigReady+ ? resolveStaleModelState(+ { model, provider },+ {+ builtinAiModelList,+ enabledList: enabledChatModelList,+ modelRedirects,+ modelType: 'chat',+ },+ )+ : undefined,+ [builtinAiModelList, enabledChatModelList, isModelConfigReady, model, modelRedirects, provider],+ );+ const enableTargetProviderId =+ staleModelState?.status === 'notEnabled'+ ? resolveEnableTargetProviderId(+ { model, provider },+ {+ enabledAiProviders,+ enabledList: enabledChatModelList,+ metaProviderId: staleModelState.meta?.providerId,+ },+ )+ : undefined;+ /**+ * A locked Agent selection can only be repaired in place. Enabling an id-only fallback+ * provider would mutate global model settings while leaving the persisted selection stale.+ */+ const isModelDisabled = Boolean(+ enableTargetProviderId && (enableTargetProviderId === provider || canSelectModel),+ );const { canUseResource, isGroupContext } = useChatInputResourceAccess();- return resolveChatInputNotice({+ const notice = resolveChatInputNotice({currentChatModel,isAgentModelPending: isAgentConfigLoading || isMemberOverridePending,isGroupContext,isHeterogeneousAgent,+ isModelDisabled,isModelConfigReady,isResourceViewOnly: !canUseResource,});++ const handleEnableModel = useCallback(async () => {+ const providerId = enableTargetProviderId;+ if (!providerId) return;++ setActionLoading(true);+ try {+ if (!enabledChatModelList.some((item) => item.id === providerId)) {+ await toggleProviderEnabled(providerId, true);+ }+ await toggleProviderModelEnabled({+ enabled: true,+ id: model,+ providerId,+ type: 'chat',+ });+ if (providerId !== provider) {+ try {+ await selectModel({ model, provider: providerId });+ } catch (error) {+ console.error('Failed to select the enabled chat model provider:', error);+ toast.error(t('input.modelDisabled.selectionFailed'));+ }+ }+ } catch (error) {+ console.error('Failed to enable the selected chat model:', error);+ toast.error(t('input.modelDisabled.actionFailed'));+ } finally {+ setActionLoading(false);+ }+ }, [+ enableTargetProviderId,+ enabledChatModelList,+ model,+ provider,+ selectModel,+ t,+ toggleProviderEnabled,+ toggleProviderModelEnabled,+ ]);++ if (notice?.action !== 'enableModel') return notice;++ return {+ ...notice,+ actionDisabled: !canManageAiInfra,+ actionDisabledReason: canManageAiInfra ? undefined : aiInfraPermissionReason,+ actionLoading,+ onAction: canManageAiInfra ? handleEnableModel : undefined,+ };};