From e0886e967711876d2d489dd4b3245c04f2a3d686 Mon Sep 17 00:00:00 2001 From: Totoro Date: Fri, 27 Nov 2026 08:46:08 +0800 Subject: [PATCH] fix(agents): preserve reasoning choices across model and chat switches (#8698) * fix(agents): preserve reasoning choices across model and chat switches Apply inherited thinking after selecting the model so a required-thinking profile can admit the run. Keep explicit disable requests subject to the profile policy. Read manual effort choices from the current thread for both the composer and the submitted request. * fix(frontend): clear stale chat effort on model fallback Validate a saved chat effort when the composer resolves its current model. Keep supported choices in the same chat and release an obsolete override even if another chat has already resolved the shared fallback. --------- Co-authored-by: Totoro-qaq <279883115+Totoro-qaq@users.noreply.github.com> --- .../deerflow/agents/lead_agent/agent.py | 12 +- .../tests/test_lead_agent_model_resolution.py | 27 ++++ docs/guide/subagents.md | 11 +- .../src/components/workspace/input-box.tsx | 28 +++- frontend/src/core/settings/store.ts | 30 +++- frontend/src/core/threads/hooks.ts | 2 +- .../tests/e2e/settings-model-sync.spec.ts | 141 ++++++++++-------- .../thread-model-selection.dom.test.ts | 53 ++++++- 8 files changed, 209 insertions(+), 95 deletions(-) diff --git a/backend/packages/harness/deerflow/agents/lead_agent/agent.py b/backend/packages/harness/deerflow/agents/lead_agent/agent.py index ec6af4308a..6e1ccd6d3e 100644 --- a/backend/packages/harness/deerflow/agents/lead_agent/agent.py +++ b/backend/packages/harness/deerflow/agents/lead_agent/agent.py @@ -1124,14 +1124,6 @@ def _assemble_lead_agent( # Custom agent model from agent config (if any), or None to let _resolve_model_name pick the default agent_model_name = agent_config.model if agent_config and agent_config.model else None - # thinking / reasoning precedence: explicit request > custom agent > mode preset > runtime - # default (issue #4336). See ``_resolve_runtime_option`` for the falsy-vs-unset - # handling. - agent_thinking = getattr(agent_config, "thinking_enabled", None) if agent_config else None - agent_reasoning = getattr(agent_config, "reasoning_effort", None) if agent_config else None - thinking_enabled = bool(_resolve_runtime_option(cfg, "thinking_enabled", agent_thinking, True)) - reasoning_effort = _resolve_runtime_option(cfg, "reasoning_effort", agent_reasoning, None) - # Per-agent sampling overrides (temperature / max_tokens) layered on top of # the resolved model profile (issue #4336). None when the agent set none. agent_model_settings = getattr(agent_config, "model_settings", None) if agent_config else None @@ -1164,6 +1156,10 @@ def _assemble_lead_agent( # unsupported model turns it off, and a restricted effort vocabulary maps # the generic value onto the provider's own. reasoning_contract = resolve_reasoning_contract(model_config) + # Only an explicit request to disable thinking should reach a required model's rejection policy. + inherited_thinking = True if reasoning_contract.thinking_required else getattr(agent_config, "thinking_enabled", None) + thinking_enabled = bool(_resolve_runtime_option(cfg, "thinking_enabled", inherited_thinking, True)) + reasoning_effort = _resolve_runtime_option(cfg, "reasoning_effort", getattr(agent_config, "reasoning_effort", None), None) resolved_reasoning = resolve_reasoning_request(reasoning_contract, thinking_enabled=thinking_enabled, reasoning_effort=reasoning_effort) if "thinking_unsupported" in resolved_reasoning.adjustments: logger.warning(f"Thinking mode is enabled but model '{model_name}' does not support it; fallback to non-thinking mode.") diff --git a/backend/tests/test_lead_agent_model_resolution.py b/backend/tests/test_lead_agent_model_resolution.py index 1b84b4e9e4..6a9ab80cce 100644 --- a/backend/tests/test_lead_agent_model_resolution.py +++ b/backend/tests/test_lead_agent_model_resolution.py @@ -1509,6 +1509,33 @@ def test_web_mode_defaults_cannot_downgrade_an_explicit_configurable_value(): assert lead_agent_module._resolve_runtime_option(lead_agent_module._get_runtime_config(config), "thinking_enabled", True, True) is False +def test_switching_to_required_thinking_only_rejects_explicit_off(model_control_assembly, monkeypatch): + from app.gateway.services import merge_run_context_overrides + from deerflow.models.reasoning import ReasoningPolicyError + + _, _, _, model_factory = model_control_assembly + optional = _make_model("optional", supports_thinking=True) + required = ModelConfig(name="required", model="required", use="langchain_openai:ChatOpenAI", reasoning={"thinking": "required", "on_disable_request": "reject"}) + app_config = _make_app_config([optional, required]) + agent = AgentConfig(name="dispatcher", model="optional", thinking_enabled=False) + monkeypatch.setattr(lead_agent_module, "load_agent_config", lambda *args, **kwargs: agent) + + def assemble(name, **reasoning): + config = {} + merge_run_context_overrides(config, {"agent_name": "dispatcher", "mode": "ultra", "subagent_enabled": True, "model_name": name, "model_selection_requested": name, **reasoning}) + lead_agent_module._make_lead_agent(config, app_config=app_config) + return config["metadata"]["thinking_enabled"] + + preset = {"thinking_enabled": True, "mode_default_fields": ["thinking_enabled"]} + assert assemble("optional", **preset) is False + assert assemble("required", **preset) is True + assert model_factory.call_args.kwargs["thinking_enabled"] is True + model_factory.reset_mock() + with pytest.raises(ReasoningPolicyError): + assemble("required", thinking_enabled=False) + model_factory.assert_not_called() + + def _make_agent_config(**kwargs): from deerflow.config.agents_config import AgentConfig diff --git a/docs/guide/subagents.md b/docs/guide/subagents.md index 4681a0be2f..3e23a3118f 100644 --- a/docs/guide/subagents.md +++ b/docs/guide/subagents.md @@ -181,10 +181,13 @@ are shown explicitly so they can be replaced with Inherit or a supported value. In web chats, an Agent's thinking and effort settings take precedence over the mode preset. A dispatch-only Agent can turn thinking off and still delegate in -Ultra. A separately selected effort takes precedence in the browser thread -where you picked it. Choosing a mode or model resets that choice. -Explicit API request values keep their usual precedence. The selected model's -reasoning capabilities still apply. +Ultra. If you switch to a model that requires thinking, it runs with thinking +enabled. A model configured with `on_disable_request: reject` still rejects +an explicit API request to disable it. An effort you pick in one chat stays +with that chat when you change the effort in another. Choosing a mode or +model in the same chat resets its effort choice. So does switching to a +fallback when its model disappears from the catalog. Explicit API settings +take precedence over Agent defaults. Custom Agents migrated to `agent_storage.backend: db` remain editable through Agent settings and `update_agent` while the importer retains their old files diff --git a/frontend/src/components/workspace/input-box.tsx b/frontend/src/components/workspace/input-box.tsx index f356dbabda..4f0e60a5b2 100644 --- a/frontend/src/components/workspace/input-box.tsx +++ b/frontend/src/components/workspace/input-box.tsx @@ -105,7 +105,11 @@ import { retireProjectAttachments, useStagedProjectAttachments, } from "@/core/projects/composer-attach"; -import { getThreadEffortOverride, subscribe } from "@/core/settings/store"; +import { + getThreadEffortOverride, + reconcileThreadEffort, + subscribe, +} from "@/core/settings/store"; import { buildReferenceMessageMetadata, type SidecarContext, @@ -746,6 +750,11 @@ export function InputBox({ uploadLimits, ]); + const threadEffort = useSyncExternalStore( + subscribe, + () => getThreadEffortOverride(threadId), + () => undefined, + ); useEffect(() => { if (models.length === 0) { return; @@ -758,6 +767,9 @@ export function InputBox({ ? models.find((m) => m.name === defaultModelName) : undefined; const fallbackModel = currentModel ?? agentDefaultModel ?? models[0]!; + if (threadEffort && typeof context.model_name === "string") { + reconcileThreadEffort(threadId, context.model_name, fallbackModel); + } const nextModelName = fallbackModel.name; const nextMode = getResolvedMode(context.mode, fallbackModel); // A remembered effort may not exist in this model's contract (issue #5073); @@ -784,7 +796,14 @@ export function InputBox({ }, { automatic: true }, ); - }, [context, models, defaultModelName, onContextChange]); + }, [ + context, + models, + defaultModelName, + onContextChange, + threadId, + threadEffort, + ]); const selectedModel = useMemo(() => { if (models.length === 0) { @@ -813,11 +832,6 @@ export function InputBox({ ); const supportReasoningEffort = reasoningEffortOptions.length > 0; - const threadEffort = useSyncExternalStore( - subscribe, - () => getThreadEffortOverride(threadId, context.reasoning_effort), - () => undefined, - ); const thinkingForRun = thinkingRequired || (supportThinking && diff --git a/frontend/src/core/settings/store.ts b/frontend/src/core/settings/store.ts index 594153f938..0a028df0ff 100644 --- a/frontend/src/core/settings/store.ts +++ b/frontend/src/core/settings/store.ts @@ -1,3 +1,6 @@ +import { getReasoningCapabilities } from "@/core/models/reasoning"; +import type { Model } from "@/core/models/types"; + import { DEFAULT_LOCAL_SETTINGS, LOCAL_SETTINGS_KEY, @@ -209,16 +212,14 @@ export function getThreadModelSnapshot(threadId: string): string | undefined { return threadModelNames.get(threadId); } -/** Remember which chat explicitly picked the current effort. The account still owns the value. */ export function getThreadEffortOverride( threadId?: string | null, - currentEffort?: string, ): string | undefined { - if (!threadId || !currentEffort) return undefined; - const selected = threadEfforts.has(threadId) + if (!threadId) return undefined; + const effort = threadEfforts.has(threadId) ? threadEfforts.get(threadId) : safeLocalStorage.getItem(THREAD_EFFORT_KEY_PREFIX + threadId); - return selected === currentEffort ? currentEffort : undefined; + return effort?.length ? effort : undefined; } function rememberThreadEffortChoice( @@ -234,6 +235,25 @@ function rememberThreadEffortChoice( else threadEfforts.set(threadId, effort); } +/** Another chat may have resolved the shared model before this one sees the catalog. */ +export function reconcileThreadEffort( + threadId: string, + previousModel: string | undefined, + model: Model, +) { + if (!previousModel) return; + const effort = getThreadEffortOverride(threadId); + if (!effort) return; + const options = getReasoningCapabilities(model).effort; + const supported = + options && + (options.values.includes(effort) || Object.hasOwn(options.aliases, effort)); + if (previousModel !== model.name || !supported) { + rememberThreadEffortChoice(threadId, undefined); + emitChange(); + } +} + export const updateLocalSettings: LocalSettingsSetter = (key, value) => { ensureBaseSettingsLoaded(); ensureStorageListenerRegistered(); diff --git a/frontend/src/core/threads/hooks.ts b/frontend/src/core/threads/hooks.ts index f25dc2974a..b32d764736 100644 --- a/frontend/src/core/threads/hooks.ts +++ b/frontend/src/core/threads/hooks.ts @@ -414,7 +414,7 @@ export function buildRunContext({ const explicitEffort = typeof extraContext?.reasoning_effort === "string" ? extraContext.reasoning_effort - : getThreadEffortOverride(threadId, settings.reasoning_effort); + : getThreadEffortOverride(threadId); // Older Gateways read the flat values. New ones can distinguish mode // presets from a separate choice, even when both say "high". const modeDefaultFields: string[] = []; diff --git a/frontend/tests/e2e/settings-model-sync.spec.ts b/frontend/tests/e2e/settings-model-sync.spec.ts index 13469ed35b..8f8c64ef5b 100644 --- a/frontend/tests/e2e/settings-model-sync.spec.ts +++ b/frontend/tests/e2e/settings-model-sync.spec.ts @@ -4,13 +4,16 @@ import { handleRunStream, mockLangGraphAPI, MOCK_THREAD_ID, + MOCK_THREAD_ID_2, } from "./utils/mock-api"; for (const agent of [false, true]) { for (const field of ["effort", "mode"] as const) { - test(`${agent ? "agent" : "normal"} thread ${field} selection preserves the account model`, async ({ - page, - }) => { + const removeModel = !agent && field === "effort"; + const name = removeModel + ? "catalog removal drops the old chat effort after another chat selects Medium" + : `${agent ? "agent" : "normal"} thread ${field} selection preserves the account model`; + test(name, async ({ page }) => { mockLangGraphAPI(page, { agents: [ { @@ -19,22 +22,20 @@ for (const agent of [false, true]) { reasoning_effort: "low", }, ], - threads: [ - { - thread_id: MOCK_THREAD_ID, - agent_name: agent ? "researcher" : undefined, - }, - ], + threads: [MOCK_THREAD_ID, MOCK_THREAD_ID_2].map((thread_id) => ({ + thread_id, + agent_name: agent ? "researcher" : undefined, + })), }); await page.addInitScript( ({ threadId }) => { - localStorage.setItem( - `deerflow.thread-model.${threadId}`, - "thread-model", - ); + const key = `deerflow.thread-model.${threadId}`; + if (localStorage.getItem(key) === null) + localStorage.setItem(key, "thread-model"); }, { threadId: MOCK_THREAD_ID }, ); + let threadModelAvailable = true; await page.route("**/api/models", (route) => route.fulfill({ json: { @@ -50,8 +51,20 @@ for (const agent of [false, true]) { display_name: "Thread Model", supports_thinking: true, supports_reasoning_effort: true, + reasoning: { + thinking: "optional", + source: "contract", + history: null, + effort: { + values: ["low", "medium", "high", "max"], + default: "medium", + aliases: {}, + }, + }, }, - ], + ].filter( + (model) => threadModelAvailable || model.name === "account-model", + ), }, }), ); @@ -88,18 +101,28 @@ for (const agent of [false, true]) { await route.fulfill({ json: server }); } }); - await page.goto( - `/workspace/${agent ? "agents/researcher/chats" : "chats"}/${MOCK_THREAD_ID}`, - ); - await page - .locator("[data-sidebar='sidebar']") - .getByRole("button", { name: /Settings and more/ }) - .click(); - await page.keyboard.press("Escape"); - await page.evaluate(() => - document.dispatchEvent(new Event("visibilitychange")), - ); - await expect.poll(() => reads).toBe(1); + const openChat = async (id: string) => { + const previousReads = reads; + await page.goto( + `/workspace/${agent ? "agents/researcher/chats" : "chats"}/${id}`, + ); + // Activate the mocked account and wait for its current preferences. + await page + .locator("[data-sidebar='sidebar']") + .getByRole("button", { name: /Settings and more/ }) + .click(); + await page.keyboard.press("Escape"); + await page.evaluate(() => + document.dispatchEvent(new Event("visibilitychange")), + ); + await expect.poll(() => reads).toBeGreaterThan(previousReads); + }; + const chooseEffort = async (label: RegExp) => { + await page.getByRole("button", { name: /^Reasoning Effort:/ }).click(); + await page.getByRole("menuitem").filter({ hasText: label }).click(); + await page.keyboard.press("Escape"); + }; + await openChat(MOCK_THREAD_ID); await expect( page.getByRole("button", { name: "Thread Model", exact: true }), ).toBeVisible(); @@ -110,13 +133,7 @@ for (const agent of [false, true]) { }), ).toBeVisible(); if (field === "effort") { - await page - .getByRole("button", { - name: agent ? "Reasoning Effort: Low" : "Reasoning Effort: Medium", - exact: true, - }) - .click(); - await page.getByRole("menuitem").filter({ hasText: /^High/ }).click(); + await chooseEffort(removeModel ? /^Max/ : /^High/); } else { await page.getByRole("button", { name: "Pro", exact: true }).click(); await page @@ -128,7 +145,7 @@ for (const agent of [false, true]) { .poll(() => patches) .toEqual([ field === "effort" - ? { reasoning_effort: "high" } + ? { reasoning_effort: removeModel ? "max" : "high" } : { mode: "ultra", reasoning_effort: "high" }, ]); expect(server.model_name).toBe("account-model"); @@ -136,19 +153,33 @@ for (const agent of [false, true]) { await expect( page.getByRole("button", { name: "Thread Model", exact: true }), ).toBeVisible(); - if (agent) { + if (agent || removeModel) { if (field === "mode") { // The account saved high for Ultra, but the agent's own default is low. - const effort = page.getByRole("button", { - name: "Reasoning Effort: Low", - }); - await effort.click(); - await page.getByRole("menuitem").filter({ hasText: /^High/ }).click(); - await page.keyboard.press("Escape"); - // A separate choice of high matters even when it equals Ultra's preset. + await chooseEffort(/^High/); + } + if (field === "mode" || removeModel) { + await openChat(MOCK_THREAD_ID_2); + await chooseEffort(/^Medium/); + await expect.poll(() => server.reasoning_effort).toBe("medium"); + await openChat(MOCK_THREAD_ID); + } + if (removeModel) { + await expect( + page.getByRole("button", { name: "Reasoning Effort: Max" }), + ).toBeVisible(); + threadModelAvailable = false; + await openChat(MOCK_THREAD_ID); + await expect( + page.getByRole("button", { name: "Account Model", exact: true }), + ).toBeVisible(); } await expect( - page.getByRole("button", { name: "Reasoning Effort: High" }), + page.getByRole("button", { + name: removeModel + ? "Reasoning Effort: Medium" + : "Reasoning Effort: High", + }), ).toBeVisible(); await page.route("**/api/langgraph/threads/*/runs/stream", (route) => handleRunStream(route), @@ -162,27 +193,13 @@ for (const agent of [false, true]) { .fill("Check this task"); await page.getByRole("button", { name: "Send", exact: true }).click(); expect((await submitted).postDataJSON().context).toMatchObject({ - reasoning_effort: "high", - mode_default_fields: ["thinking_enabled"], + model_name: removeModel ? "account-model" : "thread-model", + reasoning_effort: removeModel ? "medium" : "high", + mode_default_fields: removeModel + ? ["thinking_enabled", "reasoning_effort"] + : ["thinking_enabled"], subagent_enabled: field === "mode", }); - if (field === "mode") { - const beforeReload = reads; - await page.reload(); - // This auth-disabled fixture activates its mocked account on opening settings. - await page - .locator("[data-sidebar='sidebar']") - .getByRole("button", { name: /Settings and more/ }) - .click(); - await page.keyboard.press("Escape"); - await page.evaluate(() => - document.dispatchEvent(new Event("visibilitychange")), - ); - await expect.poll(() => reads).toBeGreaterThan(beforeReload); - await expect( - page.getByRole("button", { name: "Reasoning Effort: High" }), - ).toBeVisible(); - } } }); } diff --git a/frontend/tests/unit/core/settings/thread-model-selection.dom.test.ts b/frontend/tests/unit/core/settings/thread-model-selection.dom.test.ts index b18c36c1d2..b86062feb0 100644 --- a/frontend/tests/unit/core/settings/thread-model-selection.dom.test.ts +++ b/frontend/tests/unit/core/settings/thread-model-selection.dom.test.ts @@ -3,27 +3,64 @@ import { afterEach, expect, it, rs } from "@rstest/core"; import { safeLocalStorage } from "@/core/settings/local"; import { getBaseSettingsSnapshot, - getThreadEffortOverride, getThreadModelSnapshot, + reconcileThreadEffort, + resolveThreadContext, selectThreadModel, updateLocalSettings, updateThreadSettings, } from "@/core/settings/store"; +import { buildRunContext } from "@/core/threads/hooks"; afterEach(() => { rs.restoreAllMocks(); }); -it("marks a separate effort choice only for that chat and its current value", () => { - updateThreadSettings("agent-thread", "context", { reasoning_effort: "high" }); - expect(getThreadEffortOverride("agent-thread", "high")).toBe("high"); - expect(getThreadEffortOverride("agent-thread", "low")).toBeUndefined(); - expect(getThreadEffortOverride("another-thread", "high")).toBeUndefined(); - updateThreadSettings("agent-thread", "context", { +it("submits each chat's own effort after another chat edits the account preference", () => { + const submit = (threadId: string) => + buildRunContext({ threadId, settings: getBaseSettingsSnapshot().context }); + updateThreadSettings("chat-a", "context", { reasoning_effort: "high" }); + updateThreadSettings("chat-b", "context", { reasoning_effort: "medium" }); + expect(submit("chat-a")).toMatchObject({ + reasoning_effort: "high", + mode_default_fields: ["thinking_enabled"], + }); + expect(submit("chat-b")).toMatchObject({ + reasoning_effort: "medium", + mode_default_fields: ["thinking_enabled"], + }); + expect(submit("fresh-chat").mode_default_fields).toContain( + "reasoning_effort", + ); + updateThreadSettings("chat-a", "context", { mode: "ultra", reasoning_effort: "high", }); - expect(getThreadEffortOverride("agent-thread", "high")).toBeUndefined(); + expect(submit("chat-a").mode_default_fields).toContain("reasoning_effort"); + expect(submit("chat-b").reasoning_effort).toBe("medium"); +}); + +it("drops an unsupported effort even when another chat has already resolved the fallback model", () => { + updateLocalSettings("context", { model_name: "extended" }); + updateThreadSettings("old-chat", "context", { reasoning_effort: "max" }); + updateThreadSettings("other-chat", "context", { reasoning_effort: "medium" }); + resolveThreadContext("other-chat", { + model_name: "legacy", + reasoning_effort: "medium", + }); + const settings = getBaseSettingsSnapshot().context; + reconcileThreadEffort("old-chat", settings.model_name, { + name: "legacy", + model: "legacy", + id: "legacy", + display_name: "Legacy", + supports_reasoning_effort: true, + }); + expect(buildRunContext({ threadId: "old-chat", settings })).toMatchObject({ + model_name: "legacy", + reasoning_effort: "medium", + mode_default_fields: ["thinking_enabled", "reasoning_effort"], + }); }); it("does not claim to save a default when browser storage rejects the write", () => {