π€― 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
β»οΈ refactor(agent): scope agent conversation subtree to explicit agentId (#15866)
Arvin Xucdb0280cd615
diff --git a/src/business/client/hooks/useHeteroAgentCloudConfig.ts b/src/business/client/hooks/useHeteroAgentCloudConfig.tsindex 27f754144e5..73d1bf0643f 100644--- a/src/business/client/hooks/useHeteroAgentCloudConfig.ts+++ b/src/business/client/hooks/useHeteroAgentCloudConfig.ts@@ -1,11 +1,10 @@import { isDesktop } from '@lobechat/const';-import { useParams } from 'react-router-dom';import urlJoin from 'url-join';import { useQueryRoute } from '@/hooks/useQueryRoute';import { lambdaQuery } from '@/libs/trpc/client';import { useAgentStore } from '@/store/agent';-import { agentSelectors } from '@/store/agent/selectors';+import { agentByIdSelectors } from '@/store/agent/selectors';// Fixed cred key β must stay in sync with CloudHeterogeneousConfigconst CLAUDE_TOKEN_CRED_KEY = 'CLAUDE_CODE_OAUTH_TOKEN';@@ -15,12 +14,11 @@ interface HeteroAgentCloudConfig {isConfigured: boolean;}-export const useHeteroAgentCloudConfig = (): HeteroAgentCloudConfig => {- const params = useParams<{ aid: string }>();+export const useHeteroAgentCloudConfig = (agentId: string): HeteroAgentCloudConfig => {const router = useQueryRoute();const heterogeneousProvider = useAgentStore(- (s) => agentSelectors.currentAgentConfig(s)?.agencyConfig?.heterogeneousProvider,+ (s) => agentByIdSelectors.getAgencyConfigById(agentId)(s)?.heterogeneousProvider,);// Only claude-code agents require a cloud credential β codex and other providers do not use this key@@ -50,7 +48,6 @@ export const useHeteroAgentCloudConfig = (): HeteroAgentCloudConfig => {isCredsLoading;const goToConfig = () => {- const agentId = params.aid;if (agentId) {router.push(urlJoin('/agent', agentId, 'profile'));}diff --git a/src/features/AgentTopicManager/Header.tsx b/src/features/AgentTopicManager/Header.tsxindex 417978a6749..18ea7a873e6 100644--- a/src/features/AgentTopicManager/Header.tsx+++ b/src/features/AgentTopicManager/Header.tsx@@ -20,8 +20,9 @@ interface HeaderProps {const Header = memo<HeaderProps>(({ agentId }) => {const { t } = useTranslation(['topic', 'chat', 'common']);- const agentTitle = useAgentStore(agentSelectors.currentAgentTitle);- const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);+ const agentTitle = useAgentStore((s) => agentSelectors.getAgentMetaById(agentId)(s).title);+ const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);+ const isInbox = !!inboxAgentId && agentId === inboxAgentId;const displayTitle = isInbox? agentTitle || t('inbox.title', { ns: 'chat' }): agentTitle || t('defaultSession', { ns: 'common' });diff --git a/src/features/Conversation/Messages/components/Extras/TTS/index.tsx b/src/features/Conversation/Messages/components/Extras/TTS/index.tsxindex a9537410533..6810f87173a 100644--- a/src/features/Conversation/Messages/components/Extras/TTS/index.tsx+++ b/src/features/Conversation/Messages/components/Extras/TTS/index.tsx@@ -1,8 +1,9 @@import { memo, useMemo } from 'react';import { Md5 } from 'ts-md5';+import { contextSelectors, useConversationStore } from '@/features/Conversation/store';import { useAgentStore } from '@/store/agent';-import { agentSelectors } from '@/store/agent/selectors';+import { agentByIdSelectors } from '@/store/agent/selectors';import { useGlobalStore } from '@/store/global';import { globalGeneralSelectors } from '@/store/global/selectors';@@ -14,7 +15,8 @@ const TTS = memo<TTSProps>((props) => {const { file, voice, content, contentMd5 } = props;const lang = useGlobalStore(globalGeneralSelectors.currentLanguage);- const currentVoice = useAgentStore(agentSelectors.currentAgentTTSVoice(lang));+ const agentId = useConversationStore(contextSelectors.agentId);+ const currentVoice = useAgentStore(agentByIdSelectors.getAgentTTSVoiceById(agentId, lang));const md5 = useMemo(() => Md5.hashStr(content).toString(), [content]);diff --git a/src/features/Conversation/components/History/index.tsx b/src/features/Conversation/components/History/index.tsxindex b773719e1d1..6ea1b8dcd9c 100644--- a/src/features/Conversation/components/History/index.tsx+++ b/src/features/Conversation/components/History/index.tsx@@ -5,10 +5,10 @@ import { ScrollText } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { agentChatConfigSelectors } from '@/store/agent/selectors';+import { chatConfigByIdSelectors } from '@/store/agent/selectors';import { useAgentStore } from '@/store/agent/store';-import { dataSelectors, useConversationStore } from '../../store';+import { contextSelectors, dataSelectors, useConversationStore } from '../../store';import HistoryDivider from './HistoryDivider';const styles = createStaticStyles(({ css, cssVar }) => ({@@ -33,8 +33,9 @@ const History = memo(() => {return [history?.content, history?.model];});+ const agentId = useConversationStore(contextSelectors.agentId);const enableCompressHistory = useAgentStore(- (s) => agentChatConfigSelectors.currentChatConfig(s).enableCompressHistory,+ (s) => chatConfigByIdSelectors.getChatConfigById(agentId)(s).enableCompressHistory,);return (diff --git a/src/features/Conversation/components/ShareMessageModal/ShareImage/index.tsx b/src/features/Conversation/components/ShareMessageModal/ShareImage/index.tsxindex cddf0a5b4ff..cd209ec013e 100644--- a/src/features/Conversation/components/ShareMessageModal/ShareImage/index.tsx+++ b/src/features/Conversation/components/ShareMessageModal/ShareImage/index.tsx@@ -13,7 +13,7 @@ import { ImageType, imageTypeOptions, useScreenshot } from '@/hooks/useScreenshoimport { useAgentStore } from '@/store/agent';import { agentSelectors } from '@/store/agent/selectors';-import { useConversationStore } from '../../../store';+import { contextSelectors, useConversationStore } from '../../../store';import { styles } from '../style';import Preview from './Preview';import { type FieldType, WidthMode } from './type';@@ -27,7 +27,10 @@ const DEFAULT_FIELD_VALUE: FieldType = {const ShareImage = memo<{ message: UIChatMessage; mobile?: boolean; uniqueId?: string }>(({ message, uniqueId }) => {- const currentAgentTitle = useAgentStore(agentSelectors.currentAgentTitle);+ const agentId = useConversationStore(contextSelectors.agentId);+ const currentAgentTitle = useAgentStore(+ (s) => agentSelectors.getAgentMetaById(agentId)(s).title,+ );const context = useConversationStore((s) => s.context);const [fieldValue, setFieldValue] = useState<FieldType>(DEFAULT_FIELD_VALUE);const { t } = useTranslation(['chat', 'common']);diff --git a/src/features/ShareModal/ShareDataProvider.tsx b/src/features/ShareModal/ShareDataProvider.tsxindex e8df15f73bd..b944474b452 100644--- a/src/features/ShareModal/ShareDataProvider.tsx+++ b/src/features/ShareModal/ShareDataProvider.tsx@@ -6,7 +6,7 @@ import { createContext, memo, type PropsWithChildren, use, useMemo } from 'reactimport { useTranslation } from 'react-i18next';import { useAgentStore } from '@/store/agent';-import { agentSelectors } from '@/store/agent/selectors';+import { agentByIdSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';import {dbMessageSelectors,@@ -47,7 +47,9 @@ const ShareDataProvider = memo<PropsWithChildren<ShareDataProviderProps>>(s.activeTopicId,s.useFetchMessages,]);- const systemRole = useAgentStore(agentSelectors.currentAgentSystemRole);+ const systemRole = useAgentStore(+ agentByIdSelectors.getAgentSystemRoleById(context?.agentId ?? activeAgentId ?? ''),+ );const resolvedContext = useMemo<ConversationContext>(() => {const hasTopicId = context && 'topicId' in context;diff --git a/src/hooks/useRemoteAgentDeviceGuard.ts b/src/hooks/useRemoteAgentDeviceGuard.tsindex 9e214fc5f0f..dfb92f11371 100644--- a/src/hooks/useRemoteAgentDeviceGuard.ts+++ b/src/hooks/useRemoteAgentDeviceGuard.ts@@ -12,6 +12,8 @@ export type RemoteAgentDeviceStatus =| 'platform-unavailable';interface UseRemoteAgentDeviceGuardOptions {+ /** The conversation's agent β validate this agent's bound device, not the global active one. */+ agentId: string;enabled?: boolean;}@@ -26,9 +28,9 @@ interface UseRemoteAgentDeviceGuardResult {* HeterogeneousChatInput before device-dispatched hetero runs.*/export const useRemoteAgentDeviceGuard = ({+ agentId,enabled = true,-}: UseRemoteAgentDeviceGuardOptions = {}): UseRemoteAgentDeviceGuardResult => {- const agentId = useAgentStore((s) => s.activeAgentId);+}: UseRemoteAgentDeviceGuardOptions): UseRemoteAgentDeviceGuardResult => {const agencyConfig = useAgentStore((s) =>agentId ? s.agentMap[agentId]?.agencyConfig : undefined,);diff --git a/src/routes/(main)/agent/features/Conversation/AgentWelcome/ToolAuthAlert.tsx b/src/routes/(main)/agent/features/Conversation/AgentWelcome/ToolAuthAlert.tsxindex d3628cd6b0c..1de1882b6d8 100644--- a/src/routes/(main)/agent/features/Conversation/AgentWelcome/ToolAuthAlert.tsx+++ b/src/routes/(main)/agent/features/Conversation/AgentWelcome/ToolAuthAlert.tsx@@ -10,9 +10,10 @@ import { PlusIcon } from 'lucide-react';import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import { contextSelectors, useConversationStore } from '@/features/Conversation/store';import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';import { useAgentStore } from '@/store/agent';-import { agentSelectors } from '@/store/agent/selectors';+import { agentByIdSelectors } from '@/store/agent/selectors';import { useToolStore } from '@/store/tool';import { type ComposioServer } from '@/store/tool/slices/composioStore';import { ComposioServerStatus, composioStoreSelectors } from '@/store/tool/slices/composioStore';@@ -279,7 +280,8 @@ MarketToolAuthItem.displayName = 'MarketToolAuthItem';const ToolAuthAlert = memo(() => {const { t } = useTranslation('chat');- const plugins = useAgentStore(agentSelectors.currentAgentPlugins, isEqual);+ const agentId = useConversationStore(contextSelectors.agentId);+ const plugins = useAgentStore(agentByIdSelectors.getAgentPluginsById(agentId), isEqual);const composioServers = useToolStore(composioStoreSelectors.getServers, isEqual);const { isAuthenticated: isMarketAuthenticated } = useMarketAuth();diff --git a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsxindex a0af016d514..d875aad6fa5 100644--- a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx+++ b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx@@ -15,7 +15,7 @@ import ZenModeToast from '@/features/ZenModeToast';import { useGatewayReconnect } from '@/hooks/useGatewayReconnect';import { useOperationState } from '@/hooks/useOperationState';import { useAgentStore } from '@/store/agent';-import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';+import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';import { threadSelectors, topicSelectors } from '@/store/chat/selectors';import { messageMapKey } from '@/store/chat/utils/messageMapKey';@@ -59,7 +59,9 @@ const Conversation = memo(() => {// Heterogeneous agents (Claude Code, etc.) use a simplified input β their// toolchain/memory/model are managed by the external runtime, so LobeHub's// model/tools/memory/KB/MCP/runtime-mode pickers don't apply.- const isHeterogeneousAgent = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);+ const isHeterogeneousAgent = useAgentStore(+ agentByIdSelectors.isAgentHeterogeneousById(context.agentId),+ );// Subagent threads (spawned by an external agent's subagent tool call) are// read-only β the parent agent drives their execution, so hide the input.@@ -73,7 +75,7 @@ const Conversation = memo(() => {);useGatewayReconnect(context.topicId, runningOperation);- const agentChatConfig = useAgentStore(agentChatConfigSelectors.currentChatConfig);+ const agentChatConfig = useAgentStore(chatConfigByIdSelectors.getChatConfigById(context.agentId));const chatFollowUpHooks = useChatFollowUp({agentChatConfig,conversationKey: chatKey,diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsxindex ee3f90cd1e4..734876fe363 100644--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx@@ -14,6 +14,7 @@ import { useHeteroAgentCloudConfig } from '@/business/client/hooks/useHeteroAgenimport { isDesktop } from '@/const/version';import { type ActionKeys } from '@/features/ChatInput';import { ChatInput } from '@/features/Conversation';+import { contextSelectors, useConversationStore } from '@/features/Conversation/store';import WideScreenContainer from '@/features/WideScreenContainer';import { resolveExecutionTarget } from '@/helpers/executionTarget';import { useRemoteAgentDeviceGuard } from '@/hooks/useRemoteAgentDeviceGuard';@@ -41,11 +42,18 @@ const rightActions: ActionKeys[] = [];*/const HeterogeneousChatInput = memo(() => {const { t } = useTranslation('chat');- const { isConfigured, goToConfig } = useHeteroAgentCloudConfig();+ // Scope every hetero check to the conversation's agent. Passing `agentId`+ // into the cloud-credential and device guards keeps them validating the same+ // agent that `agencyConfig`/`isDeviceExecution` are computed from, instead of+ // the global (hijack-prone) active agent.+ const agentId = useConversationStore(contextSelectors.agentId);+ const { isConfigured, goToConfig } = useHeteroAgentCloudConfig(agentId);const params = useParams<{ aid: string }>();const navigate = useNavigate();- const agencyConfig = useAgentStore((s) => agentSelectors.currentAgentConfig(s)?.agencyConfig);+ const agencyConfig = useAgentStore(+ (s) => agentSelectors.getAgentConfigById(agentId)(s)?.agencyConfig,+ );const providerType = agencyConfig?.heterogeneousProvider?.type;const executionTarget = resolveExecutionTarget(agencyConfig, {isDesktop,@@ -61,7 +69,7 @@ const HeterogeneousChatInput = memo(() => {const isDeviceExecution =isRemoteAgent || (executionTarget === 'device' && !!agencyConfig?.boundDeviceId);- const { status, refresh } = useRemoteAgentDeviceGuard({ enabled: isDeviceExecution });+ const { status, refresh } = useRemoteAgentDeviceGuard({ agentId, enabled: isDeviceExecution });const goToAgentProfile = () => {if (params.aid) navigate(urlJoin('/agent', params.aid, 'profile'));diff --git a/src/routes/(main)/agent/features/Conversation/MainChatInput/AgentConfigError.tsx b/src/routes/(main)/agent/features/Conversation/MainChatInput/AgentConfigError.tsxindex de74ce08d0e..9dee97e4044 100644--- a/src/routes/(main)/agent/features/Conversation/MainChatInput/AgentConfigError.tsx+++ b/src/routes/(main)/agent/features/Conversation/MainChatInput/AgentConfigError.tsx@@ -4,8 +4,9 @@ import { Alert, Button } from '@lobehub/ui';import { memo } from 'react';import { useTranslation } from 'react-i18next';+import { contextSelectors, useConversationStore } from '@/features/Conversation/store';import { useAgentStore } from '@/store/agent';-import { agentSelectors } from '@/store/agent/selectors';+import { agentByIdSelectors } from '@/store/agent/selectors';/*** Surfaces an agent-config fetch failure above the chat input with a retry@@ -14,8 +15,9 @@ import { agentSelectors } from '@/store/agent/selectors';*/const AgentConfigError = memo(() => {const { t } = useTranslation('chat');- const errorMessage = useAgentStore(agentSelectors.currentAgentConfigError);- const isConfigMissing = useAgentStore(agentSelectors.isAgentConfigLoading);+ const agentId = useConversationStore(contextSelectors.agentId);+ const errorMessage = useAgentStore(agentByIdSelectors.getAgentConfigErrorById(agentId));+ const isConfigMissing = useAgentStore(agentByIdSelectors.isAgentConfigLoadingById(agentId));const retryAgentConfigFetch = useAgentStore((s) => s.retryAgentConfigFetch);if (!errorMessage || !isConfigMissing) return null;@@ -28,7 +30,7 @@ const AgentConfigError = memo(() => {style={{ marginBlockEnd: 8 }}type={'error'}action={- <Button size={'small'} onClick={() => retryAgentConfigFetch()}>+ <Button size={'small'} onClick={() => retryAgentConfigFetch(agentId)}>{t('agentConfigError.retry')}</Button>}diff --git a/src/routes/(main)/agent/features/Conversation/MainChatInput/index.tsx b/src/routes/(main)/agent/features/Conversation/MainChatInput/index.tsxindex ccc65dafa09..d8caa060e57 100644--- a/src/routes/(main)/agent/features/Conversation/MainChatInput/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/MainChatInput/index.tsx@@ -4,9 +4,10 @@ import { memo, useMemo } from 'react';import { type ActionKeys } from '@/features/ChatInput';import { ChatInput } from '@/features/Conversation';+import { contextSelectors, useConversationStore } from '@/features/Conversation/store';import { useModelSupportImageOutput } from '@/hooks/useModelSupportImageOutput';import { useAgentStore } from '@/store/agent';-import { agentSelectors } from '@/store/agent/selectors';+import { agentByIdSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';import { useUserStore } from '@/store/user';import { userGeneralSettingsSelectors } from '@/store/user/selectors';@@ -29,9 +30,10 @@ const MainChatInput = memo(() => {const isDevMode = useUserStore((s) => userGeneralSettingsSelectors.config(s).isDevMode);const sendMenuItems = useSendMenuItems();- const model = useAgentStore(agentSelectors.currentAgentModel);- const provider = useAgentStore(agentSelectors.currentAgentModelProvider);- const isAgentConfigLoading = useAgentStore(agentSelectors.isAgentConfigLoading);+ const agentId = useConversationStore(contextSelectors.agentId);+ const model = useAgentStore(agentByIdSelectors.getAgentModelById(agentId));+ const provider = useAgentStore(agentByIdSelectors.getAgentModelProviderById(agentId));+ const isAgentConfigLoading = useAgentStore(agentByIdSelectors.isAgentConfigLoadingById(agentId));const supportsImageOutput = useModelSupportImageOutput(model, provider);const rightActions = supportsImageOutput? promptTransformRightActionsdiff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/AgentSummary.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/AgentSummary.tsxindex 581c02132e2..82fd36f6dcd 100644--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/AgentSummary.tsx+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/AgentSummary.tsx@@ -7,6 +7,7 @@ import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwarimport { getPlatformIcon } from '@/routes/(main)/agent/channel/const';import { useAgentStore } from '@/store/agent';import { agentSelectors } from '@/store/agent/selectors';+import { useChatStore } from '@/store/chat';const styles = createStaticStyles(({ css }) => ({header: css`@@ -33,8 +34,11 @@ const styles = createStaticStyles(({ css }) => ({const AgentSummary = memo(() => {const { t } = useTranslation(['chat', 'discover']);const navigate = useWorkspaceAwareNavigate();- const activeAgentId = useAgentStore((s) => s.activeAgentId);- const meta = useAgentStore(agentSelectors.currentAgentMeta);+ // WorkingSidebar renders outside the ConversationProvider, so take the routed+ // agent from the chat store (set by AgentIdSync, not the hijack-prone agent+ // store) and read its meta by id.+ const activeAgentId = useChatStore((s) => s.activeAgentId) || '';+ const meta = useAgentStore(agentSelectors.getAgentMetaById(activeAgentId));const { data: providers = [] } = useAgentStore((s) => s.useFetchBotProviders(activeAgentId));const { data: platforms = [] } = useAgentStore((s) => s.useFetchPlatformDefinitions());const title = meta.title || t('untitledAgent');diff --git a/src/routes/(main)/agent/features/Conversation/index.tsx b/src/routes/(main)/agent/features/Conversation/index.tsxindex 6a196c7e7fb..af401f6174c 100644--- a/src/routes/(main)/agent/features/Conversation/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/index.tsx@@ -6,7 +6,7 @@ import DragUploadZone, { type DroppedFolder, useUploadFiles } from '@/componentsimport Loading from '@/components/Loading/BrandTextLoading';import { insertLocalFolderMentions } from '@/features/ChatInput/InputEditor/insertLocalFolderMentions';import { useAgentStore } from '@/store/agent';-import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';+import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';import ConversationArea from './ConversationArea';@@ -19,10 +19,16 @@ const wrapperStyle: React.CSSProperties = {};const ChatConversation = memo(() => {- const model = useAgentStore(agentSelectors.currentAgentModel);- const provider = useAgentStore(agentSelectors.currentAgentModelProvider);- const isHeterogeneous = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);- const isLocalSystemEnabled = useAgentStore(agentChatConfigSelectors.isLocalSystemEnabled);+ // ChatConversation sits above the ConversationProvider, so read the routed+ // agent from the chat store (set by AgentIdSync, not the hijack-prone agent+ // store) and feed it to the scoped `*ById` selectors.+ const agentId = useChatStore((s) => s.activeAgentId) || '';+ const model = useAgentStore(agentByIdSelectors.getAgentModelById(agentId));+ const provider = useAgentStore(agentByIdSelectors.getAgentModelProviderById(agentId));+ const isHeterogeneous = useAgentStore(agentByIdSelectors.isAgentHeterogeneousById(agentId));+ const isLocalSystemEnabled = useAgentStore(+ chatConfigByIdSelectors.isLocalSystemEnabledById(agentId),+ );const { handleUploadFiles } = useUploadFiles({ model, provider });diff --git a/src/store/agent/selectors/agentByIdSelectors.test.ts b/src/store/agent/selectors/agentByIdSelectors.test.tsindex 5f405519f59..4118a9d1cd5 100644--- a/src/store/agent/selectors/agentByIdSelectors.test.ts+++ b/src/store/agent/selectors/agentByIdSelectors.test.ts@@ -155,4 +155,37 @@ describe('agentByIdSelectors', () => {);});});++ describe('getAgentConfigErrorById', () => {+ it('returns the recorded error for the agent', () => {+ const state = createState({ agentConfigErrorMap: { 'agent-1': 'boom' } });++ expect(agentByIdSelectors.getAgentConfigErrorById('agent-1')(state)).toBe('boom');+ });++ it('returns undefined for another agent or an empty id', () => {+ const state = createState({ agentConfigErrorMap: { 'agent-1': 'boom' } });++ expect(agentByIdSelectors.getAgentConfigErrorById('agent-2')(state)).toBeUndefined();+ expect(agentByIdSelectors.getAgentConfigErrorById('')(state)).toBeUndefined();+ });+ });++ describe('getAgentTTSVoiceById', () => {+ it('returns the configured openai voice', () => {+ const state = createState({+ agentMap: {+ 'agent-1': { tts: { ttsService: 'openai', voice: { openai: 'nova' } } },+ },+ });++ expect(agentByIdSelectors.getAgentTTSVoiceById('agent-1', 'en-US')(state)).toBe('nova');+ });++ it('falls back to a default voice when the agent config is missing', () => {+ const state = createState({ agentMap: {} });++ expect(agentByIdSelectors.getAgentTTSVoiceById('missing', 'en-US')(state)).toBeTruthy();+ });+ });});diff --git a/src/store/agent/selectors/agentByIdSelectors.ts b/src/store/agent/selectors/agentByIdSelectors.tsindex 7e74221680d..9a2b6234aaa 100644--- a/src/store/agent/selectors/agentByIdSelectors.ts+++ b/src/store/agent/selectors/agentByIdSelectors.ts@@ -7,6 +7,7 @@ import {type LobeAgentTTSConfig,type RuntimeEnvConfig,} from '@lobechat/types';+import { VoiceList } from '@lobehub/tts';import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';@@ -44,6 +45,34 @@ const getAgentTTSById =(s: AgentStoreState): LobeAgentTTSConfig =>agentSelectors.getAgentConfigById(agentId)(s)?.tts || DEFAUTT_AGENT_TTS_CONFIG;+const getAgentTTSVoiceById =+ (agentId: string, lang: string) =>+ (s: AgentStoreState): string => {+ const { voice, ttsService } = getAgentTTSById(agentId)(s);+ const voiceList = new VoiceList(lang);+ let currentVoice;+ switch (ttsService) {+ case 'openai': {+ currentVoice = voice.openai || (VoiceList.openaiVoiceOptions?.[0].value as string);+ break;+ }+ case 'edge': {+ currentVoice = voice.edge || (voiceList.edgeVoiceOptions?.[0].value as string);+ break;+ }+ case 'microsoft': {+ currentVoice = voice.microsoft || (voiceList.microsoftVoiceOptions?.[0].value as string);+ break;+ }+ }+ return currentVoice || 'alloy';+ };++const getAgentConfigErrorById =+ (agentId: string) =>+ (s: AgentStoreState): string | undefined =>+ agentId ? s.agentConfigErrorMap[agentId] : undefined;+const getAgentFilesById = (agentId: string) => (s: AgentStoreState) =>agentSelectors.getAgentConfigById(agentId)(s)?.files || [];@@ -172,6 +201,7 @@ export const agentByIdSelectors = {getAgentBuilderContextById,getAgentById,getAgentConfigById: agentSelectors.getAgentConfigById,+ getAgentConfigErrorById,getAgentEnableModeById,getAgentFilesById,getAgentKnowledgeBasesById,@@ -182,6 +212,7 @@ export const agentByIdSelectors = {getAgentPluginsById,getAgentSystemRoleById,getAgentTTSById,+ getAgentTTSVoiceById,getAgentWorkingDirectoryById,isAgentConfigLoadingById,isAgentHeterogeneousById,