π€― 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(chat): keep agent tools while model runtime-state is loading (#16638)
LiJian0a5bc263384b
diff --git a/src/features/ChatInput/hooks/useEffectiveAgentMode.test.ts b/src/features/ChatInput/hooks/useEffectiveAgentMode.test.tsindex b0085d0fe62..7abbaeaf26b 100644--- a/src/features/ChatInput/hooks/useEffectiveAgentMode.test.ts+++ b/src/features/ChatInput/hooks/useEffectiveAgentMode.test.ts@@ -32,4 +32,56 @@ describe('resolveEffectiveAgentMode', () => {supportToolUse: true,});});++ describe('when the model list is not ready yet', () => {+ it('honours stored agent mode instead of downgrading on the transient unknown', () => {+ // supportToolUse is `false` only because the model has not hydrated yet.+ // We must NOT flash to chat mode / mark agent mode unavailable.+ expect(+ resolveEffectiveAgentMode({+ enableAgentMode: true,+ isModelListReady: false,+ supportToolUse: false,+ }),+ ).toEqual({+ canSelectAgentMode: true,+ currentMode: 'agent',+ isAgentModeUnavailable: false,+ isAgentRuntimeMode: true,+ supportToolUse: true,+ });+ });++ it('still respects an explicit chat-mode choice while not ready', () => {+ expect(+ resolveEffectiveAgentMode({+ enableAgentMode: false,+ isModelListReady: false,+ supportToolUse: false,+ }),+ ).toEqual({+ canSelectAgentMode: true,+ currentMode: 'chat',+ isAgentModeUnavailable: false,+ isAgentRuntimeMode: false,+ supportToolUse: true,+ });+ });++ it('applies the real capability once the list becomes ready', () => {+ expect(+ resolveEffectiveAgentMode({+ enableAgentMode: true,+ isModelListReady: true,+ supportToolUse: false,+ }),+ ).toEqual({+ canSelectAgentMode: false,+ currentMode: 'chat',+ isAgentModeUnavailable: true,+ isAgentRuntimeMode: false,+ supportToolUse: false,+ });+ });+ });});diff --git a/src/features/ChatInput/hooks/useEffectiveAgentMode.ts b/src/features/ChatInput/hooks/useEffectiveAgentMode.tsindex 6a67530ae4f..4c93b1187b5 100644--- a/src/features/ChatInput/hooks/useEffectiveAgentMode.ts+++ b/src/features/ChatInput/hooks/useEffectiveAgentMode.ts@@ -1,28 +1,44 @@import { useModelSupportToolUse } from '@/hooks/useModelSupportToolUse';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';+import { aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';export type ChatInputMode = 'agent' | 'chat';interface ResolveEffectiveAgentModeParams {enableAgentMode: boolean;+ /**+ * Whether the aiProvider runtime-state (the enabled-model list + abilities)+ * has finished loading. Defaults to `true` so callers that don't track it keep+ * the prior behaviour.+ */+ isModelListReady?: boolean;supportToolUse: boolean;}export const resolveEffectiveAgentMode = ({enableAgentMode,+ isModelListReady = true,supportToolUse,}: ResolveEffectiveAgentModeParams) => {- const currentMode: ChatInputMode = enableAgentMode && supportToolUse ? 'agent' : 'chat';+ // While the model list is not ready, `supportToolUse` is `false` only because+ // the model hasn't hydrated into the store yet β not because it lacks tool+ // calling. Downgrading to chat mode on that transient unknown would drop tools+ // and flash the mode pill to "chat" on first paint. Assume tool use is+ // available while loading and honour the user's stored intent; the real+ // capability re-evaluates once the list loads.+ const effectiveSupportToolUse = isModelListReady ? supportToolUse : true;++ const currentMode: ChatInputMode = enableAgentMode && effectiveSupportToolUse ? 'agent' : 'chat';// Example: stored Agent mode + a model without tool calling should render chat-only runtime UI.const isAgentRuntimeMode = currentMode === 'agent';return {- canSelectAgentMode: supportToolUse,+ canSelectAgentMode: effectiveSupportToolUse,currentMode,- isAgentModeUnavailable: enableAgentMode && !supportToolUse,+ isAgentModeUnavailable: enableAgentMode && !effectiveSupportToolUse,isAgentRuntimeMode,- supportToolUse,+ supportToolUse: effectiveSupportToolUse,};};@@ -33,6 +49,7 @@ export const useEffectiveAgentMode = (agentId: string) => {agentByIdSelectors.getAgentModelProviderById(agentId)(s),]);const supportToolUse = useModelSupportToolUse(model, provider);+ const isModelListReady = useAiInfraStore(aiProviderSelectors.isInitAiProviderRuntimeState);- return resolveEffectiveAgentMode({ enableAgentMode, supportToolUse });+ return resolveEffectiveAgentMode({ enableAgentMode, isModelListReady, supportToolUse });};diff --git a/src/helpers/isCanUseFC.test.ts b/src/helpers/isCanUseFC.test.tsnew file mode 100644index 00000000000..727a66bdb3a--- /dev/null+++ b/src/helpers/isCanUseFC.test.ts@@ -0,0 +1,53 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import * as aiInfraStore from '@/store/aiInfra';++import { isCanUseFC } from './isCanUseFC';++const modelWithFC = { abilities: { functionCall: true }, id: 'gpt-4', providerId: 'openai' };+const modelWithoutFC = { abilities: { functionCall: false }, id: 'no-tools', providerId: 'openai' };++const mockAiInfraState = (state: Record<string, unknown>) =>+ vi.spyOn(aiInfraStore, 'getAiInfraStoreState').mockReturnValue(state as any);++afterEach(() => {+ vi.restoreAllMocks();+});++describe('isCanUseFC', () => {+ describe('while the aiProvider runtime-state is not ready', () => {+ it('assumes function calling is available (unknown must not be treated as "no FC")', () => {+ mockAiInfraState({ enabledAiModels: [], isInitAiProviderRuntimeState: false });++ // Even though the model is absent from the (empty, not-yet-loaded) list,+ // we must not report `false` β that would force chat mode and drop tools.+ expect(isCanUseFC('gpt-4', 'openai')).toBe(true);+ });++ it('assumes function calling is available for an unknown model too', () => {+ mockAiInfraState({ enabledAiModels: [], isInitAiProviderRuntimeState: false });++ expect(isCanUseFC('claude-sonnet-4-6', 'lobehub')).toBe(true);+ });+ });++ describe('once the aiProvider runtime-state is ready', () => {+ it('returns true when the model supports function calling', () => {+ mockAiInfraState({ enabledAiModels: [modelWithFC], isInitAiProviderRuntimeState: true });++ expect(isCanUseFC('gpt-4', 'openai')).toBe(true);+ });++ it('returns false when the model does not support function calling', () => {+ mockAiInfraState({ enabledAiModels: [modelWithoutFC], isInitAiProviderRuntimeState: true });++ expect(isCanUseFC('no-tools', 'openai')).toBe(false);+ });++ it('returns false when the model is absent from the enabled list', () => {+ mockAiInfraState({ enabledAiModels: [], isInitAiProviderRuntimeState: true });++ expect(isCanUseFC('gpt-4', 'openai')).toBe(false);+ });+ });+});diff --git a/src/helpers/isCanUseFC.ts b/src/helpers/isCanUseFC.tsindex 3fa1565dc0d..3c013c6fb13 100644--- a/src/helpers/isCanUseFC.ts+++ b/src/helpers/isCanUseFC.ts@@ -1,5 +1,18 @@-import { aiModelSelectors, getAiInfraStoreState } from '@/store/aiInfra';+import { aiModelSelectors, aiProviderSelectors, getAiInfraStoreState } from '@/store/aiInfra';export const isCanUseFC = (model: string, provider: string): boolean => {- return aiModelSelectors.isModelSupportToolUse(model, provider)(getAiInfraStoreState()) || false;+ const state = getAiInfraStoreState();++ // The enabled-model list hydrates asynchronously (BetterAuth session resolves+ // β `isLoaded` β the aiProvider runtime-state SWR fires β `enabledAiModels` is+ // populated). Until it's ready the model simply isn't in the store yet, so+ // `isModelSupportToolUse` returns `false` for reasons of *timing*, not+ // capability. Treating that transient unknown as "no function calling" forces+ // chat mode and silently drops every user tool for the first message(s) after+ // page load. Assume function calling is available until the list is ready; the+ // real capability check applies once it loads, and the server re-derives it+ // authoritatively for gateway runs.+ if (!aiProviderSelectors.isInitAiProviderRuntimeState(state)) return true;++ return aiModelSelectors.isModelSupportToolUse(model, provider)(state) || false;};diff --git a/src/store/aiInfra/slices/aiProvider/action.test.ts b/src/store/aiInfra/slices/aiProvider/action.test.tsnew file mode 100644index 00000000000..31f7d2ab9d1--- /dev/null+++ b/src/store/aiInfra/slices/aiProvider/action.test.ts@@ -0,0 +1,67 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { useAiInfraStore } from '@/store/aiInfra';++describe('AiProviderAction', () => {+ describe('ensureAiProviderRuntimeStateReady', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ vi.useRealTimers();+ useAiInfraStore.setState({ isInitAiProviderRuntimeState: false });+ });++ it('resolves immediately without refreshing when the runtime-state is already loaded', async () => {+ const refresh = vi.fn(async () => {});+ useAiInfraStore.setState({+ isInitAiProviderRuntimeState: true,+ refreshAiProviderRuntimeState: refresh,+ });++ await useAiInfraStore.getState().ensureAiProviderRuntimeStateReady();++ expect(refresh).not.toHaveBeenCalled();+ });++ it('triggers a refresh and awaits it when the runtime-state is not loaded', async () => {+ const refresh = vi.fn(async () => {});+ useAiInfraStore.setState({+ isInitAiProviderRuntimeState: false,+ refreshAiProviderRuntimeState: refresh,+ });++ await useAiInfraStore.getState().ensureAiProviderRuntimeStateReady();++ expect(refresh).toHaveBeenCalledTimes(1);+ });++ it('falls back after the timeout when the refresh never settles', async () => {+ vi.useFakeTimers();+ // A refresh that never resolves β e.g. still gated behind an unresolved+ // auth session. The caller must not be blocked forever.+ const refresh = vi.fn(() => new Promise<void>(() => {}));+ useAiInfraStore.setState({+ isInitAiProviderRuntimeState: false,+ refreshAiProviderRuntimeState: refresh,+ });++ const pending = useAiInfraStore.getState().ensureAiProviderRuntimeStateReady(1000);+ await vi.advanceTimersByTimeAsync(1000);++ await expect(pending).resolves.toBeUndefined();+ });++ it('does not reject when the refresh throws', async () => {+ const refresh = vi.fn(async () => {+ throw new Error('network down');+ });+ useAiInfraStore.setState({+ isInitAiProviderRuntimeState: false,+ refreshAiProviderRuntimeState: refresh,+ });++ await expect(+ useAiInfraStore.getState().ensureAiProviderRuntimeStateReady(),+ ).resolves.toBeUndefined();+ });+ });+});diff --git a/src/store/aiInfra/slices/aiProvider/action.ts b/src/store/aiInfra/slices/aiProvider/action.tsindex 804c35ed738..1e981ad58b5 100644--- a/src/store/aiInfra/slices/aiProvider/action.ts+++ b/src/store/aiInfra/slices/aiProvider/action.ts@@ -307,6 +307,29 @@ export class AiProviderActionImpl {]);};+ /**+ * Resolve once the aiProvider runtime-state (the enabled-model list + model+ * abilities) has loaded, so callers can decide function-calling / tool+ * capability from *real* data instead of guessing while it's still hydrating.+ *+ * No-op when already loaded. Otherwise it triggers/awaits the (usually already+ * in-flight) fetch, bounded by `timeoutMs` so a slow or blocked request β e.g.+ * one still gated behind an unresolved auth session β never holds up the+ * caller indefinitely; it then proceeds on whatever state is available.+ */+ ensureAiProviderRuntimeStateReady = async (timeoutMs = 3000): Promise<void> => {+ if (this.#get().isInitAiProviderRuntimeState) return;++ await Promise.race([+ this.#get()+ .refreshAiProviderRuntimeState()+ .catch(() => undefined),+ new Promise<void>((resolve) => {+ setTimeout(resolve, timeoutMs);+ }),+ ]);+ };+removeAiProvider = async (id: string): Promise<void> => {await aiProviderService.deleteAiProvider(id);await this.#get().refreshAiProviderList();diff --git a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.tsindex 6b105430a8b..f2949e14246 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts@@ -140,6 +140,9 @@ beforeEach(() => {act(() => {useAgentStore.setState({ availableAgents: [] });+ // executeClientAgent waits for the aiProvider runtime-state before building+ // tools; mark it ready so that guard is a no-op in these tests.+ useAiInfraStore.setState({ isInitAiProviderRuntimeState: true });useChatStore.setState({refreshMessages: vi.fn(),executeClientAgent: vi.fn(),diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.tsindex 0a6e2ee524b..43f05981967 100644--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts@@ -510,6 +510,16 @@ export class StreamingExecutorActionImpl {// Create a new array to avoid modifying the original messagesconst messages = [...originalMessages];+ // Decide tool / function-calling capability from real data, not a guess.+ // The enabled-model list hydrates asynchronously (auth session β aiProvider+ // runtime-state SWR); until it's ready `isCanUseFC` optimistically assumes+ // tool use so we don't drop tools for a capable model. But this is the+ // outbound path: `createAgentToolsEngine` below bakes the tool set into the+ // payload and the `/webapi/chat/[provider]` route forwards it to the provider+ // without rechecking capability. Wait (bounded) for the list so a fast first+ // send after reload never attaches tools to a model that can't use them.+ await getAiInfraStoreState().ensureAiProviderRuntimeStateReady();+// ===========================================// Step 1: Create Agent State (resolves config once)// ===========================================