Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
📌 fix: Keep the Composer Thinking Level for the Rest of the Conversation (#17497)
Marco Beretta749c1a394398
diff --git a/api/server/middleware/buildEndpointOption.js b/api/server/middleware/buildEndpointOption.jsindex cb33cb4be1..131899dac3 100644--- a/api/server/middleware/buildEndpointOption.js+++ b/api/server/middleware/buildEndpointOption.js@@ -22,7 +22,7 @@ const azureAssistants = require('~/server/services/Endpoints/azureAssistants');const assistants = require('~/server/services/Endpoints/assistants');const { getEndpointsConfig } = require('~/server/services/Config');const agents = require('~/server/services/Endpoints/agents');-const { updateFilesUsage } = require('~/models');+const { updateFilesUsage, getBranchReasoningOverride } = require('~/models');const buildFunction = {[EModelEndpoint.agents]: agents.buildOptions,@@ -198,6 +198,7 @@ async function buildEndpointOption(req, res, next) {enforcedModelSpecFields,loadReasoningCapabilities: (endpointName) =>getReasoningCapabilities(appConfig, endpointName),+ getBranchReasoningOverride,});if (!reasoningApplied) {return handleError(res, { text: 'Invalid reasoning override' });diff --git a/client/src/components/Chat/Input/Composer/Effort.tsx b/client/src/components/Chat/Input/Composer/Effort.tsxindex 9873ee4480..3d9cc98b7f 100644--- a/client/src/components/Chat/Input/Composer/Effort.tsx+++ b/client/src/components/Chat/Input/Composer/Effort.tsx@@ -1,4 +1,4 @@-import { memo, useRef, useMemo, useState, useEffect, useCallback, useLayoutEffect } from 'react';+import { memo, useRef, useMemo, useState, useEffect, useCallback } from 'react';import { CircleHelp } from 'lucide-react';import { Constants, reasoningOverrideSchema } from 'librechat-data-provider';import {@@ -184,11 +184,10 @@ function Effort({ setting, conversation, value, onChange }: EffortProps) {: -1;const restoreIndex = rememberedIndex >= 0 ? rememberedIndex : 0;const shownIndex = activeIndex >= 0 ? activeIndex : restoreIndex;- const initialShownIndex = useRef(shownIndex);-- useLayoutEffect(() => {- stopRefs.current[initialShownIndex.current]?.focus();- }, []);+ /* Where the popover's own autofocus lands on open. In the separate mode no+ level is checked, so it starts on the pressed toggle that names that mode+ rather than on an unchecked, unlabelled stop. */+ const initialFocus = useRef({ index: shownIndex, ungraded: isUngraded && ungradedValue != null });const select = useCallback((nextValue: string) => {@@ -477,6 +476,11 @@ function Effort({ setting, conversation, value, onChange }: EffortProps) {between them. In the ungraded mode no level is checked, so the one thatwould be restored takes the tab stop. */tabIndex={index === shownIndex ? 0 : -1}+ data-autofocus={+ !initialFocus.current.ungraded && index === initialFocus.current.index+ ? true+ : undefined+ }onKeyDown={(event) => {const step = ARROW_STEP[event.key];if (step === undefined) {@@ -529,6 +533,7 @@ function Effort({ setting, conversation, value, onChange }: EffortProps) {{ungradedValue != null && (<Buttonvariant="pill-toggle"+ data-autofocus={initialFocus.current.ungraded ? true : undefined}aria-pressed={isUngraded}onClick={() => select(isUngraded ? levels[restoreIndex] : ungradedValue)}>diff --git a/client/src/components/Chat/Input/Composer/Thinking.tsx b/client/src/components/Chat/Input/Composer/Thinking.tsxindex 43ec3c3c24..8ddcb0528d 100644--- a/client/src/components/Chat/Input/Composer/Thinking.tsx+++ b/client/src/components/Chat/Input/Composer/Thinking.tsx@@ -1,8 +1,17 @@import { memo, useRef, useMemo, useState, useLayoutEffect } from 'react';+import { useAtomValue } from 'jotai';import * as Ariakit from '@ariakit/react';import { ChevronDown } from 'lucide-react';+import { Constants } from 'librechat-data-provider';+import { getAppendParentMessageId } from '@librechat/chat';+import { queuedMessagesByConvoId } from '@librechat/chat/react';import { Button, TooltipAnchor, useMediaQuery } from '@librechat/client';-import type { SettingDefinition, TConversation, TReasoningOverride } from 'librechat-data-provider';+import type {+ TMessage,+ TConversation,+ SettingDefinition,+ TReasoningOverride,+} from 'librechat-data-provider';import { ReasoningControl, useComposerReasoning } from '../Reasoning';import Effort, { effortRank, resolveEffortLabel } from './Effort';import { useGetStartupConfig } from '~/data-provider';@@ -243,6 +252,30 @@ function ThinkingControl({** Split in two so the control's hooks are never behind that early return.*/+/**+ * The level a branch runs at, by the server's rule: the override on the nearest user message at or+ * above `fromMessageId` that carries one.+ */+function getBranchReasoning(+ messages: TMessage[],+ fromMessageId: string,+): TMessage['reasoningOverride'] {+ const byId = new Map<string, TMessage>();+ for (const message of messages) {+ byId.set(message.messageId, message);+ }+ const visited = new Set<string>();+ let current = byId.get(fromMessageId);+ while (current != null && !visited.has(current.messageId)) {+ visited.add(current.messageId);+ if (current.isCreatedByUser === true && current.reasoningOverride != null) {+ return current.reasoningOverride;+ }+ current = current.parentMessageId != null ? byId.get(current.parentMessageId) : undefined;+ }+ return undefined;+}+interface ThinkingProps {index: number;disabled: boolean;@@ -250,7 +283,7 @@ interface ThinkingProps {}function Thinking({ index, disabled, hasAddedConversation }: ThinkingProps) {- const { conversation } = useChatContext();+ const { conversation, latestMessageId, getMessages } = useChatContext();const { data: startupConfig } = useGetStartupConfig();const parametersEnabled = startupConfig?.interface?.parameters;const modelSpec = getModelSpec({ specName: conversation?.spec, startupConfig });@@ -260,12 +293,45 @@ function Thinking({ index, disabled, hasAddedConversation }: ThinkingProps) {}return new Set(Object.keys(modelSpec.preset));}, [modelSpec?.preset, startupConfig?.modelSpecs?.enforce]);+ const queueKey =+ conversation?.conversationId != null && conversation.conversationId !== ''+ ? conversation.conversationId+ : Constants.NEW_CONVO;+ const queued = useAtomValue(queuedMessagesByConvoId(queueKey));+ /* The server runs a turn without its own pick at the level its branch last ran at, so the+ button names that level: the latest pick still waiting in the queue, otherwise the one the+ branch the composer extends carries. */+ const queuedReasoning = useMemo(() => {+ for (let i = queued.length - 1; i >= 0; i--) {+ const row = queued[i];+ /* A held row waits for an explicit send, so it is not the turn that runs next. */+ if (row.heldByUser === true || row.needsExplicitSend === true) {+ continue;+ }+ if (row.reasoningOverride != null) {+ return row.reasoningOverride;+ }+ }+ return undefined;+ }, [queued]);+ const branchReasoning = useMemo(() => {+ if (queuedReasoning != null) {+ return queuedReasoning;+ }+ const messages = getMessages(conversation?.conversationId) ?? [];+ const latestMessage = messages.find((message) => message.messageId === latestMessageId);+ return getBranchReasoning(+ messages,+ getAppendParentMessageId({ latestMessage: latestMessage ?? null, currentMessages: messages }),+ );+ }, [conversation?.conversationId, getMessages, latestMessageId, queuedReasoning]);const reasoning = useComposerReasoning({conversation: conversation ?? null,index,hasAddedConversation,enabled: parametersEnabled,blockedReasoningKeys,+ branchReasoning,});if (parametersEnabled !== true || reasoning == null) {diff --git a/client/src/components/Chat/Input/Composer/__tests__/Thinking.spec.tsx b/client/src/components/Chat/Input/Composer/__tests__/Thinking.spec.tsxindex 133550c46e..992553e21b 100644--- a/client/src/components/Chat/Input/Composer/__tests__/Thinking.spec.tsx+++ b/client/src/components/Chat/Input/Composer/__tests__/Thinking.spec.tsx@@ -1,7 +1,10 @@import React, { createRef } from 'react';+import { getDefaultStore } from 'jotai';import { ReasoningEffort } from 'librechat-data-provider';-import { fireEvent, render, screen } from '@testing-library/react';+import { queuedMessagesByConvoId } from '@librechat/chat/react';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';import type { SettingDefinition, TConversation, TReasoningOverride } from 'librechat-data-provider';+import type { QueuedMessage } from '@librechat/chat';import type * as ReasoningModule from '../../Reasoning';import { effortRank, leanFor } from '../Effort';import Thinking from '../Thinking';@@ -24,10 +27,11 @@ const mockChatContext = React.createContext<{ conversation: TConversation | nulljest.mock('../../Reasoning', () => ({ReasoningControl: jest.requireActual<typeof ReasoningModule>('../../Reasoning').ReasoningControl,- useComposerReasoning: () => ({+ useComposerReasoning: ({ branchReasoning }: { branchReasoning?: TReasoningOverride }) => ({setting: mockSetting,value:mockPendingOverride ??+ branchReasoning ??({key: mockSetting.key,value: mockConversation[mockSetting.key as keyof TConversation] ?? mockSetting.default,@@ -65,8 +69,11 @@ jest.mock('~/data-provider', () => ({}));jest.mock('~/Providers', () => ({- useChatContext: () =>- jest.requireActual<typeof import('react')>('react').useContext(mockChatContext),+ useChatContext: () => ({+ ...jest.requireActual<typeof import('react')>('react').useContext(mockChatContext),+ latestMessageId: undefined,+ getMessages: () => [],+ }),}));function renderInComposer({@@ -120,7 +127,7 @@ describe('Thinking', () => {} as SettingDefinition;renderInComposer({ index: 1 });- fireEvent.click(screen.getByRole('button', { name: /com_ui_reasoning_for_next_message/ }));+ fireEvent.click(screen.getByRole('button', { name: /com_ui_composer_thinking/ }));const slider = screen.getByRole('slider');slider.focus();fireEvent.keyDown(slider, { key: 'ArrowRight' });@@ -178,7 +185,7 @@ describe('Thinking', () => {expect(mockConversation.reasoning_effort).toBe('low');});- it('keeps activation inside the control and supports arrow-key navigation', () => {+ it('keeps activation inside the control and supports arrow-key navigation', async () => {const { onComposerClick } = renderInComposer();const disclosure = screen.getByTestId('composer-thinking-button');@@ -188,8 +195,7 @@ describe('Thinking', () => {expect(onComposerClick).not.toHaveBeenCalled();expect(screen.getByRole('radiogroup')).toBeVisible();const low = screen.getByRole('radio', { name: 'Low' });- low.focus();- expect(low).toHaveFocus();+ await waitFor(() => expect(low).toHaveFocus());fireEvent.keyDown(low, { key: 'ArrowRight' });expect(screen.getByRole('radio', { name: 'High' })).toHaveFocus();@@ -256,6 +262,82 @@ describe('Thinking', () => {expect(mockSetValue).toHaveBeenCalledWith({ key: 'reasoning_effort', value: 'low' });});+ it('focuses the Auto toggle when the popover opens in Auto', async () => {+ mockSetting = {+ key: 'reasoning_effort',+ type: 'enum',+ default: '',+ options: ['', 'none', 'low', 'medium', 'xhigh'],+ } as unknown as SettingDefinition;+ mockConversation = { conversationId: 'convo-1' } as unknown as TConversation;+ renderInComposer();++ fireEvent.click(screen.getByTestId('composer-thinking-button'));++ await waitFor(() => expect(screen.getByRole('button', { name: 'Auto' })).toHaveFocus());+ expect(screen.getByRole('button', { name: 'Auto' })).toHaveAttribute('aria-pressed', 'true');+ });++ it('focuses the first level when the option list has no Auto value', async () => {+ mockSetting = {+ key: 'reasoning_effort',+ type: 'enum',+ options: ['low', 'high'],+ } as unknown as SettingDefinition;+ mockConversation = { conversationId: 'convo-1' } as unknown as TConversation;+ renderInComposer();+ fireEvent.click(screen.getByTestId('composer-thinking-button'));++ await waitFor(() => expect(screen.getByRole('radio', { name: 'Low' })).toHaveFocus());+ expect(screen.queryByRole('button', { name: 'Auto' })).not.toBeInTheDocument();+ });++ it('focuses the current level when the popover opens on one', async () => {+ renderInComposer();+ fireEvent.click(screen.getByTestId('composer-thinking-button'));++ await waitFor(() => expect(screen.getByRole('radio', { name: 'Low' })).toHaveFocus());+ });++ it('names the level the last queued turn will run at', () => {+ const store = getDefaultStore();+ store.set(queuedMessagesByConvoId('convo-1'), [+ {+ id: 'queued-1',+ text: 'next',+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },+ } as QueuedMessage,+ ]);+ try {+ renderInComposer();+ expect(screen.getByTestId('composer-thinking-button')).toHaveAccessibleName(+ 'com_ui_composer_thinking_value:High',+ );+ } finally {+ store.set(queuedMessagesByConvoId('convo-1'), []);+ }+ });++ it('ignores a held queued turn when naming the next level', () => {+ const store = getDefaultStore();+ store.set(queuedMessagesByConvoId('convo-1'), [+ {+ id: 'held-1',+ text: 'waiting',+ heldByUser: true,+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },+ } as QueuedMessage,+ ]);+ try {+ renderInComposer();+ expect(screen.getByTestId('composer-thinking-button')).toHaveAccessibleName(+ 'com_ui_composer_thinking_value:Low',+ );+ } finally {+ store.set(queuedMessagesByConvoId('convo-1'), []);+ }+ });+it('does not carry a remembered level across model settings', () => {mockConversation = {conversationId: 'convo-1',diff --git a/client/src/components/Chat/Input/Reasoning.tsx b/client/src/components/Chat/Input/Reasoning.tsxindex 0427b43178..f3bfcf88cb 100644--- a/client/src/components/Chat/Input/Reasoning.tsx+++ b/client/src/components/Chat/Input/Reasoning.tsx@@ -18,6 +18,7 @@ import {} from 'librechat-data-provider';import type {Agent,+ TMessage,SettingDefinition,TConversation,TReasoningOverride,@@ -118,7 +119,7 @@ export function ReasoningControl({<Buttonvariant="composer-trigger"disabled={disabled}- aria-label={`${localize('com_ui_reasoning_for_next_message')} ${displayValue}`}+ aria-label={`${localize('com_ui_composer_thinking')} ${displayValue}`}><BrainCircuit className="size-4" aria-hidden="true" /><ChevronDown className="size-3" aria-hidden="true" />@@ -140,7 +141,7 @@ export function ReasoningControl({{label}</div><div className="text-text-secondary truncate text-xs">- {localize('com_ui_reasoning_for_next_message')}+ {localize('com_ui_composer_thinking')}</div></div><Popover.Close asChild>@@ -248,12 +249,21 @@ export function ReasoningControl({);}+/** Override keys whose level also turns thinking on. */+const THINKING_LEVEL_KEYS: ReadonlySet<string> = new Set([+ 'effort',+ 'thinkingLevel',+ 'thinkingBudget',+]);+type ComposerReasoningOptions = {conversation: TConversation | null;index: number;hasAddedConversation?: boolean;enabled?: boolean;blockedReasoningKeys?: ReadonlySet<string>;+ /** The level the branch the next turn extends last ran at; shown until the user picks again. */+ branchReasoning?: TMessage['reasoningOverride'];};type ComposerReasoningState = {@@ -268,6 +278,7 @@ export function useComposerReasoning({hasAddedConversation = false,enabled = true,blockedReasoningKeys,+ branchReasoning,}: ComposerReasoningOptions): ComposerReasoningState | null {const agentsMap = useAgentsMapContext();const { data: fetchedAgent } = useGetAgentByIdQuery(conversation?.agent_id);@@ -420,14 +431,82 @@ export function useComposerReasoning({value,]);+ let configuredValue: unknown;+ if (setting != null) {+ configuredValue =+ isAgent && agent != null+ ? agent.model_parameters?.[setting.key]+ : conversation?.[setting.key];+ }+ const configuredScope = `${reasoningStateKey}\u0000${targetFingerprint ?? ''}`;+ const thinkingKey: string = 'thinking';+ const thinkingOff =+ (isAgent && agent != null ? agent.model_parameters?.[thinkingKey] : conversation?.thinking) ===+ false;+ /* Switching thinking off withdraws a staged level that would turn it back on; a level picked+ after the switch is off is the user turning it on for that turn, so it stays. */+ const previousThinking = useRef({ scope: configuredScope, off: thinkingOff });+ useEffect(() => {+ const previous = previousThinking.current;+ previousThinking.current = { scope: configuredScope, off: thinkingOff };+ if (+ previous.scope === configuredScope &&+ thinkingOff &&+ !previous.off &&+ value != null &&+ THINKING_LEVEL_KEYS.has(value.key)+ ) {+ setValue(undefined);+ }+ }, [configuredScope, setValue, thinkingOff, value]);+ /* The configured value changing while the conversation and target stay put is the user setting+ the level elsewhere (the Parameters panel). It replaces the branch level the way a composer+ pick does; otherwise the inherited level would silently outrank the edit. */+ const previousConfigured = useRef<{ scope: string; value: unknown } | null>(null);+ useEffect(() => {+ /* While the capabilities load the setting is hidden, which says nothing about the configured+ value: keep the last one seen, or its reappearance would read as an edit. */+ if (setting == null) {+ return;+ }+ const previous = previousConfigured.current;+ previousConfigured.current = { scope: configuredScope, value: configuredValue };+ if (+ previous == null ||+ previous.scope !== configuredScope ||+ Object.is(previous.value, configuredValue)+ ) {+ return;+ }+ /* A reset removes the value; it is the user choosing the default, not leaving the choice. */+ const editedValue = configuredValue ?? setting.default;+ if (editedValue == null) {+ return;+ }+ /* A pick turns thinking on; with the switch off, the panel's value stays a parameter. */+ if (thinkingOff && THINKING_LEVEL_KEYS.has(setting.key)) {+ return;+ }+ const edited = reasoningOverrideSchema.safeParse({ key: setting.key, value: editedValue });+ if (edited.success && isReasoningOverrideSupported(edited.data, setting)) {+ setValue(edited.data);+ }+ }, [configuredScope, configuredValue, setValue, setting, thinkingOff]);+if (!available || setting == null) {return null;}- const configuredValue =- isAgent && agent != null ? agent.model_parameters?.[setting.key] : conversation?.[setting.key];+ /* Mirrors the server: thinking switched off wins over a level the next turn would only inherit. */+ const inherited =+ branchReasoning != null &&+ isReasoningOverrideSupported(branchReasoning, setting) &&+ !(thinkingOff && THINKING_LEVEL_KEYS.has(branchReasoning.key))+ ? branchReasoning+ : undefined;const displayedValue =value ??+ inherited ??reasoningOverrideSchema.safeParse({key: setting.key,value: configuredValue ?? setting.default,diff --git a/client/src/components/Chat/Input/__tests__/Reasoning.spec.tsx b/client/src/components/Chat/Input/__tests__/Reasoning.spec.tsxindex adaafa4e66..120f6e0ad1 100644--- a/client/src/components/Chat/Input/__tests__/Reasoning.spec.tsx+++ b/client/src/components/Chat/Input/__tests__/Reasoning.spec.tsx@@ -103,7 +103,7 @@ describe('ReasoningControl', () => {);const trigger = screen.getByRole('button', {- name: 'com_ui_reasoning_for_next_message com_ui_medium',+ name: 'com_ui_composer_thinking com_ui_medium',});fireEvent.click(trigger);@@ -124,7 +124,7 @@ describe('ReasoningControl', () => {/>,);- fireEvent.click(screen.getByRole('button', { name: /com_ui_reasoning_for_next_message/ }));+ fireEvent.click(screen.getByRole('button', { name: /com_ui_composer_thinking/ }));const slider = screen.getByRole('slider', { name: 'com_endpoint_reasoning_effort' });expect(slider).toHaveAttribute('aria-valuenow', '3');expect(slider).toHaveAttribute('aria-valuetext', 'com_ui_medium');@@ -146,7 +146,7 @@ describe('ReasoningControl', () => {/>,);- fireEvent.click(screen.getByRole('button', { name: /com_ui_reasoning_for_next_message/ }));+ fireEvent.click(screen.getByRole('button', { name: /com_ui_composer_thinking/ }));const dialog = screen.getByRole('dialog', { name: 'com_endpoint_reasoning_effort' });expect(dialog).toBeVisible();@@ -164,7 +164,7 @@ describe('ReasoningControl', () => {/>,);- fireEvent.click(screen.getByRole('button', { name: /com_ui_reasoning_for_next_message/ }));+ fireEvent.click(screen.getByRole('button', { name: /com_ui_composer_thinking/ }));const slider = screen.getByRole('slider', { name: 'com_endpoint_thinking_budget' });expect(slider).toHaveAttribute('aria-valuemin', '128');expect(slider).toHaveAttribute('aria-valuemax', '32768');@@ -194,7 +194,7 @@ describe('ReasoningControl', () => {/>,);- fireEvent.click(screen.getByRole('button', { name: /com_ui_reasoning_for_next_message/ }));+ fireEvent.click(screen.getByRole('button', { name: /com_ui_composer_thinking/ }));const input = screen.getByRole('spinbutton', { name: 'com_endpoint_thinking_budget' });fireEvent.change(input, { target: { value: '16' } });fireEvent.blur(input);@@ -213,7 +213,7 @@ describe('ReasoningControl', () => {/>,);- fireEvent.click(screen.getByRole('button', { name: /com_ui_reasoning_for_next_message/ }));+ fireEvent.click(screen.getByRole('button', { name: /com_ui_composer_thinking/ }));const input = screen.getByRole('spinbutton', { name: 'com_endpoint_thinking_budget' });fireEvent.focus(input);fireEvent.blur(input);@@ -234,7 +234,7 @@ describe('ReasoningControl', () => {/>,);- fireEvent.click(screen.getByRole('button', { name: /com_ui_reasoning_for_next_message/ }));+ fireEvent.click(screen.getByRole('button', { name: /com_ui_composer_thinking/ }));const input = screen.getByRole('spinbutton', { name: 'com_endpoint_thinking_budget' });fireEvent.change(input, { target: { value: '' } });fireEvent.blur(input);@@ -401,6 +401,305 @@ describe('useComposerReasoning', () => {);});+ it('shows the level the branch last ran at until the user picks another', async () => {+ const reasoningStore = createStore();+ const wrapper = ({ children }: { children: ReactNode }) => (+ <RecoilRoot>+ <JotaiProvider store={reasoningStore}>{children}</JotaiProvider>+ </RecoilRoot>+ );+ const rendered = renderHook(+ ({ branchReasoning }: { branchReasoning?: TReasoningOverride }) =>+ useComposerReasoning({+ conversation: {+ conversationId: 'branch-conversation',+ endpoint: 'openAI',+ model: 'gpt-5',+ } as TConversation,+ index: 0,+ enabled: true,+ branchReasoning,+ }),+ {+ initialProps: {+ branchReasoning: {+ key: 'reasoning_effort',+ value: ReasoningEffort.high,+ } as TReasoningOverride,+ },+ wrapper,+ },+ );++ await waitFor(() =>+ expect(rendered.result.current?.value).toEqual({+ key: 'reasoning_effort',+ value: ReasoningEffort.high,+ }),+ );++ act(() => {+ rendered.result.current?.setValue({ key: 'reasoning_effort', value: ReasoningEffort.low });+ });+ expect(rendered.result.current?.value).toEqual({+ key: 'reasoning_effort',+ value: ReasoningEffort.low,+ });+ });++ it('treats a Parameters reset as choosing the default over the branch level', async () => {+ const reasoningStore = createStore();+ const wrapper = ({ children }: { children: ReactNode }) => (+ <RecoilRoot>+ <JotaiProvider store={reasoningStore}>{children}</JotaiProvider>+ </RecoilRoot>+ );+ const high = { key: 'reasoning_effort', value: ReasoningEffort.high } as TReasoningOverride;+ const base = {+ conversationId: 'reset-conversation',+ endpoint: 'openAI',+ model: 'gpt-5',+ } as TConversation;+ const rendered = renderHook(+ ({ conversation }: { conversation: TConversation }) =>+ useComposerReasoning({ conversation, index: 0, enabled: true, branchReasoning: high }),+ {+ initialProps: {+ conversation: { ...base, reasoning_effort: ReasoningEffort.medium } as TConversation,+ },+ wrapper,+ },+ );+ await waitFor(() => expect(rendered.result.current?.value).toEqual(high));++ rendered.rerender({ conversation: base });++ const reset = {+ key: 'reasoning_effort',+ value: rendered.result.current?.setting.default,+ };+ await waitFor(() =>+ expect(+ reasoningStore.get(+ pendingReasoningOverrideFamily(getReasoningStateKey('reset-conversation', 0)),+ ),+ ).toEqual(reset),+ );+ expect(rendered.result.current?.value).toEqual(reset);+ });++ it('lets a Parameters edit replace the branch level, but not a conversation switch', async () => {+ const reasoningStore = createStore();+ const wrapper = ({ children }: { children: ReactNode }) => (+ <RecoilRoot>+ <JotaiProvider store={reasoningStore}>{children}</JotaiProvider>+ </RecoilRoot>+ );+ const high = { key: 'reasoning_effort', value: ReasoningEffort.high } as TReasoningOverride;+ const rendered = renderHook(+ ({ conversation }: { conversation: TConversation }) =>+ useComposerReasoning({ conversation, index: 0, enabled: true, branchReasoning: high }),+ {+ initialProps: {+ conversation: {+ conversationId: 'edited-conversation',+ endpoint: 'openAI',+ model: 'gpt-5',+ } as TConversation,+ },+ wrapper,+ },+ );+ await waitFor(() => expect(rendered.result.current?.value).toEqual(high));++ rendered.rerender({+ conversation: {+ conversationId: 'other-conversation',+ endpoint: 'openAI',+ model: 'gpt-5',+ reasoning_effort: ReasoningEffort.low,+ } as TConversation,+ });+ expect(rendered.result.current?.value).toEqual(high);++ rendered.rerender({+ conversation: {+ conversationId: 'other-conversation',+ endpoint: 'openAI',+ model: 'gpt-5',+ reasoning_effort: ReasoningEffort.medium,+ } as TConversation,+ });+ await waitFor(() =>+ expect(rendered.result.current?.value).toEqual({+ key: 'reasoning_effort',+ value: ReasoningEffort.medium,+ }),+ );+ expect(+ reasoningStore.get(+ pendingReasoningOverrideFamily(getReasoningStateKey('other-conversation', 0)),+ ),+ ).toEqual({ key: 'reasoning_effort', value: ReasoningEffort.medium });+ });++ it('does not show an inherited level while thinking is switched off', async () => {+ const wrapper = ({ children }: { children: ReactNode }) => (+ <RecoilRoot>+ <JotaiProvider store={createStore()}>{children}</JotaiProvider>+ </RecoilRoot>+ );+ const rendered = renderHook(+ () =>+ useComposerReasoning({+ conversation: {+ conversationId: 'thinking-off',+ endpoint: 'anthropic',+ model: 'claude-sonnet-4-6',+ thinking: false,+ } as TConversation,+ index: 0,+ enabled: true,+ branchReasoning: { key: 'effort', value: 'high' } as TReasoningOverride,+ }),+ { wrapper },+ );++ await waitFor(() => expect(rendered.result.current?.setting.key).toBe('effort'));+ expect(rendered.result.current?.value?.value).not.toBe('high');+ });++ it('keeps a Parameters effort edit a parameter while thinking is switched off', async () => {+ const reasoningStore = createStore();+ const wrapper = ({ children }: { children: ReactNode }) => (+ <RecoilRoot>+ <JotaiProvider store={reasoningStore}>{children}</JotaiProvider>+ </RecoilRoot>+ );+ const base = {+ conversationId: 'thinking-off-edit',+ endpoint: 'anthropic',+ model: 'claude-sonnet-4-6',+ thinking: false,+ } as TConversation;+ const rendered = renderHook(+ ({ conversation }: { conversation: TConversation }) =>+ useComposerReasoning({ conversation, index: 0, enabled: true }),+ { initialProps: { conversation: { ...base, effort: 'low' } as TConversation }, wrapper },+ );+ await waitFor(() => expect(rendered.result.current?.setting.key).toBe('effort'));++ rendered.rerender({ conversation: { ...base, effort: 'high' } as TConversation });++ await waitFor(() => expect(rendered.result.current?.value?.value).toBe('high'));+ expect(+ reasoningStore.get(+ pendingReasoningOverrideFamily(getReasoningStateKey('thinking-off-edit', 0)),+ ),+ ).toBeUndefined();+ });++ it('withdraws a staged level when thinking is switched off, but keeps one picked after', async () => {+ const reasoningStore = createStore();+ const wrapper = ({ children }: { children: ReactNode }) => (+ <RecoilRoot>+ <JotaiProvider store={reasoningStore}>{children}</JotaiProvider>+ </RecoilRoot>+ );+ const base = {+ conversationId: 'thinking-switch',+ endpoint: 'anthropic',+ model: 'claude-sonnet-4-6',+ } as TConversation;+ const key = getReasoningStateKey('thinking-switch', 0);+ const high = { key: 'effort', value: 'high' } as TReasoningOverride;+ const rendered = renderHook(+ ({ conversation }: { conversation: TConversation }) =>+ useComposerReasoning({ conversation, index: 0, enabled: true }),+ { initialProps: { conversation: { ...base, thinking: true } as TConversation }, wrapper },+ );+ await waitFor(() => expect(rendered.result.current?.setting.key).toBe('effort'));+ act(() => {+ rendered.result.current?.setValue(high);+ });++ rendered.rerender({ conversation: { ...base, thinking: false } as TConversation });+ await waitFor(() =>+ expect(reasoningStore.get(pendingReasoningOverrideFamily(key))).toBeUndefined(),+ );++ act(() => {+ rendered.result.current?.setValue(high);+ });+ rendered.rerender({ conversation: { ...base, thinking: false } as TConversation });+ expect(reasoningStore.get(pendingReasoningOverrideFamily(key))).toEqual(high);+ });++ it('does not withdraw a level when moving to a conversation with thinking off', async () => {+ const reasoningStore = createStore();+ const wrapper = ({ children }: { children: ReactNode }) => (+ <RecoilRoot>+ <JotaiProvider store={reasoningStore}>{children}</JotaiProvider>+ </RecoilRoot>+ );+ const high = { key: 'effort', value: 'high' } as TReasoningOverride;+ const otherKey = getReasoningStateKey('thinking-off-other', 0);+ reasoningStore.set(pendingReasoningOverrideFamily(otherKey), high);+ const model = { endpoint: 'anthropic', model: 'claude-sonnet-4-6' };+ const rendered = renderHook(+ ({ conversation }: { conversation: TConversation }) =>+ useComposerReasoning({ conversation, index: 0, enabled: true }),+ {+ initialProps: {+ conversation: {+ conversationId: 'thinking-on',+ thinking: true,+ ...model,+ } as TConversation,+ },+ wrapper,+ },+ );+ await waitFor(() => expect(rendered.result.current?.setting.key).toBe('effort'));++ rendered.rerender({+ conversation: {+ conversationId: 'thinking-off-other',+ thinking: false,+ ...model,+ } as TConversation,+ });++ await waitFor(() => expect(rendered.result.current?.value).toEqual(high));+ expect(reasoningStore.get(pendingReasoningOverrideFamily(otherKey))).toEqual(high);+ });++ it('does not show a branch level the current model does not take', async () => {+ const wrapper = ({ children }: { children: ReactNode }) => (+ <RecoilRoot>+ <JotaiProvider store={createStore()}>{children}</JotaiProvider>+ </RecoilRoot>+ );+ const rendered = renderHook(+ () =>+ useComposerReasoning({+ conversation: {+ conversationId: 'branch-conversation',+ endpoint: 'openAI',+ model: 'gpt-5',+ } as TConversation,+ index: 0,+ enabled: true,+ branchReasoning: { key: 'thinkingBudget', value: 4096 } as TReasoningOverride,+ }),+ { wrapper },+ );++ await waitFor(() => expect(rendered.result.current?.setting.key).toBe('reasoning_effort'));+ expect(rendered.result.current?.value?.key).toBe('reasoning_effort');+ expect(rendered.result.current?.value?.value).not.toBe(4096);+ });+it('resolves the control for an ephemeral agent from its encoded target', async () => {const wrapper = ({ children }: { children: ReactNode }) => (<RecoilRoot>@@ -847,6 +1146,43 @@ describe('useComposerReasoning: OpenRouter per-model efforts', () => {};});+ it('keeps the branch level when the capabilities reload, not mistaking it for an edit', async () => {+ const high = { key: 'reasoning_effort', value: ReasoningEffort.high } as TReasoningOverride;+ mockCapabilities = { OpenRouter: { [model]: { efforts: ['low', 'high'] } } };+ const store = createStore();+ const storeWrapper = ({ children }: { children: ReactNode }) => (+ <RecoilRoot>+ <JotaiProvider store={store}>{children}</JotaiProvider>+ </RecoilRoot>+ );+ const configured = { ...conversation, reasoning_effort: ReasoningEffort.low } as TConversation;+ const rendered = renderHook(+ () =>+ useComposerReasoning({+ conversation: configured,+ index: 0,+ enabled: true,+ branchReasoning: high,+ }),+ { wrapper: storeWrapper },+ );+ await waitFor(() => expect(rendered.result.current?.value).toEqual(high));++ mockCapabilities = undefined;+ mockCapabilitiesLoading = true;+ rendered.rerender();+ expect(rendered.result.current).toBeNull();++ mockCapabilities = { OpenRouter: { [model]: { efforts: ['low', 'high'] } } };+ mockCapabilitiesLoading = false;+ rendered.rerender();++ await waitFor(() => expect(rendered.result.current?.value).toEqual(high));+ expect(+ store.get(pendingReasoningOverrideFamily(getReasoningStateKey('openrouter-conversation', 0))),+ ).toBeUndefined();+ });+it('offers no control while the capabilities are still loading', () => {mockCapabilitiesLoading = true;diff --git a/client/src/hooks/useKeyboardShortcuts.spec.tsx b/client/src/hooks/useKeyboardShortcuts.spec.tsxindex ce65fa7d6a..7a87e30a71 100644--- a/client/src/hooks/useKeyboardShortcuts.spec.tsx+++ b/client/src/hooks/useKeyboardShortcuts.spec.tsx@@ -49,6 +49,8 @@ jest.mock('~/data-provider/Endpoints/queries', () => ({jest.mock('~/Providers', () => ({useChatContext: () => ({conversation: { conversationId: 'test-convo', endpoint: 'openAI', model: 'gpt-4o' },+ latestMessageId: undefined,+ getMessages: () => [],}),}));@@ -729,7 +731,7 @@ describe('stop generating shortcut', () => {const second = appendComposerForm();first.form.dataset.chatPane = '0';second.form.dataset.chatPane = '1';- fireEvent.click(screen.getByRole('button', { name: /Reasoning for next message/ }));+ fireEvent.click(screen.getByRole('button', { name: /^Thinking / }));for (const role of ['spinbutton', 'slider']) {const control = screen.getByRole(role);diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex dd77058f32..dbad0de562 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -1341,7 +1341,6 @@"com_ui_authentication": "Authentication","com_ui_authentication_type": "Authentication Type","com_ui_auto": "Auto",- "com_ui_reasoning_for_next_message": "Reasoning for next message","com_ui_reasoning_encrypted": "Reasoning (encrypted)","com_ui_reasoning_encrypted_description": "The model returned its reasoning encrypted, so it cannot be shown","com_ui_available_options": "Available options",diff --git a/e2e/specs/mock/scenarios/composer-buttons.spec.ts b/e2e/specs/mock/scenarios/composer-buttons.spec.tsindex 72deed4d9d..a39025e7af 100644--- a/e2e/specs/mock/scenarios/composer-buttons.spec.ts+++ b/e2e/specs/mock/scenarios/composer-buttons.spec.ts@@ -211,7 +211,7 @@ test.describe('composer controls on the shared Button', () => {/** The popover is modal, so Radix hides its trigger from the accessibility tree while open. */const reasoning = page.getByRole('button', {- name: /Reasoning for next message/i,+ name: /^Thinking /i,includeHidden: true,});await expect(reasoning).toBeVisible();diff --git a/e2e/specs/mock/scenarios/composer-context.spec.ts b/e2e/specs/mock/scenarios/composer-context.spec.tsindex 241618484e..1dd49bb73d 100644--- a/e2e/specs/mock/scenarios/composer-context.spec.ts+++ b/e2e/specs/mock/scenarios/composer-context.spec.ts@@ -142,53 +142,4 @@ test.describe('composer context', () => {await cleanupConversation(page);}});-- test('thinking selection applies to one turn and then resolves back to default @scenario:per-turn-thinking-level-applies-to-the-next-turn-only', async ({- page,- }) => {- test.setTimeout(120000);- try {- await page.goto(NEW_CHAT_PATH, { timeout: 10000 });- // Mock Provider A resolves the custom endpoint to Anthropic's adaptive- // `effort` setting, so the composer renders the compact effort slider.- await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);-- const thinkingButton = page.getByRole('button', { name: /^Thinking: / });- await expect(thinkingButton).toBeVisible();- const resolvedDefaultLabel = await thinkingButton.getAttribute('aria-label');- expect(resolvedDefaultLabel).toBeTruthy();-- await thinkingButton.click();- const thinkingDialog = page.getByRole('dialog', { name: /^Thinking: / });- await expect(thinkingDialog).toBeVisible();- const thinkingMax = thinkingDialog.getByRole('radio', { name: 'Max', exact: true });- await thinkingMax.click();- await expect(thinkingButton).not.toHaveAttribute('aria-label', resolvedDefaultLabel!);- await page.keyboard.press('Escape');-- const firstRequestPromise = page.waitForRequest(- (request) => request.url().includes('/api/agents/chat') && request.method() === 'POST',- );- await sendMessageAndWaitForCompletion(page, 'E2E first scoped thinking turn');- const firstBody = (await firstRequestPromise).postDataJSON() as {- reasoningOverride?: { key?: string; value?: string };- };- expect(firstBody.reasoningOverride).toEqual(- expect.objectContaining({ key: 'effort', value: 'max' }),- );- await expect(thinkingButton).toHaveAttribute('aria-label', resolvedDefaultLabel!);-- const secondRequestPromise = page.waitForRequest(- (request) => request.url().includes('/api/agents/chat') && request.method() === 'POST',- );- await sendMessageAndWaitForCompletion(page, 'E2E second default thinking turn');- const secondBody = (await secondRequestPromise).postDataJSON() as {- reasoningOverride?: unknown;- };- expect(secondBody.reasoningOverride).toBeUndefined();- await expect(thinkingButton).toHaveAttribute('aria-label', resolvedDefaultLabel!);- } finally {- await cleanupConversation(page);- }- });});diff --git a/e2e/specs/mock/scenarios/composer-numeric-reasoning.spec.ts b/e2e/specs/mock/scenarios/composer-numeric-reasoning.spec.tsindex f39dd8470c..dcf6337890 100644--- a/e2e/specs/mock/scenarios/composer-numeric-reasoning.spec.ts+++ b/e2e/specs/mock/scenarios/composer-numeric-reasoning.spec.ts@@ -36,7 +36,7 @@ test('Inspecting numeric reasoning preserves Auto and steering @scenario:inspectawait input.fill('Keep steering after inspecting Auto');const send = page.getByTestId('during-run-send-button');await expect(send).toHaveAttribute('data-during-run-action', 'steer');- const reasoning = page.getByRole('button', { name: /Reasoning for next message.*Auto/i });+ const reasoning = page.getByRole('button', { name: /^Thinking .*Auto/i });await reasoning.click();const budget = page.getByRole('spinbutton');await expect(budget).toHaveValue('');diff --git a/e2e/specs/mock/scenarios/composer-thinking-level.spec.ts b/e2e/specs/mock/scenarios/composer-thinking-level.spec.tsnew file mode 100644index 0000000000..851867362b--- /dev/null+++ b/e2e/specs/mock/scenarios/composer-thinking-level.spec.ts@@ -0,0 +1,114 @@+import { expect, test } from '@playwright/test';+import type { Page, Request } from '@playwright/test';+import type { TMessage } from 'librechat-data-provider';+import {+ fetchJson,+ MOCK_ENDPOINTS,+ NEW_CHAT_PATH,+ getAccessToken,+ selectMockEndpoint,+ sendMessageAndWaitForCompletion,+} from '../helpers';++/* Mock Provider A advertises Anthropic's `effort` enum: Auto, then Low through Max. */+const trigger = (page: Page) => page.getByTestId('composer-thinking-button');+const popover = (page: Page) => page.getByRole('dialog', { name: /^Thinking: / });++async function openNewChat(page: Page) {+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);+ await expect(trigger(page)).toHaveAccessibleName('Thinking: Auto');+}++async function pick(page: Page, level: string) {+ await trigger(page).click();+ await popover(page).getByRole('radio', { name: level, exact: true }).click();+ await expect(trigger(page)).toHaveAccessibleName(`Thinking: ${level}`);+ await page.keyboard.press('Escape');+ await expect(popover(page)).toBeHidden();+ /* Focus returns to the trigger, whose tooltip sits over the message field on a phone. */+ await page.keyboard.press('Escape');+ await expect(page.getByRole('tooltip')).toBeHidden();+}++/** Sends a turn and returns the reasoning override its request carried. */+async function send(page: Page, text: string) {+ const [request] = await Promise.all([+ page.waitForRequest(+ (req: Request) => req.method() === 'POST' && req.url().includes('/api/agents/chat'),+ { timeout: 30000 },+ ),+ sendMessageAndWaitForCompletion(page, `${text}-${Date.now()}`),+ ]);+ return (request.postDataJSON() as { reasoningOverride?: unknown }).reasoningOverride;+}++/** The level the server recorded on each user turn, oldest first. */+async function savedLevels(page: Page) {+ const conversationId = new URL(page.url()).pathname.split('/c/')[1];+ const messages = await fetchJson<TMessage[]>(+ page,+ `/api/messages/${encodeURIComponent(conversationId)}`,+ await getAccessToken(page),+ );+ return messages+ .filter((message) => message.isCreatedByUser === true)+ .sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)))+ .map((message) => message.reasoningOverride?.value ?? null);+}++test.describe('composer thinking level', () => {+ test('Thinking level holds for the rest of the conversation @scenario:thinking-level-holds-for-the-conversation', async ({+ page,+ }) => {+ await openNewChat(page);+ await pick(page, 'Medium');++ expect(await send(page, 'first')).toEqual({ key: 'effort', value: 'medium' });+ await expect(trigger(page)).toHaveAccessibleName('Thinking: Medium');++ /* Nothing new picked: the server runs and records the branch's level. */+ expect(await send(page, 'second')).toBeUndefined();+ await expect(trigger(page)).toHaveAccessibleName('Thinking: Medium');+ expect(await savedLevels(page)).toEqual(['medium', 'medium']);+ });++ test('Thinking level survives a reload of the conversation @scenario:thinking-level-survives-reload', async ({+ page,+ }) => {+ await openNewChat(page);+ await pick(page, 'High');+ expect(await send(page, 'before-reload')).toEqual({ key: 'effort', value: 'high' });+ await expect(page).toHaveURL(/\/c\/(?!new)/);++ await page.reload();+ await expect(trigger(page)).toHaveAccessibleName('Thinking: High');+ await send(page, 'after-reload');+ expect(await savedLevels(page)).toEqual(['high', 'high']);+ });++ test('Picking another level replaces it for later messages @scenario:thinking-level-changes-with-a-new-pick', async ({+ page,+ }) => {+ await openNewChat(page);+ await pick(page, 'Medium');+ expect(await send(page, 'medium')).toEqual({ key: 'effort', value: 'medium' });++ await pick(page, 'Low');+ expect(await send(page, 'low')).toEqual({ key: 'effort', value: 'low' });+ await expect(trigger(page)).toHaveAccessibleName('Thinking: Low');+ await send(page, 'still-low');+ expect(await savedLevels(page)).toEqual(['medium', 'low', 'low']);+ });++ test('Thinking popover opens on the Auto toggle in Auto @scenario:thinking-popover-focuses-auto-toggle', async ({+ page,+ }) => {+ await openNewChat(page);+ await trigger(page).click();++ const autoToggle = popover(page).getByRole('button', { name: 'Auto' });+ await expect(autoToggle).toHaveAttribute('aria-pressed', 'true');+ await expect(autoToggle).toBeFocused();+ });+});diff --git a/packages/api/src/modelSpecs/reasoningOverride.spec.ts b/packages/api/src/modelSpecs/reasoningOverride.spec.tsindex afc2b2e56e..4a00f7d75d 100644--- a/packages/api/src/modelSpecs/reasoningOverride.spec.ts+++ b/packages/api/src/modelSpecs/reasoningOverride.spec.ts@@ -295,6 +295,128 @@ describe('resolveReasoningOverride', () => {});});+describe('applyRequestReasoningOverride branch inheritance', () => {+ const { endpointOption, ...input } = baseInput;+ const { reasoningOverride: _picked, ...withoutPick } = input as typeof input & {+ reasoningOverride?: unknown;+ };+ const high = { key: 'reasoning_effort', value: ReasoningEffort.high };+ const request = (body: Record<string, unknown> = {}) => ({+ user: { id: 'user-1' },+ body: {+ conversationId: 'convo-1',+ parentMessageId: 'assistant-1',+ ...body,+ endpointOption: {+ ...endpointOption,+ model_parameters: { ...endpointOption.model_parameters },+ },+ } as Record<string, unknown> & { endpointOption: typeof endpointOption },+ });++ it('applies and records the level the branch last ran at when the turn picks none', async () => {+ const getBranchReasoningOverride = jest.fn().mockResolvedValue(high);+ const req = request();++ await expect(+ applyRequestReasoningOverride(req, { ...withoutPick, getBranchReasoningOverride }),+ ).resolves.toBe(true);++ expect(getBranchReasoningOverride).toHaveBeenCalledWith({+ user: 'user-1',+ conversationId: 'convo-1',+ parentMessageId: 'assistant-1',+ });+ expect(req.body.endpointOption.model_parameters).toMatchObject({ reasoning_effort: 'high' });+ expect(req.body.reasoningOverride).toEqual(high);+ });++ it('does not consult the branch when the turn picks a level', async () => {+ const getBranchReasoningOverride = jest.fn();+ const req = request();++ await applyRequestReasoningOverride(req, {+ ...withoutPick,+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.low },+ getBranchReasoningOverride,+ });++ expect(getBranchReasoningOverride).not.toHaveBeenCalled();+ expect(req.body.endpointOption.model_parameters).toMatchObject({ reasoning_effort: 'low' });+ });++ it('skips an inherited level the target no longer takes instead of refusing the turn', async () => {+ const getBranchReasoningOverride = jest.fn().mockResolvedValue(high);+ const req = request();+ const before = req.body.endpointOption;++ await expect(+ applyRequestReasoningOverride(req, {+ ...withoutPick,+ enforcedModelSpecFields: new Set(['reasoning_effort']),+ getBranchReasoningOverride,+ }),+ ).resolves.toBe(true);++ expect(req.body.endpointOption).toBe(before);+ expect(req.body).not.toHaveProperty('reasoningOverride');+ });++ it.each([+ ['a new conversation', { conversationId: 'new' }],+ ['a first turn', { parentMessageId: '00000000-0000-0000-0000-000000000000' }],+ ['an edit', { isEdited: true }],+ ['an edit from the browser', { editedContent: { index: 0, text: 'changed' } }],+ ['a regeneration', { isRegenerate: true }],+ ['a continuation', { isContinued: true }],+ ])('does not inherit for %s', async (_label, body) => {+ const getBranchReasoningOverride = jest.fn().mockResolvedValue(high);+ const req = request(body);++ await applyRequestReasoningOverride(req, { ...withoutPick, getBranchReasoningOverride });++ expect(getBranchReasoningOverride).not.toHaveBeenCalled();+ expect(req.body).not.toHaveProperty('reasoningOverride');+ });++ it.each([+ ['applies it while thinking is on', true],+ ['skips it while thinking is switched off', false],+ ])('for an inherited thinking budget, %s', async (_label, thinking) => {+ const model = 'gemini-2.5-pro';+ const getBranchReasoningOverride = jest+ .fn()+ .mockResolvedValue({ key: 'thinkingBudget', value: 32768 });+ const req = request();+ req.body.endpointOption = {+ model_parameters: { model, thinking },+ agent: Promise.resolve({ provider: EModelEndpoint.google, model }),+ };++ await expect(+ applyRequestReasoningOverride(req, {+ ...withoutPick,+ endpoint: EModelEndpoint.google,+ getBranchReasoningOverride,+ }),+ ).resolves.toBe(true);++ expect(req.body.endpointOption.model_parameters).toMatchObject(+ thinking ? { thinking: true, thinkingBudget: 32768 } : { thinking: false },+ );+ expect('reasoningOverride' in req.body).toBe(thinking);+ });++ it('does not inherit for a resumed turn, which replays its own parameters', async () => {+ const getBranchReasoningOverride = jest.fn().mockResolvedValue(high);+ const req = { ...request(), resumeReplayed: true };++ await applyRequestReasoningOverride(req, { ...withoutPick, getBranchReasoningOverride });++ expect(getBranchReasoningOverride).not.toHaveBeenCalled();+ });+});+describe('applyRequestReasoningOverride', () => {const { reasoningOverride, endpointOption, ...input } = baseInput;const request = () => ({diff --git a/packages/api/src/modelSpecs/reasoningOverride.ts b/packages/api/src/modelSpecs/reasoningOverride.tsindex 4781a5a2f5..46a6f2ad90 100644--- a/packages/api/src/modelSpecs/reasoningOverride.ts+++ b/packages/api/src/modelSpecs/reasoningOverride.ts@@ -1,4 +1,5 @@import {+ Constants,Providers,getModelReasoning,effectiveModelReasoning,@@ -15,6 +16,13 @@ import {import type { AgentContinuationAdmissionSource } from '~/agents/triggers/host';import type { ReasoningCapabilityResult } from '~/types';+/** Override keys whose level also turns thinking on. */+const THINKING_LEVEL_KEYS: ReadonlySet<string> = new Set([+ 'effort',+ 'thinkingLevel',+ 'thinkingBudget',+]);+export type ReasoningOverrideRequest =| { ok: true; reasoningOverride?: TReasoningOverride }| { ok: false; reason: 'invalid-reasoning-override' };@@ -151,10 +159,7 @@ export async function resolveReasoningOverride({return { ok: false, reason: 'invalid-reasoning-override' };}- const enablesThinking =- reasoningOverride.key === 'effort' ||- reasoningOverride.key === 'thinkingLevel' ||- reasoningOverride.key === 'thinkingBudget';+ const enablesThinking = THINKING_LEVEL_KEYS.has(reasoningOverride.key);const nextBase =existingBase?.key === reasoningOverride.key? existingBase@@ -228,8 +233,64 @@ export type RequestReasoningOverrideInput = Omit<loadReasoningCapabilities?: (endpoint: string) => Promise<ReasoningCapabilityResult>;/** The raw request field; validated here, so the caller passes it unparsed. */reasoningOverride?: unknown;+ /** Reads the level the branch a fresh turn extends last ran at, for a request that picks none. */+ getBranchReasoningOverride?: (params: {+ user: string;+ conversationId: string;+ parentMessageId: string;+ }) => Promise<unknown>;+};++type BranchReasoningRequest = {+ resumeReplayed?: boolean;+ user?: { id?: string };+ body: {+ conversationId?: unknown;+ parentMessageId?: unknown;+ isEdited?: unknown;+ editedContent?: unknown;+ isRegenerate?: unknown;+ isContinued?: unknown;+ };};+/**+ * The level a turn without its own pick inherits: the one the branch it extends last ran at, so a+ * composer choice holds for the rest of the conversation until the user picks another. Only a fresh+ * turn inherits: a resume replays its own parameters, and an edit, regeneration or continuation+ * replays a turn that already ran, with the override the client sends for it.+ */+async function loadBranchReasoningOverride(+ req: BranchReasoningRequest,+ getBranchReasoningOverride: RequestReasoningOverrideInput['getBranchReasoningOverride'],+): Promise<TReasoningOverride | undefined> {+ const { conversationId, parentMessageId, isEdited, editedContent, isRegenerate, isContinued } =+ req.body;+ if (+ getBranchReasoningOverride == null ||+ req.resumeReplayed === true ||+ isEdited === true ||+ editedContent != null ||+ isRegenerate === true ||+ isContinued === true ||+ req.user?.id == null ||+ typeof conversationId !== 'string' ||+ conversationId === '' ||+ conversationId === Constants.NEW_CONVO ||+ typeof parentMessageId !== 'string' ||+ parentMessageId === Constants.NO_PARENT+ ) {+ return undefined;+ }+ const stored = await getBranchReasoningOverride({+ user: req.user.id,+ conversationId,+ parentMessageId,+ });+ const parsed = reasoningOverrideSchema.safeParse(stored);+ return parsed.success ? parsed.data : undefined;+}+/*** Validates a request's reasoning override, applies it to the built endpoint* option and records the trusted base snapshot on the request. A request without@@ -248,13 +309,19 @@ export async function applyRequestReasoningOverride<T extends EndpointOption>(reasoningOverrideBase?: ReasoningOverrideBase;resumeReplayed?: boolean;_isAgentTrigger?: boolean;- body: {+ user?: { id?: string };+ body: BranchReasoningRequest['body'] & {endpointOption: T;reasoningOverride?: unknown;agentContinuationAdmission?: AgentContinuationAdmissionSource;};},- { reasoningOverride: raw, loadReasoningCapabilities, ...input }: RequestReasoningOverrideInput,+ {+ reasoningOverride: raw,+ loadReasoningCapabilities,+ getBranchReasoningOverride,+ ...input+ }: RequestReasoningOverrideInput,): Promise<boolean> {const stripReplayedOverride = (): boolean => {delete req.body.reasoningOverride;@@ -295,24 +362,46 @@ export async function applyRequestReasoningOverride<T extends EndpointOption>(if (!request.ok) {return replayed ? stripReplayedOverride() : false;}- if (request.reasoningOverride == null) {+ const inherited = request.reasoningOverride == null;+ const reasoningOverride =+ request.reasoningOverride ??+ (await loadBranchReasoningOverride(req, getBranchReasoningOverride));+ if (reasoningOverride == null) {+ return true;+ }+ /* Thinking switched off for the conversation wins over a level the turn only inherited: applying+ it would turn thinking back on behind the switch. A level picked for this turn still does. */+ if (+ inherited &&+ THINKING_LEVEL_KEYS.has(reasoningOverride.key) &&+ req.body.endpointOption.model_parameters?.thinking === false+ ) {return true;}const resolution = await resolveReasoningOverride({...input,reasoningCapabilities: await loadCapabilitiesFor(- request.reasoningOverride,+ reasoningOverride,req.body.endpointOption,input,loadReasoningCapabilities,),- reasoningOverride: request.reasoningOverride,+ reasoningOverride,endpointOption: req.body.endpointOption,reasoningOverrideBase: req.reasoningOverrideBase,});+ /* An inherited level the target no longer takes (a model switch, an enforced spec, an+ unknown catalog) is skipped rather than refused: the user asked for nothing this turn. */if (!resolution.ok) {+ if (inherited) {+ return true;+ }return replayed ? stripReplayedOverride() : false;}+ if (inherited) {+ /* Recorded on the turn like a pick, so the level keeps riding the branch. */+ req.body.reasoningOverride = reasoningOverride;+ }req.reasoningOverrideBase = resolution.reasoningOverrideBase;req.body.endpointOption = {...req.body.endpointOption,diff --git a/packages/data-schemas/src/methods/message.reasoning.spec.ts b/packages/data-schemas/src/methods/message.reasoning.spec.tsnew file mode 100644index 0000000000..2ff79e30b6--- /dev/null+++ b/packages/data-schemas/src/methods/message.reasoning.spec.ts@@ -0,0 +1,124 @@+import mongoose from 'mongoose';+import { MongoMemoryServer } from 'mongodb-memory-server';+import type { IMessage } from '~/types';+import { createMessageMethods } from './message';+import { createModels } from '~/models';++jest.mock('~/config/winston', () => ({+ error: jest.fn(),+ info: jest.fn(),+ warn: jest.fn(),+ debug: jest.fn(),+}));++let mongoServer: InstanceType<typeof MongoMemoryServer>;+let Message: mongoose.Model<IMessage>;+let getBranchReasoningOverride: ReturnType<+ typeof createMessageMethods+>['getBranchReasoningOverride'];++const user = 'user-1';+const conversationId = 'convo-1';+const high = { key: 'reasoning_effort', value: 'high' } as NonNullable<+ IMessage['reasoningOverride']+>;+const low = { key: 'reasoning_effort', value: 'low' } as NonNullable<IMessage['reasoningOverride']>;++const turn = (+ messageId: string,+ parentMessageId: string,+ isCreatedByUser: boolean,+ reasoningOverride?: IMessage['reasoningOverride'],+) => ({+ messageId,+ parentMessageId,+ conversationId,+ user,+ isCreatedByUser,+ text: messageId,+ ...(reasoningOverride != null && { reasoningOverride }),+});++beforeAll(async () => {+ mongoServer = await MongoMemoryServer.create();+ Object.assign(mongoose.models, createModels(mongoose));+ Message = mongoose.models.Message;+ getBranchReasoningOverride = createMessageMethods(mongoose).getBranchReasoningOverride;+ await mongoose.connect(mongoServer.getUri());+});++afterAll(async () => {+ await mongoose.disconnect();+ await mongoServer.stop();+});++beforeEach(async () => {+ await Message.deleteMany({});+});++describe('getBranchReasoningOverride', () => {+ it('returns the level of the nearest user message on the branch that carries one', async () => {+ await Message.insertMany([+ turn('u1', '00000000-0000-0000-0000-000000000000', true, high),+ turn('a1', 'u1', false),+ turn('u2', 'a1', true),+ turn('a2', 'u2', false),+ ]);++ await expect(+ getBranchReasoningOverride({ user, conversationId, parentMessageId: 'a2' }),+ ).resolves.toEqual(high);+ });++ it('follows the branch, not the newest message in the conversation', async () => {+ await Message.insertMany([+ turn('u1', '00000000-0000-0000-0000-000000000000', true, high),+ turn('a1', 'u1', false),+ turn('u2', 'a1', true, low),+ turn('a2', 'u2', false),+ turn('u2b', 'a1', true),+ turn('a2b', 'u2b', false),+ ]);++ await expect(+ getBranchReasoningOverride({ user, conversationId, parentMessageId: 'a2b' }),+ ).resolves.toEqual(high);+ });++ it('returns null when no user message on the branch carries a level', async () => {+ await Message.insertMany([+ turn('u1', '00000000-0000-0000-0000-000000000000', true),+ turn('a1', 'u1', false),+ ]);++ await expect(+ getBranchReasoningOverride({ user, conversationId, parentMessageId: 'a1' }),+ ).resolves.toBeNull();+ });++ it('answers with a single read of the conversation', async () => {+ await Message.insertMany([+ turn('u1', '00000000-0000-0000-0000-000000000000', true, high),+ turn('a1', 'u1', false),+ turn('u2', 'a1', true),+ turn('a2', 'u2', false),+ ]);+ const find = jest.spyOn(Message, 'find');++ await getBranchReasoningOverride({ user, conversationId, parentMessageId: 'a2' });++ expect(find).toHaveBeenCalledTimes(1);+ find.mockRestore();+ });++ it("does not read another user's messages", async () => {+ await Message.insertMany([+ { ...turn('u1', '00000000-0000-0000-0000-000000000000', true, high), user: 'user-2' },+ { ...turn('a1', 'u1', false), user: 'user-2' },+ ]);++ await expect(+ getBranchReasoningOverride({ user, conversationId, parentMessageId: 'a1' }),+ ).resolves.toBeNull();+ });+});diff --git a/packages/data-schemas/src/methods/message.ts b/packages/data-schemas/src/methods/message.tsindex cc6403e189..a4554a3b32 100644--- a/packages/data-schemas/src/methods/message.ts+++ b/packages/data-schemas/src/methods/message.ts@@ -943,6 +943,11 @@ export interface MessageMethods {limitPerThread: number;}): Promise<ParentSubagentTaskRecord[]>;getMessage(params: { user: string; messageId: string }): Promise<IMessage | null>;+ getBranchReasoningOverride(params: {+ user: string;+ conversationId: string;+ parentMessageId: string;+ }): Promise<IMessage['reasoningOverride'] | null>;getMessagesByCursor(filter: FilterQuery<IMessage>,options?: {@@ -4202,6 +4207,40 @@ export function createMessageMethods(}}+ /**+ * The reasoning level a branch runs at: the override on the nearest user message at or above+ * `parentMessageId` that carries one, or `null` when none does. One read of the conversation's+ * links and levels, projected to those fields; the walk itself is in memory.+ */+ async function getBranchReasoningOverride({+ user,+ conversationId,+ parentMessageId,+ }: {+ user: string;+ conversationId: string;+ parentMessageId: string;+ }): Promise<IMessage['reasoningOverride'] | null> {+ const Message = mongoose.models.Message as Model<IMessage>;+ const rows = await Message.find(+ { user, conversationId },+ { _id: 0, messageId: 1, parentMessageId: 1, isCreatedByUser: 1, reasoningOverride: 1 },+ ).lean<+ Pick<IMessage, 'messageId' | 'parentMessageId' | 'isCreatedByUser' | 'reasoningOverride'>[]+ >();+ const byId = new Map(rows.map((row) => [row.messageId, row]));+ const visited = new Set<string>();+ let current = byId.get(parentMessageId);+ while (current != null && !visited.has(current.messageId)) {+ visited.add(current.messageId);+ if (current.isCreatedByUser === true && current.reasoningOverride != null) {+ return current.reasoningOverride;+ }+ current = current.parentMessageId != null ? byId.get(current.parentMessageId) : undefined;+ }+ return null;+ }+/*** Retrieves a single message from the database.*/@@ -4445,6 +4484,7 @@ export function createMessageMethods(getMessagesForSubagentThreadView,listSubagentTasksForThreads,getMessage,+ getBranchReasoningOverride,getMessagesByCursor,searchMessages,deleteMessages,