From 08694c63786531a9ba9a40ce4a9f2466b7382a37 Mon Sep 17 00:00:00 2001 From: Totoro Date: Thu, 26 Nov 2026 21:14:00 +0800 Subject: [PATCH] fix(agents): respect custom lead reasoning in web chat modes (#8690) Distinguish reasoning defaults supplied by the chat mode from explicit selections. Keep the configured lead reasoning and Ultra delegation independent while honoring a per-request override. Co-authored-by: Totoro-qaq <279883115+Totoro-qaq@users.noreply.github.com> --- backend/app/gateway/services.py | 15 +++++ .../deerflow/agents/lead_agent/agent.py | 14 ++-- .../tests/test_lead_agent_model_resolution.py | 28 ++++++++ docs/guide/subagents.md | 7 ++ .../[agent_name]/chats/[thread_id]/page.tsx | 1 + .../src/components/workspace/input-box.tsx | 28 +++++++- frontend/src/core/settings/store.ts | 45 ++++++++++++- frontend/src/core/threads/hooks.ts | 19 +++++- .../tests/e2e/settings-model-sync.spec.ts | 66 +++++++++++++++++-- frontend/tests/e2e/utils/mock-api.ts | 1 + .../thread-model-selection.dom.test.ts | 14 ++++ .../unit/core/threads/run-context.test.ts | 29 ++++++++ 12 files changed, 249 insertions(+), 18 deletions(-) diff --git a/backend/app/gateway/services.py b/backend/app/gateway/services.py index 2d7108ac87..ea286e156a 100644 --- a/backend/app/gateway/services.py +++ b/backend/app/gateway/services.py @@ -1200,6 +1200,7 @@ _CONTEXT_CONFIGURABLE_KEYS: frozenset[str] = frozenset( "model_name", "tool_approval_mode", "mode", + "mode_default_fields", "thinking_enabled", "reasoning_effort", "is_plan_mode", @@ -1354,6 +1355,12 @@ def merge_run_context_overrides(config: dict[str, Any], context: Mapping[str, An existing_runtime_context["locale"] = locale for section in (existing_configurable, existing_runtime_context): if isinstance(section, dict): + # A previous turn's mode preset only applies when this request sends it again. + previous_defaults = section.pop("mode_default_fields", None) + if isinstance(previous_defaults, list): + for field in ("thinking_enabled", "reasoning_effort"): + if field in previous_defaults: + section.pop(field, None) for key in _MODEL_SELECTION_CONTEXT_KEYS: section.pop(key, None) if isinstance(existing_runtime_context, dict) and "client" in existing_runtime_context: @@ -1368,6 +1375,14 @@ def merge_run_context_overrides(config: dict[str, Any], context: Mapping[str, An configurable = config.setdefault("configurable", {}) runtime_context = config.setdefault("context", {}) + if isinstance(mode_fields := context.get("mode_default_fields"), list): + context = dict(context) + defaults = [key for key in ("thinking_enabled", "reasoning_effort") if key in mode_fields and key in context] + for key in defaults: + # A preset cannot replace an explicit value supplied in body.config. + if any(isinstance(section, dict) and key in section for section in (configurable, runtime_context)): + context.pop(key) + context["mode_default_fields"] = [key for key in defaults if key in context] # UI language is public request data, never a checkpoint default. An # explicit invalid/null value clears a legacy config.context preference. if "locale" in context and isinstance(runtime_context, dict): diff --git a/backend/packages/harness/deerflow/agents/lead_agent/agent.py b/backend/packages/harness/deerflow/agents/lead_agent/agent.py index c7cad43a7a..ec6af4308a 100644 --- a/backend/packages/harness/deerflow/agents/lead_agent/agent.py +++ b/backend/packages/harness/deerflow/agents/lead_agent/agent.py @@ -168,14 +168,10 @@ def _subagent_release_policy( def _resolve_runtime_option(cfg: dict, key: str, agent_value, default): - """Resolve a runtime option with ``request > agent config > default`` precedence. - - ``key in cfg`` (not ``cfg.get(key)``) distinguishes "request omitted the - field" from "request set it to a falsy value", so a request-supplied - ``thinking_enabled: false`` is honored instead of falling through to the - agent default. ``agent_value`` is used only when it is not ``None`` (a - custom agent's unset field means "do not override" — issue #4336). - """ + """Resolve lead reasoning: explicit request, agent setting, mode preset, runtime default.""" + mode_fields = cfg.get("mode_default_fields") + if agent_value is not None and isinstance(mode_fields, list) and key in mode_fields: + return agent_value if key in cfg: return cfg[key] if agent_value is not None: @@ -1128,7 +1124,7 @@ 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: request > custom agent default > runtime + # 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 diff --git a/backend/tests/test_lead_agent_model_resolution.py b/backend/tests/test_lead_agent_model_resolution.py index 00c8455374..1b84b4e9e4 100644 --- a/backend/tests/test_lead_agent_model_resolution.py +++ b/backend/tests/test_lead_agent_model_resolution.py @@ -1481,6 +1481,34 @@ def test_resolve_runtime_option_precedence(): assert lead_agent_module._resolve_runtime_option({}, "thinking_enabled", None, False) is False +@pytest.mark.parametrize("explicit_effort", [False, True]) +def test_ultra_mode_defaults_respect_the_custom_lead(explicit_effort): + from app.gateway.services import merge_run_context_overrides + + config = {} + fields = ["thinking_enabled"] if explicit_effort else ["thinking_enabled", "reasoning_effort"] + merge_run_context_overrides(config, {"mode": "ultra", "mode_default_fields": fields, "thinking_enabled": True, "reasoning_effort": "high", "is_plan_mode": True, "subagent_enabled": True}) + cfg = lead_agent_module._get_runtime_config(config) + resolve = lead_agent_module._resolve_runtime_option + assert cfg["subagent_enabled"] is cfg["is_plan_mode"] is True + assert resolve(cfg, "thinking_enabled", False, True) is False + assert resolve(cfg, "reasoning_effort", "low", None) == ("high" if explicit_effort else "low") + assert resolve(cfg, "thinking_enabled", None, False) is True + assert resolve(cfg, "reasoning_effort", None, None) == "high" + merge_run_context_overrides(config, {"thinking_enabled": False, "reasoning_effort": "high"}) + explicit = lead_agent_module._get_runtime_config(config) + assert resolve(explicit, "thinking_enabled", True, True) is False + assert resolve(explicit, "reasoning_effort", "low", None) == "high" + + +def test_web_mode_defaults_cannot_downgrade_an_explicit_configurable_value(): + from app.gateway.services import merge_run_context_overrides + + config = {"configurable": {"thinking_enabled": False}} + merge_run_context_overrides(config, {"mode_default_fields": ["thinking_enabled"], "thinking_enabled": True}) + assert lead_agent_module._resolve_runtime_option(lead_agent_module._get_runtime_config(config), "thinking_enabled", True, True) is False + + 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 f864ac619a..4681a0be2f 100644 --- a/docs/guide/subagents.md +++ b/docs/guide/subagents.md @@ -179,6 +179,13 @@ Saving a model switch waits until the selected model is available; unrelated edits remain saveable without the catalog. Incompatible saved reasoning values 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. + Custom Agents migrated to `agent_storage.backend: db` remain editable through Agent settings and `update_agent` while the importer retains their old files for rollback. See [Agent Storage](../../backend/docs/CONFIGURATION.md#agent-storage) diff --git a/frontend/src/app/workspace/agents/[agent_name]/chats/[thread_id]/page.tsx b/frontend/src/app/workspace/agents/[agent_name]/chats/[thread_id]/page.tsx index 10f6992561..c70b8d560d 100644 --- a/frontend/src/app/workspace/agents/[agent_name]/chats/[thread_id]/page.tsx +++ b/frontend/src/app/workspace/agents/[agent_name]/chats/[thread_id]/page.tsx @@ -725,6 +725,7 @@ export default function AgentChatPage() { agentSkillNames={agent?.skills} agentSkillsLoading={agentSkillsLoading} defaultModelName={agent?.model} + agentReasoning={agent} knowledgeScopeControl={ selectorVisible && knowledgeScope ? ( | null; /** Optional knowledge-scope control rendered directly after mode. */ knowledgeScopeControl?: React.ReactNode; initialValue?: string; @@ -804,15 +809,32 @@ export function InputBox({ ); const supportReasoningEffort = reasoningEffortOptions.length > 0; + const threadEffort = useSyncExternalStore( + subscribe, + () => getThreadEffortOverride(threadId, context.reasoning_effort), + () => undefined, + ); + const thinkingForRun = + thinkingRequired || + (supportThinking && + (agentReasoning?.thinking_enabled ?? context.mode !== "flash")); const effectiveReasoningEffort = useMemo( () => resolveReasoningEffort( selectedModel, - context.reasoning_effort ?? + threadEffort ?? + agentReasoning?.reasoning_effort ?? + context.reasoning_effort ?? reasoningEffortForMode(context.mode ?? "pro", selectedModel), ), - [context.mode, context.reasoning_effort, selectedModel], + [ + threadEffort, + agentReasoning?.reasoning_effort, + context.mode, + context.reasoning_effort, + selectedModel, + ], ); const reasoningEffortLabel = useCallback( @@ -3409,7 +3431,7 @@ export function InputBox({ {knowledgeScopeControl} - {supportReasoningEffort && context.mode !== "flash" && ( + {supportReasoningEffort && thinkingForRun && ( ( const listeners = new Set(); const threadModelNames = new Map(); +const THREAD_EFFORT_KEY_PREFIX = "deerflow.thread-reasoning-effort."; +const threadEfforts = new Map(); let baseSettings: LocalSettings = DEFAULT_LOCAL_SETTINGS; let baseSettingsLoaded = false; @@ -157,6 +159,7 @@ function handleStorage(event: StorageEvent) { if (event.key === null) { baseSettings = readSharedSettings(); threadModelNames.clear(); + threadEfforts.clear(); emitChange(); return; } @@ -167,6 +170,11 @@ function handleStorage(event: StorageEvent) { return; } + if (event.key.startsWith(THREAD_EFFORT_KEY_PREFIX)) { + threadEfforts.delete(event.key.slice(THREAD_EFFORT_KEY_PREFIX.length)); + emitChange(); + return; + } if (!event.key.startsWith(THREAD_MODEL_KEY_PREFIX)) { return; } @@ -201,6 +209,31 @@ 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) + ? threadEfforts.get(threadId) + : safeLocalStorage.getItem(THREAD_EFFORT_KEY_PREFIX + threadId); + return selected === currentEffort ? currentEffort : undefined; +} + +function rememberThreadEffortChoice( + threadId: string, + effort: string | undefined, +) { + const key = THREAD_EFFORT_KEY_PREFIX + threadId; + const saved = + effort === undefined + ? safeLocalStorage.removeItem(key) + : safeLocalStorage.setItem(key, effort); + if (saved) threadEfforts.delete(threadId); + else threadEfforts.set(threadId, effort); +} + export const updateLocalSettings: LocalSettingsSetter = (key, value) => { ensureBaseSettingsLoaded(); ensureStorageListenerRegistered(); @@ -224,6 +257,7 @@ export function selectThreadModel(threadId: string, modelName: string) { ) { throw new Error("Unable to save the conversation model in this browser."); } + rememberThreadEffortChoice(threadId, undefined); threadModelNames.set(threadId, modelName); emitChange(); } @@ -232,11 +266,20 @@ export function updateThreadSettings( threadId: string, key: K, value: Partial, + automatic = false, ) { ensureBaseSettingsLoaded(); ensureStorageListenerRegistered(); const previous = baseSettings; + if (key === "context" && !automatic) { + const edit = value as Partial; + if ("mode" in edit || "model_name" in edit) { + rememberThreadEffortChoice(threadId, undefined); + } else if ("reasoning_effort" in edit) { + rememberThreadEffortChoice(threadId, edit.reasoning_effort); + } + } const nextBaseSettings = mergeSettingsSection(baseSettings, key, value); baseSettings = nextBaseSettings; persistLocalOnlySettings(); @@ -261,7 +304,7 @@ export function resolveThreadContext( context: Partial, ) { if (!preferenceEdit) { - updateThreadSettings(threadId, "context", context); + updateThreadSettings(threadId, "context", context, true); return; } baseSettings = mergeSettingsSection(baseSettings, "context", context); diff --git a/frontend/src/core/threads/hooks.ts b/frontend/src/core/threads/hooks.ts index d6db7d934e..1584566b5a 100644 --- a/frontend/src/core/threads/hooks.ts +++ b/frontend/src/core/threads/hooks.ts @@ -47,6 +47,7 @@ import { import type { FileInMessage } from "../messages/utils"; import { PROJECTS_QUERY_KEY } from "../projects/api"; import type { LocalSettings } from "../settings"; +import { getThreadEffortOverride } from "../settings/store"; import { isSidecarThread, SIDECAR_METADATA_KEY } from "../sidecar/thread"; import { useSubtaskContext, useUpdateSubtask } from "../tasks/context"; import { taskEventToSubtaskUpdate } from "../tasks/lifecycle"; @@ -406,6 +407,20 @@ export function buildRunContext({ ([key]) => key !== "conversation_references", ), ); + const explicitThinking = + typeof extraContext?.thinking_enabled === "boolean" + ? extraContext.thinking_enabled + : undefined; + const explicitEffort = + typeof extraContext?.reasoning_effort === "string" + ? extraContext.reasoning_effort + : getThreadEffortOverride(threadId, settings.reasoning_effort); + // Older Gateways read the flat values. New ones can distinguish mode + // presets from a separate choice, even when both say "high". + const modeDefaultFields: string[] = []; + if (explicitThinking === undefined) + modeDefaultFields.push("thinking_enabled"); + if (explicitEffort === undefined) modeDefaultFields.push("reasoning_effort"); return { ...extraContext, ...ownedSettings, @@ -415,10 +430,12 @@ export function buildRunContext({ ...(conversationReferences?.length ? { conversation_references: [...conversationReferences] } : {}), - thinking_enabled: settings.mode !== "flash", + mode_default_fields: modeDefaultFields, + thinking_enabled: explicitThinking ?? settings.mode !== "flash", is_plan_mode: settings.mode === "pro" || settings.mode === "ultra", subagent_enabled: settings.mode === "ultra", reasoning_effort: + explicitEffort ?? settings.reasoning_effort ?? (settings.mode === "ultra" ? "high" diff --git a/frontend/tests/e2e/settings-model-sync.spec.ts b/frontend/tests/e2e/settings-model-sync.spec.ts index 05a38cf834..13469ed35b 100644 --- a/frontend/tests/e2e/settings-model-sync.spec.ts +++ b/frontend/tests/e2e/settings-model-sync.spec.ts @@ -1,6 +1,10 @@ import { expect, test } from "@playwright/test"; -import { mockLangGraphAPI, MOCK_THREAD_ID } from "./utils/mock-api"; +import { + handleRunStream, + mockLangGraphAPI, + MOCK_THREAD_ID, +} from "./utils/mock-api"; for (const agent of [false, true]) { for (const field of ["effort", "mode"] as const) { @@ -8,7 +12,13 @@ for (const agent of [false, true]) { page, }) => { mockLangGraphAPI(page, { - agents: [{ name: "researcher", description: "Research agent" }], + agents: [ + { + name: "researcher", + description: "Research agent", + reasoning_effort: "low", + }, + ], threads: [ { thread_id: MOCK_THREAD_ID, @@ -95,14 +105,14 @@ for (const agent of [false, true]) { ).toBeVisible(); await expect( page.getByRole("button", { - name: "Reasoning Effort: Medium", + name: agent ? "Reasoning Effort: Low" : "Reasoning Effort: Medium", exact: true, }), ).toBeVisible(); if (field === "effort") { await page .getByRole("button", { - name: "Reasoning Effort: Medium", + name: agent ? "Reasoning Effort: Low" : "Reasoning Effort: Medium", exact: true, }) .click(); @@ -126,6 +136,54 @@ for (const agent of [false, true]) { await expect( page.getByRole("button", { name: "Thread Model", exact: true }), ).toBeVisible(); + if (agent) { + 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 expect( + page.getByRole("button", { name: "Reasoning Effort: High" }), + ).toBeVisible(); + await page.route("**/api/langgraph/threads/*/runs/stream", (route) => + handleRunStream(route), + ); + const submitted = page.waitForRequest( + (req) => + req.method() === "POST" && req.url().endsWith("/runs/stream"), + ); + await page + .getByPlaceholder(/how can i assist you/i) + .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"], + 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/e2e/utils/mock-api.ts b/frontend/tests/e2e/utils/mock-api.ts index 52515f8897..053ce292c4 100644 --- a/frontend/tests/e2e/utils/mock-api.ts +++ b/frontend/tests/e2e/utils/mock-api.ts @@ -122,6 +122,7 @@ export type MockAgent = { system_prompt?: string; tool_groups?: string[] | null; skills?: string[] | null; + reasoning_effort?: string | null; }; export type MockSkill = { 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 8b66f2cabf..b18c36c1d2 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,15 +3,29 @@ import { afterEach, expect, it, rs } from "@rstest/core"; import { safeLocalStorage } from "@/core/settings/local"; import { getBaseSettingsSnapshot, + getThreadEffortOverride, getThreadModelSnapshot, selectThreadModel, updateLocalSettings, + updateThreadSettings, } from "@/core/settings/store"; 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", { + mode: "ultra", + reasoning_effort: "high", + }); + expect(getThreadEffortOverride("agent-thread", "high")).toBeUndefined(); +}); + it("does not claim to save a default when browser storage rejects the write", () => { rs.spyOn(safeLocalStorage, "setItem").mockReturnValue(false); expect(() => selectThreadModel("blocked-write-thread", "model-B")).toThrow(); diff --git a/frontend/tests/unit/core/threads/run-context.test.ts b/frontend/tests/unit/core/threads/run-context.test.ts index c94387a353..75fc70cd4b 100644 --- a/frontend/tests/unit/core/threads/run-context.test.ts +++ b/frontend/tests/unit/core/threads/run-context.test.ts @@ -10,6 +10,35 @@ const settings = { } as unknown as LocalSettings["context"]; describe("buildRunContext", () => { + it("keeps Ultra delegation separate from its lead reasoning defaults", () => { + const input = { + settings: { + ...settings, + mode: "ultra" as const, + reasoning_effort: "high", + }, + threadId: "dispatch", + }; + expect(buildRunContext(input)).toMatchObject({ + thinking_enabled: true, + reasoning_effort: "high", + mode_default_fields: ["thinking_enabled", "reasoning_effort"], + is_plan_mode: true, + subagent_enabled: true, + }); + expect( + buildRunContext({ + ...input, + extraContext: { thinking_enabled: false, reasoning_effort: "high" }, + }), + ).toMatchObject({ + thinking_enabled: false, + reasoning_effort: "high", + mode_default_fields: [], + subagent_enabled: true, + }); + }); + it("uses the current UI locale instead of stale saved or caller context", () => { const stale = { ...settings, locale: "en-US" }; const context = buildRunContext({