🤯 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: support fable campaign UI (#15616)
YuTengjing4b7ef28e46fe
diff --git a/locales/en-US/subscription.json b/locales/en-US/subscription.jsonindex cd21f087c1b..cb54f6e7238 100644--- a/locales/en-US/subscription.json+++ b/locales/en-US/subscription.json@@ -140,6 +140,10 @@"limitation.chat.topupSuccess.title": "Top-up Successful","limitation.expired.desc": "Your {{plan}} credits expired on {{expiredAt}}. Upgrade your plan now to get credits.","limitation.expired.title": "Credits Expired",+ "limitation.fableCampaign.desc": "Claude Fable 5 is a high-cost model. The campaign trial credits have been used up. Upgrade your plan to keep using Fable.",+ "limitation.fableCampaign.title": "Fable Trial Credits Used Up",+ "limitation.fableCampaign.upgrade": "Upgrade Plan",+ "limitation.fableCampaign.upgradeToPlan": "Upgrade to {{plan}}","limitation.hobby.action": "Configured, continue chatting","limitation.hobby.configAPI": "Configure API","limitation.hobby.desc": "Your free credits have been exhausted. Please configure a custom model API to continue.",diff --git a/locales/zh-CN/subscription.json b/locales/zh-CN/subscription.jsonindex 7035f129781..114eb7ac21d 100644--- a/locales/zh-CN/subscription.json+++ b/locales/zh-CN/subscription.json@@ -143,6 +143,10 @@"limitation.chat.topupSuccess.title": "充值成功","limitation.expired.desc": "您的 {{plan}} 计算积分已于 {{expiredAt}} 过期。请立即升级套餐以获取新的计算积分。","limitation.expired.title": "计算积分已过期",+ "limitation.fableCampaign.desc": "Claude Fable 5 成本较高,本次活动赠送额度已经用完。升级套餐后即可继续使用 Fable。",+ "limitation.fableCampaign.title": "Fable 赠送额度已用完",+ "limitation.fableCampaign.upgrade": "升级套餐",+ "limitation.fableCampaign.upgradeToPlan": "升级至 {{plan}}","limitation.hobby.action": "已配置,继续聊天","limitation.hobby.configAPI": "配置 API","limitation.hobby.desc": "您的免费计算积分已用尽,请配置自定义模型 API 以继续使用。",diff --git a/packages/fetch-sse/src/fetchSSE.ts b/packages/fetch-sse/src/fetchSSE.tsindex b144845e676..8d1ba3ddc8b 100644--- a/packages/fetch-sse/src/fetchSSE.ts+++ b/packages/fetch-sse/src/fetchSSE.ts@@ -19,12 +19,15 @@ import { getMessageError } from './parseError';type SSEFinishType = 'done' | 'error' | 'abort' | string;+const PLAN_UPGRADE_AFTER_FINISH_HEADER = 'x-lobe-plan-upgrade-after-finish';+export type OnFinishHandler = (text: string,context: {grounding?: GroundingSearch;images?: ChatImageChunk[];observationId?: string | null;+ planUpgradeAfterFinish?: boolean;reasoning?: ModelReasoning;speed?: ModelPerformance;toolCalls?: MessageToolCall[];@@ -540,6 +543,7 @@ export const fetchSSE = async (url: string, options: RequestInit & FetchSSEOptioconst traceId = response.headers.get(LOBE_CHAT_TRACE_ID);const observationId = response.headers.get(LOBE_CHAT_OBSERVATION_ID);+ const planUpgradeAfterFinish = response.headers.get(PLAN_UPGRADE_AFTER_FINISH_HEADER) === '1';textController.flushQueue();thinkingController.flushQueue();@@ -548,6 +552,7 @@ export const fetchSSE = async (url: string, options: RequestInit & FetchSSEOptiogrounding,images: images.length > 0 ? images : undefined,observationId,+ planUpgradeAfterFinish,reasoning: !!thinking ? { content: thinking, signature: thinkingSignature } : undefined,speed,toolCalls,diff --git a/packages/locales/src/default/subscription.ts b/packages/locales/src/default/subscription.tsindex 23d839bc71f..009902f6afd 100644--- a/packages/locales/src/default/subscription.ts+++ b/packages/locales/src/default/subscription.ts@@ -162,6 +162,11 @@ export default {'limitation.expired.desc':'Your {{plan}} credits expired on {{expiredAt}}. Upgrade your plan now to get credits.','limitation.expired.title': 'Credits Expired',+ 'limitation.fableCampaign.desc':+ 'Claude Fable 5 is a high-cost model. The campaign trial credits have been used up. Upgrade your plan to keep using Fable.',+ 'limitation.fableCampaign.title': 'Fable Trial Credits Used Up',+ 'limitation.fableCampaign.upgrade': 'Upgrade Plan',+ 'limitation.fableCampaign.upgradeToPlan': 'Upgrade to {{plan}}','limitation.insufficientBudget.approximateDesc':'This request may need more credits. Top up credits or upgrade your plan.','limitation.insufficientBudget.available': 'Available Credits',diff --git a/src/business/client/hooks/useBusinessAgentMode.ts b/src/business/client/hooks/useBusinessAgentMode.tsnew file mode 100644index 00000000000..13601f3733d--- /dev/null+++ b/src/business/client/hooks/useBusinessAgentMode.ts@@ -0,0 +1,15 @@+export interface BusinessModelModeConfig {+ chatConfig?: {+ enableAgentMode?: boolean;+ };+ model: string;+ provider: string;+}++export const useBusinessModelModeConfig = () => {+ return <T extends BusinessModelModeConfig>(config: T): T => config;+};++export const useBusinessCanEnableAgentMode = (_agentId: string): boolean => true;++export const useBusinessAgentModeSync = (_agentId: string): void => {};diff --git a/src/business/client/hooks/useBusinessModelPricing.ts b/src/business/client/hooks/useBusinessModelPricing.tsnew file mode 100644index 00000000000..7fbe49599e2--- /dev/null+++ b/src/business/client/hooks/useBusinessModelPricing.ts@@ -0,0 +1,13 @@+import type { Pricing } from 'model-bank';++export interface BusinessModelPricingParams {+ model?: string;+ pricing?: Pricing;+ provider?: string;+}++export const applyBusinessModelPricing = ({ pricing }: BusinessModelPricingParams) => pricing;++export const useBusinessModelPricing = () => applyBusinessModelPricing;++export const useBusinessModelPricingPrefetch = () => {};diff --git a/src/features/ChatInput/ActionBar/AgentMode/index.tsx b/src/features/ChatInput/ActionBar/AgentMode/index.tsxindex 519555997c8..e65ead5f3b4 100644--- a/src/features/ChatInput/ActionBar/AgentMode/index.tsx+++ b/src/features/ChatInput/ActionBar/AgentMode/index.tsx@@ -12,6 +12,7 @@ import {import { memo, useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';+import { useBusinessAgentModeSync } from '@/business/client/hooks/useBusinessAgentMode';import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';import { useToggleAgentMode } from '@/features/ChatInput/hooks/useToggleAgentMode';import { useAgentStore } from '@/store/agent';@@ -108,6 +109,7 @@ const AgentMode = memo(() => {const { t } = useTranslation('chat');const agentId = useAgentId();const toggleAgentMode = useToggleAgentMode();+ useBusinessAgentModeSync(agentId);const [open, setOpen] = useState(false);const enableAgentMode = useAgentStore(agentByIdSelectors.getAgentEnableModeById(agentId));diff --git a/src/features/ChatInput/ActionBar/Model/index.tsx b/src/features/ChatInput/ActionBar/Model/index.tsxindex f080019e0a1..b2640dc4c4a 100644--- a/src/features/ChatInput/ActionBar/Model/index.tsx+++ b/src/features/ChatInput/ActionBar/Model/index.tsx@@ -3,6 +3,7 @@ import { Center } from '@lobehub/ui';import { createStaticStyles } from 'antd-style';import { memo, useCallback } from 'react';+import { useBusinessModelModeConfig } from '@/business/client/hooks/useBusinessAgentMode';import ModelSwitchPanel from '@/features/ModelSwitchPanel';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';@@ -41,12 +42,13 @@ const ModelSwitch = memo(() => {agentByIdSelectors.getAgentModelProviderById(agentId)(s),s.updateAgentConfigById,]);+ const applyBusinessModelModeConfig = useBusinessModelModeConfig();const handleModelChange = useCallback(async (params: { model: string; provider: string }) => {- await updateAgentConfigById(agentId, params);+ await updateAgentConfigById(agentId, applyBusinessModelModeConfig(params));},- [agentId, updateAgentConfigById],+ [agentId, applyBusinessModelModeConfig, updateAgentConfigById],);return (diff --git a/src/features/ChatInput/ActionBar/ModelLabel/index.tsx b/src/features/ChatInput/ActionBar/ModelLabel/index.tsxindex 3153bf4ff41..10c7bd716dd 100644--- a/src/features/ChatInput/ActionBar/ModelLabel/index.tsx+++ b/src/features/ChatInput/ActionBar/ModelLabel/index.tsx@@ -3,6 +3,7 @@ import { createStaticStyles } from 'antd-style';import { ChevronDownIcon } from 'lucide-react';import { memo, useCallback } from 'react';+import { useBusinessModelModeConfig } from '@/business/client/hooks/useBusinessAgentMode';import ModelSwitchPanel from '@/features/ModelSwitchPanel';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';@@ -44,15 +45,16 @@ const ModelLabel = memo(() => {agentByIdSelectors.getAgentModelProviderById(agentId)(s),s.updateAgentConfigById,]);+ const applyBusinessModelModeConfig = useBusinessModelModeConfig();const enabledModel = useAiInfraStore(aiModelSelectors.getEnabledModelById(model, provider));const displayName = enabledModel?.displayName || model;const handleModelChange = useCallback(async (params: { model: string; provider: string }) => {- await updateAgentConfigById(agentId, params);+ await updateAgentConfigById(agentId, applyBusinessModelModeConfig(params));},- [agentId, updateAgentConfigById],+ [agentId, applyBusinessModelModeConfig, updateAgentConfigById],);return (diff --git a/src/features/ChatInput/ControlBar/ModeSelector.tsx b/src/features/ChatInput/ControlBar/ModeSelector.tsxindex 65f5ea7b6eb..e3cf2cfdb10 100644--- a/src/features/ChatInput/ControlBar/ModeSelector.tsx+++ b/src/features/ChatInput/ControlBar/ModeSelector.tsx@@ -12,6 +12,7 @@ import {import { memo, useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';+import { useBusinessAgentModeSync } from '@/business/client/hooks/useBusinessAgentMode';import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';import { useToggleAgentMode } from '@/features/ChatInput/hooks/useToggleAgentMode';import { useAgentStore } from '@/store/agent';@@ -108,6 +109,7 @@ const ModeSelector = memo(() => {const { t } = useTranslation('chat');const agentId = useAgentId();const toggleAgentMode = useToggleAgentMode();+ useBusinessAgentModeSync(agentId);const [open, setOpen] = useState(false);const enableAgentMode = useAgentStore(agentByIdSelectors.getAgentEnableModeById(agentId));diff --git a/src/features/ChatInput/hooks/useToggleAgentMode.ts b/src/features/ChatInput/hooks/useToggleAgentMode.tsindex ee3a6542cb6..6033ec6e7cb 100644--- a/src/features/ChatInput/hooks/useToggleAgentMode.ts+++ b/src/features/ChatInput/hooks/useToggleAgentMode.ts@@ -2,6 +2,9 @@import { useCallback } from 'react';+import { useBusinessCanEnableAgentMode } from '@/business/client/hooks/useBusinessAgentMode';++import { useAgentId } from './useAgentId';import { useUpdateAgentConfig } from './useUpdateAgentConfig';/**@@ -12,10 +15,13 @@ import { useUpdateAgentConfig } from './useUpdateAgentConfig';* untouched — chat mode is enforced at the runtime tools engine layer.*/export const useToggleAgentMode = () => {+ const agentId = useAgentId();const { updateAgentChatConfig } = useUpdateAgentConfig();+ const canEnableBusinessAgentMode = useBusinessCanEnableAgentMode(agentId);return useCallback(- (enable: boolean) => updateAgentChatConfig({ enableAgentMode: enable }),- [updateAgentChatConfig],+ (enable: boolean) =>+ updateAgentChatConfig({ enableAgentMode: enable && canEnableBusinessAgentMode }),+ [canEnableBusinessAgentMode, updateAgentChatConfig],);};diff --git a/src/features/ModelSwitchPanel/components/ModelDetailPanel.tsx b/src/features/ModelSwitchPanel/components/ModelDetailPanel.tsxindex 9a7af5e054e..a196c7d8346 100644--- a/src/features/ModelSwitchPanel/components/ModelDetailPanel.tsx+++ b/src/features/ModelSwitchPanel/components/ModelDetailPanel.tsx@@ -27,6 +27,7 @@ import type { FC } from 'react';import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';+import { useBusinessModelPricing } from '@/business/client/hooks/useBusinessModelPricing';import { useEnabledChatModels } from '@/hooks/useEnabledChatModels';import { useGlobalStore } from '@/store/global';import type { ModelDetailPanelExpandedKey } from '@/store/global/initialState';@@ -328,23 +329,28 @@ const ModelDetailPanel: FC<ModelDetailPanelProps> = memo(const expandedKeys = useGlobalStore(systemStatusSelectors.modelDetailPanelExpandedKeys);const updateExpandedKeys = useGlobalStore((s) => s.updateModelDetailPanelExpandedKeys);+ const applyBusinessModelPricing = useBusinessModelPricing();const pricing = model?.pricing;+ const displayPricing = useMemo(+ () => applyBusinessModelPricing({ model: modelId, pricing, provider }),+ [applyBusinessModelPricing, modelId, pricing, provider],+ );const isCreditPricing = provider === BRANDING_PROVIDER;- const hasPricing = !!pricing;- const formatPrice = pricing ? getPrice(pricing, isCreditPricing) : null;+ const hasPricing = !!displayPricing;+ const formatPrice = displayPricing ? getPrice(displayPricing, isCreditPricing) : null;const pricingGroups = useMemo(- () => (pricing ? groupPricingUnits(pricing.units) : []),- [pricing],+ () => (displayPricing ? groupPricingUnits(displayPricing.units) : []),+ [displayPricing],);const approximatePriceLabel = useMemo(() => {- if (!pricing || !pricingMode) return null;- const currency = pricing.currency as ModelPriceCurrency | undefined;- if (pricingMode === 'image' && typeof pricing.approximatePricePerImage === 'number') {+ if (!displayPricing || !pricingMode) return null;+ const currency = displayPricing.currency as ModelPriceCurrency | undefined;+ if (pricingMode === 'image' && typeof displayPricing.approximatePricePerImage === 'number') {const amount = isCreditPricing- ? formatBrandingCreditRate(pricing.approximatePricePerImage, 'image')- : formatPriceByCurrency(pricing.approximatePricePerImage, currency);+ ? formatBrandingCreditRate(displayPricing.approximatePricePerImage, 'image')+ : formatPriceByCurrency(displayPricing.approximatePricePerImage, currency);return t(isCreditPricing? 'ModelSwitchPanel.detail.pricing.credits.perImage'@@ -357,10 +363,10 @@ const ModelDetailPanel: FC<ModelDetailPanelProps> = memo(},);}- if (pricingMode === 'video' && typeof pricing.approximatePricePerVideo === 'number') {+ if (pricingMode === 'video' && typeof displayPricing.approximatePricePerVideo === 'number') {const amount = isCreditPricing- ? formatBrandingCreditRate(pricing.approximatePricePerVideo)- : formatPriceByCurrency(pricing.approximatePricePerVideo, currency);+ ? formatBrandingCreditRate(displayPricing.approximatePricePerVideo)+ : formatPriceByCurrency(displayPricing.approximatePricePerVideo, currency);return t(isCreditPricing? 'ModelSwitchPanel.detail.pricing.credits.perVideo'@@ -374,7 +380,7 @@ const ModelDetailPanel: FC<ModelDetailPanelProps> = memo();}return null;- }, [isCreditPricing, pricing, pricingMode, t]);+ }, [displayPricing, isCreditPricing, pricingMode, t]);const getCreditsUnitLabel = (unit: PricingUnit['unit']) =>t(`ModelSwitchPanel.detail.pricing.credits.${unit}` as any, {@@ -520,7 +526,7 @@ const ModelDetailPanel: FC<ModelDetailPanelProps> = memo(<span className={styles.actionText}>{approximatePriceLabel}</span>) : (<Flexbox horizontal align={'center'} className={styles.actionText} gap={8}>- {getCachedTextInputUnitRate(model.pricing!) && (+ {getCachedTextInputUnitRate(displayPricing) && (<Tooltiptitle={getPricingTooltip('cachedInput', formatPrice!.cachedInput.current)}>@@ -593,7 +599,7 @@ const ModelDetailPanel: FC<ModelDetailPanelProps> = memo(prefix={isCreditPricing ? '' : '$'}price={formatUnitRate(unit,- model.pricing?.currency as ModelPriceCurrency,+ displayPricing.currency as ModelPriceCurrency,isCreditPricing,)}suffix={diff --git a/src/features/ModelSwitchPanel/components/PanelContent.tsx b/src/features/ModelSwitchPanel/components/PanelContent.tsxindex c25dd1cc07f..6b6120e6d72 100644--- a/src/features/ModelSwitchPanel/components/PanelContent.tsx+++ b/src/features/ModelSwitchPanel/components/PanelContent.tsx@@ -3,6 +3,7 @@ import { type ComponentType, type FC } from 'react';import { useState } from 'react';import { Rnd } from 'react-rnd';+import { useBusinessModelPricingPrefetch } from '@/business/client/hooks/useBusinessModelPricing';import { useEnabledChatModels } from '@/hooks/useEnabledChatModels';import { useUserStore } from '@/store/user';import { userGeneralSettingsSelectors } from '@/store/user/slices/settings/selectors/general';@@ -41,6 +42,8 @@ export const PanelContent: FC<PanelContentProps> = ({const { groupMode, handleGroupModeChange } = usePanelState();const { panelHeight, panelWidth, handlePanelWidthChange } = usePanelSize(enabledList.length);+ useBusinessModelPricingPrefetch();+const content = (<><Toolbardiff --git a/src/routes/(main)/home/features/InputArea/StarterList.tsx b/src/routes/(main)/home/features/InputArea/StarterList.tsxindex ed660f3179e..e0ee78583b4 100644--- a/src/routes/(main)/home/features/InputArea/StarterList.tsx+++ b/src/routes/(main)/home/features/InputArea/StarterList.tsx@@ -5,6 +5,7 @@ import { createStaticStyles, cx } from 'antd-style';import { memo, useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';+import { useBusinessModelModeConfig } from '@/business/client/hooks/useBusinessAgentMode';import type { HomeNewModelItem } from '@/business/client/hooks/useHomeNewModels';import { useHomeNewModels } from '@/business/client/hooks/useHomeNewModels';import { useStableNavigate } from '@/hooks/useStableNavigate';@@ -48,6 +49,7 @@ const StarterList = memo(() => {const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);const [switchingKey, setSwitchingKey] = useState<string | null>(null);const { isLoading, items } = useHomeNewModels(DEFAULT_HOME_NEW_MODELS);+ const applyBusinessModelModeConfig = useBusinessModelModeConfig();const handleClick = useCallback(async (item: HomeNewModelItem) => {@@ -80,15 +82,24 @@ const StarterList = memo(() => {const currentModel = agentByIdSelectors.getAgentModelById(activeAgentId)(agentState);const currentProvider =agentByIdSelectors.getAgentModelProviderById(activeAgentId)(agentState);- if (currentModel === item.model && currentProvider === provider) {+ const nextConfig = applyBusinessModelModeConfig({+ model: item.model,+ provider,+ });+ const shouldUpdateAgentMode =+ nextConfig.chatConfig?.enableAgentMode === false &&+ agentByIdSelectors.getAgentEnableModeById(activeAgentId)(agentState);++ if (+ currentModel === item.model &&+ currentProvider === provider &&+ !shouldUpdateAgentMode+ ) {message.info(t('starter.modelInUse', { name: item.title }));return;}- await updateAgentConfigById(activeAgentId, {- model: item.model,- provider,- });+ await updateAgentConfigById(activeAgentId, nextConfig);message.success(t('starter.modelSwitched', { name: item.title }));} finally {setSwitchingKey(null);@@ -96,7 +107,15 @@ const StarterList = memo(() => {return;}},- [navigate, activeAgentId, updateAgentConfigById, switchingKey, message, t],+ [+ navigate,+ activeAgentId,+ applyBusinessModelModeConfig,+ updateAgentConfigById,+ switchingKey,+ message,+ t,+ ],);return (diff --git a/src/store/agent/selectors/agentByIdSelectors.test.ts b/src/store/agent/selectors/agentByIdSelectors.test.tsindex 612aae8066e..5f405519f59 100644--- a/src/store/agent/selectors/agentByIdSelectors.test.ts+++ b/src/store/agent/selectors/agentByIdSelectors.test.ts@@ -64,6 +64,38 @@ describe('agentByIdSelectors', () => {});});+ describe('agent mode', () => {+ it('should default to agent mode when enableAgentMode is not explicitly false', () => {+ const state = createState({+ agentMap: {+ 'agent-1': {+ chatConfig: {},+ model: 'gpt-4o',+ provider: 'openai',+ },+ },+ });++ expect(agentByIdSelectors.getAgentModeById('agent-1')(state)).toBe('auto');+ expect(agentByIdSelectors.getAgentEnableModeById('agent-1')(state)).toBe(true);+ });++ it('should keep fable in agent mode when agent mode is enabled', () => {+ const state = createState({+ agentMap: {+ 'agent-1': {+ chatConfig: { enableAgentMode: true },+ model: 'claude-fable-5',+ provider: 'lobehub',+ },+ },+ });++ expect(agentByIdSelectors.getAgentModeById('agent-1')(state)).toBe('auto');+ expect(agentByIdSelectors.getAgentEnableModeById('agent-1')(state)).toBe(true);+ });+ });+describe('getAgentWorkingDirectoryById', () => {afterEach(() => {vi.restoreAllMocks();diff --git a/src/store/agent/selectors/agentByIdSelectors.ts b/src/store/agent/selectors/agentByIdSelectors.tsindex f382415e752..7e74221680d 100644--- a/src/store/agent/selectors/agentByIdSelectors.ts+++ b/src/store/agent/selectors/agentByIdSelectors.ts@@ -61,7 +61,8 @@ const isAgentConfigLoadingById = (agentId: string) => (s: AgentStoreState) =>const getAgentModeById =(agentId: string) =>(s: AgentStoreState): AgentMode | undefined => {- const chatConfig = agentSelectors.getAgentConfigById(agentId)(s)?.chatConfig;+ const config = agentSelectors.getAgentConfigById(agentId)(s);+ const chatConfig = config?.chatConfig;return chatConfig?.enableAgentMode === false ? undefined : 'auto';};@@ -72,7 +73,8 @@ const getAgentModeById =const getAgentEnableModeById =(agentId: string) =>(s: AgentStoreState): boolean => {- const chatConfig = agentSelectors.getAgentConfigById(agentId)(s)?.chatConfig;+ const config = agentSelectors.getAgentConfigById(agentId)(s);+ const chatConfig = config?.chatConfig;return chatConfig?.enableAgentMode !== false;};diff --git a/src/store/agent/selectors/chatConfigByIdSelectors.test.ts b/src/store/agent/selectors/chatConfigByIdSelectors.test.tsindex 647802ecced..1bbb2b96184 100644--- a/src/store/agent/selectors/chatConfigByIdSelectors.test.ts+++ b/src/store/agent/selectors/chatConfigByIdSelectors.test.ts@@ -58,6 +58,23 @@ describe('chatConfigByIdSelectors', () => {// Individual selectors (like getHistoryCountById) apply defaults via ?? operatorexpect(chatConfigByIdSelectors.getChatConfigById('non-existent')(state)).toEqual({});});++ it('should return stored fable chat config without model-specific overrides', () => {+ const state = createState({+ agentMap: {+ 'agent-1': {+ chatConfig: { enableAgentMode: true, historyCount: 10 },+ model: 'claude-fable-5',+ provider: 'lobehub',+ },+ },+ });++ expect(chatConfigByIdSelectors.getChatConfigById('agent-1')(state)).toMatchObject({+ enableAgentMode: true,+ historyCount: 10,+ });+ });});describe('getEnableHistoryCountById', () => {diff --git a/src/store/agent/selectors/chatConfigByIdSelectors.ts b/src/store/agent/selectors/chatConfigByIdSelectors.tsindex dfe2520ce93..7c735f931dc 100644--- a/src/store/agent/selectors/chatConfigByIdSelectors.ts+++ b/src/store/agent/selectors/chatConfigByIdSelectors.ts@@ -15,14 +15,18 @@ import { agentSelectors } from './selectors';* Used in ChatInput components where agentId is passed as prop.*/-const getChatConfigById =+const getStoredChatConfigById =(agentId: string) =>(s: AgentStoreState): LobeAgentChatConfig =>agentSelectors.getAgentConfigById(agentId)(s)?.chatConfig || {};-// Return raw chatConfig value without business logic overrides+const getChatConfigById =+ (agentId: string) =>+ (s: AgentStoreState): LobeAgentChatConfig =>+ getStoredChatConfigById(agentId)(s);+const getEnableHistoryCountById = (agentId: string) => (s: AgentStoreState) =>- getChatConfigById(agentId)(s).enableHistoryCount;+ getStoredChatConfigById(agentId)(s).enableHistoryCount;const getHistoryCountById =(agentId: string) =>diff --git a/src/store/agent/selectors/chatConfigSelectors.ts b/src/store/agent/selectors/chatConfigSelectors.tsindex 6998b7073a9..82d35aeaa78 100644--- a/src/store/agent/selectors/chatConfigSelectors.ts+++ b/src/store/agent/selectors/chatConfigSelectors.ts@@ -21,9 +21,9 @@ const useModelBuiltinSearch = (s: AgentStoreState) =>const searchFCModel = (s: AgentStoreState) =>chatConfigByIdSelectors.getSearchFCModelById(s.activeAgentId || '')(s);-// Use raw chatConfig value, not the selector with business logic that may force false+// Read the stored history flag directly; model-level mode overrides should not affect history.const enableHistoryCount = (s: AgentStoreState) =>- chatConfigByIdSelectors.getChatConfigById(s.activeAgentId || '')(s).enableHistoryCount;+ chatConfigByIdSelectors.getEnableHistoryCountById(s.activeAgentId || '')(s);const historyCount = (s: AgentStoreState): number =>chatConfigByIdSelectors.getHistoryCountById(s.activeAgentId || '')(s);diff --git a/src/store/agent/selectors/selectors.test.ts b/src/store/agent/selectors/selectors.test.tsindex 40239b26adf..b182f81dbb8 100644--- a/src/store/agent/selectors/selectors.test.ts+++ b/src/store/agent/selectors/selectors.test.ts@@ -99,6 +99,34 @@ describe('agentSelectors', () => {});});+ describe('currentAgentMode', () => {+ it('should return auto by default', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': { chatConfig: {} } },+ });++ expect(agentSelectors.currentAgentMode(state)).toBe('auto');+ expect(agentSelectors.isAgentModeEnabled(state)).toBe(true);+ });++ it('should keep fable in agent mode when agent mode is enabled', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ chatConfig: { enableAgentMode: true },+ model: 'claude-fable-5',+ provider: 'lobehub',+ },+ },+ });++ expect(agentSelectors.currentAgentMode(state)).toBe('auto');+ expect(agentSelectors.isAgentModeEnabled(state)).toBe(true);+ });+ });+describe('currentAgentMeta', () => {it('should return complete meta data', () => {const state = createState({diff --git a/src/store/agent/selectors/selectors.ts b/src/store/agent/selectors/selectors.tsindex 6be63cfcb31..212b3126564 100644--- a/src/store/agent/selectors/selectors.ts+++ b/src/store/agent/selectors/selectors.ts@@ -244,7 +244,8 @@ const openingMessage = (s: AgentStoreState) => currentAgentConfig(s)?.openingMes* collapses the agent to chat mode.*/const currentAgentMode = (s: AgentStoreState): AgentMode | undefined => {- const chatConfig = currentAgentConfig(s)?.chatConfig;+ const config = currentAgentConfig(s);+ const chatConfig = config?.chatConfig;return chatConfig?.enableAgentMode === false ? undefined : 'auto';};diff --git a/src/store/chat/agents/__tests__/createAgentExecutors/call-llm.test.ts b/src/store/chat/agents/__tests__/createAgentExecutors/call-llm.test.tsindex d4465b6a79f..5b8f72c8f03 100644--- a/src/store/chat/agents/__tests__/createAgentExecutors/call-llm.test.ts+++ b/src/store/chat/agents/__tests__/createAgentExecutors/call-llm.test.ts@@ -1,7 +1,7 @@import { type GeneralAgentCallLLMResultPayload } from '@lobechat/agent-runtime';import { LOADING_FLAT } from '@lobechat/const';import type { MessageToolCall } from '@lobechat/types';-import { RequestTrigger } from '@lobechat/types';+import { ChatErrorType, RequestTrigger } from '@lobechat/types';import { describe, expect, it, vi } from 'vitest';import { chatService } from '@/services/chat';@@ -62,10 +62,11 @@ vi.mock('@/store/agent/store', () => ({const mockStreamResponse = (response: {content?: string;finishType?: string;+ planUpgradeAfterFinish?: boolean;tool_calls?: MessageToolCall[];usage?: any;}) => {- const { content = '', finishType = 'stop', tool_calls, usage } = response;+ const { content = '', finishType = 'stop', planUpgradeAfterFinish, tool_calls, usage } = response;vi.mocked(chatService.createAssistantMessageStream).mockImplementation(async (params: any) => {// Simulate text streaming@@ -85,6 +86,7 @@ const mockStreamResponse = (response: {// Simulate finishif (params.onFinish) {await params.onFinish(content, {+ planUpgradeAfterFinish,toolCalls: tool_calls,type: finishType,usage,@@ -170,6 +172,59 @@ describe('call_llm executor', () => {);});+ it('should append a plan upgrade assistant message after successful campaign finish', async () => {+ const mockStore = createMockStore();+ const context = createTestContext({ agentId: 'test-session', topicId: 'test-topic' });+ const instruction = createCallLLMInstruction({+ messages: [createUserMessage({ content: 'Hello' })],+ model: 'claude-fable-5',+ provider: 'lobehub',+ });+ const state = createInitialState();++ mockStreamResponse({ content: 'AI response', planUpgradeAfterFinish: true });+ mockStore.dbMessagesMap[context.messageKey] = [];++ await executeWithMockContext({+ executor: 'call_llm',+ instruction,+ state,+ mockStore,+ context,+ });++ expect(mockStore.optimisticCreateMessage).toHaveBeenCalledTimes(2);+ const firstMessage = await vi.mocked(mockStore.optimisticCreateMessage).mock.results[0].value;+ const planUpgradeMessage = vi+ .mocked(mockStore.optimisticCreateMessage)+ .mock.calls.at(-1)?.[0];+ expect(mockStore.optimisticCreateMessage).toHaveBeenLastCalledWith(+ expect.objectContaining({+ content: '',+ error: expect.objectContaining({+ body: {+ budget: {+ modelId: 'claude-fable-5',+ pricingBasis: 'unknown',+ providerId: 'lobehub',+ scenario: 'chat',+ },+ },+ type: ChatErrorType.FreePlanLimit,+ }),+ model: 'claude-fable-5',+ parentId: firstMessage.id,+ provider: 'lobehub',+ role: 'assistant',+ topicId: 'test-topic',+ }),+ expect.objectContaining({+ operationId: expect.any(String),+ }),+ );+ expect(planUpgradeMessage?.error).not.toHaveProperty('message');+ });+it('should forward request metadata to chatService', async () => {const mockStore = createMockStore();const context = createTestContext();diff --git a/src/store/chat/agents/createAgentExecutors.ts b/src/store/chat/agents/createAgentExecutors.tsindex 36448e5c163..7f147c8fcb5 100644--- a/src/store/chat/agents/createAgentExecutors.ts+++ b/src/store/chat/agents/createAgentExecutors.ts@@ -20,6 +20,7 @@ import { UsageCounter } from '@lobechat/agent-runtime';import { countContextTokens, type ToolsEngine } from '@lobechat/context-engine';import { chainCompressContext } from '@lobechat/prompts';import {+ ChatErrorType,type ChatMessageError,type ChatToolPayload,type CreateMessageParams,@@ -297,7 +298,7 @@ export const createAgentExecutors = (context: {if (!operation) {throw new Error(`Operation not found: ${context.operationId}`);}- const { subAgentId, groupId, topicId } = operation.context;+ const { subAgentId, groupId, threadId, topicId } = operation.context;const abortController = operation.abortController;// In group orchestration, subAgentId is the actual responding agent@@ -494,9 +495,21 @@ export const createAgentExecutors = (context: {});},onFinish: async (- content,- { traceId, observationId, toolCalls, reasoning, grounding, usage, speed, type },+ _content,+ {+ traceId,+ observationId,+ planUpgradeAfterFinish,+ toolCalls,+ reasoning,+ grounding,+ usage,+ speed,+ type,+ },) => {+ void _content;+if (traceId) {messageService.updateMessage(assistantMessageId,@@ -538,6 +551,34 @@ export const createAgentExecutors = (context: {},{ operationId: context.operationId },);++ if (planUpgradeAfterFinish && type !== 'abort' && type !== 'error') {+ await context.get().optimisticCreateMessage(+ {+ agentId: agentId || undefined,+ content: '',+ error: {+ body: {+ budget: {+ modelId: llmPayload.model,+ pricingBasis: 'unknown',+ providerId: llmPayload.provider,+ scenario: 'chat',+ },+ },+ type: ChatErrorType.FreePlanLimit,+ },+ groupId,+ model: llmPayload.model,+ parentId: assistantMessageId,+ provider: llmPayload.provider,+ role: 'assistant',+ threadId,+ topicId: topicId ?? undefined,+ },+ { operationId: context.operationId },+ );+ }},onMessageHandle: async (chunk) => {handler.handleChunk(chunk as StreamChunk);