Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

review(models): upstream mirror for model-scoped reasoning Off (#2111)

Call White5a6d0bbd7fa6
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index d0b3a433e..07fb82334 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -243,6 +243,10 @@ def project_opencode_public_model(
if model.supports_reasoning is not False
else {}
)
+ # Translate an explicitly declared Off variant, without inventing one or
+ # changing the existing payloads of ordinary/custom effort values.
+ if model.native_protocol == "anthropic" and "none" in variants:
+ variants["none"] = {"thinking": {"type": "disabled"}}
if variants:
projected["variants"] = variants
return projected
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index 2c250a664..bb6ddda83 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -466,6 +466,7 @@ class SessionHandler(BaseHandler):
session_key: str,
stored_claude_session_id: Optional[str],
current_model: Optional[str],
+ effective_effort: Optional[str],
agent_system_prompt: Optional[str],
model_hub_launch: "ModelHubLaunch",
) -> ClaudeSDKClient | None:
@@ -477,13 +478,18 @@ class SessionHandler(BaseHandler):
client,
):
return None
- if getattr(client, "_vibe_model_hub_fingerprint", "direct") != model_hub_launch.fingerprint:
- logger.info("Recreating cached Claude SDK client because Model Hub channel changed")
+ reasoning_changed = getattr(client, "_vibe_reasoning_effort", None) != effective_effort
+ if (
+ reasoning_changed
+ or getattr(client, "_vibe_model_hub_fingerprint", "direct") != model_hub_launch.fingerprint
+ ):
+ reason = "reasoning_effort_changed" if reasoning_changed else "model_hub_channel_changed"
+ logger.info("Recreating cached Claude SDK client: %s", reason)
await self._wait_for_claude_session_idle(composite_key)
await self._cleanup_session_locked(
composite_key,
retire_model_hub_scope=model_hub_launch.channel == "direct",
- reason="model_hub_channel_changed",
+ reason=reason,
)
return None
@@ -582,6 +588,7 @@ class SessionHandler(BaseHandler):
session_key: str,
native_session_id: Optional[str],
desired_model: Optional[str],
+ effective_effort: Optional[str],
effective_agent: str,
agent_system_prompt: Optional[str],
model_hub_launch: "ModelHubLaunch",
@@ -594,13 +601,18 @@ class SessionHandler(BaseHandler):
client,
):
return None
- if getattr(client, "_vibe_model_hub_fingerprint", "direct") != model_hub_launch.fingerprint:
- logger.info("Recreating cached Claude subagent SDK client because Model Hub channel changed")
+ reasoning_changed = getattr(client, "_vibe_reasoning_effort", None) != effective_effort
+ if (
+ reasoning_changed
+ or getattr(client, "_vibe_model_hub_fingerprint", "direct") != model_hub_launch.fingerprint
+ ):
+ reason = "reasoning_effort_changed" if reasoning_changed else "subagent_model_hub_channel_changed"
+ logger.info("Recreating cached Claude subagent SDK client: %s", reason)
await self._wait_for_claude_session_idle(composite_key)
await self._cleanup_session_locked(
composite_key,
retire_model_hub_scope=model_hub_launch.channel == "direct",
- reason="subagent_model_hub_channel_changed",
+ reason=reason,
)
return None
self.ensure_agent_session_id(
@@ -1328,6 +1340,18 @@ class SessionHandler(BaseHandler):
bind_launch(context, model_hub_launch)
runtime_model = model_hub_launch.runtime_model or launch_model
cached_subagent_model = self._cached_claude_subagent_model(explicit_model, model_hub_launch)
+ from modules.agents.opencode.utils import normalize_claude_reasoning_effort
+
+ # Reasoning is a process-creation option, unlike set_model. Resolve it
+ # once for both reuse and creation, including the in-flight create path.
+ catalog_efforts = (
+ model_hub_launch.reasoning_efforts
+ if model_hub_launch.channel in {"hub", "native_cli"}
+ else backend_model_catalog.catalog_reasoning_efforts_for_model("claude", launch_model)
+ )
+ effective_effort = normalize_claude_reasoning_effort(
+ launch_model, explicit_effort, catalog_efforts,
+ )
if not effective_agent:
# Claude SDK model changes are control requests; only send one when
@@ -1341,6 +1365,7 @@ class SessionHandler(BaseHandler):
session_key=session_key,
stored_claude_session_id=stored_claude_session_id,
current_model=current_model,
+ effective_effort=effective_effort,
agent_system_prompt=None,
model_hub_launch=model_hub_launch,
)
@@ -1362,6 +1387,7 @@ class SessionHandler(BaseHandler):
session_key=session_key,
native_session_id=cached_session_id,
desired_model=cached_subagent_model,
+ effective_effort=effective_effort,
effective_agent=effective_agent,
agent_system_prompt=agent_system_prompt,
model_hub_launch=model_hub_launch,
@@ -1388,6 +1414,7 @@ class SessionHandler(BaseHandler):
session_key=session_key,
native_session_id=stored_claude_session_id,
desired_model=cached_subagent_model,
+ effective_effort=effective_effort,
effective_agent=effective_agent,
agent_system_prompt=agent_system_prompt,
model_hub_launch=model_hub_launch,
@@ -1401,6 +1428,7 @@ class SessionHandler(BaseHandler):
session_key=session_key,
stored_claude_session_id=stored_claude_session_id,
current_model=runtime_model,
+ effective_effort=effective_effort,
agent_system_prompt=None,
model_hub_launch=model_hub_launch,
)
@@ -1418,7 +1446,7 @@ class SessionHandler(BaseHandler):
stored_claude_session_id=fork_source_claude_session_id or stored_claude_session_id,
effective_agent=effective_agent,
explicit_model=explicit_model,
- explicit_effort=explicit_effort,
+ effective_effort=effective_effort,
agent_system_prompt=agent_system_prompt,
fork_session=bool(fork_source_claude_session_id),
)
@@ -1447,7 +1475,7 @@ class SessionHandler(BaseHandler):
stored_claude_session_id: Optional[str],
effective_agent: Optional[str],
explicit_model: Optional[str],
- explicit_effort: Optional[str],
+ effective_effort: Optional[str],
agent_system_prompt: Optional[str],
fork_session: bool = False,
) -> ClaudeSDKClient:
@@ -1500,23 +1528,7 @@ class SessionHandler(BaseHandler):
if model_hub_launch is not None and model_hub_launch.backend == "claude"
else effective_model
)
- from modules.agents.opencode.utils import normalize_claude_reasoning_effort
-
- catalog_efforts = (
- model_hub_launch.reasoning_efforts
- if model_hub_launch is not None
- and model_hub_launch.backend == "claude"
- and model_hub_launch.channel in {"hub", "native_cli"}
- else backend_model_catalog.catalog_reasoning_efforts_for_model(
- "claude",
- effective_model,
- )
- )
- effective_effort = normalize_claude_reasoning_effort(
- effective_model,
- explicit_effort,
- catalog_efforts,
- )
+ from modules.agents.opencode.utils import NO_REASONING_EFFORT
# Determine final system prompt: agent prompt takes precedence over config.
# Always append avibe system prompt injection so transport
@@ -1608,7 +1620,11 @@ class SessionHandler(BaseHandler):
cli_path_override = self._get_claude_cli_path_override()
if cli_path_override:
option_kwargs["cli_path"] = cli_path_override
- if effective_effort:
+ if effective_effort == NO_REASONING_EFFORT:
+ # The exact model declaration admitted Off. Claude expresses that
+ # choice through the thinking switch, not an `effort="none"` tier.
+ option_kwargs["thinking"] = {"type": "disabled"}
+ elif effective_effort:
option_kwargs["effort"] = effective_effort
# Only set allowed_tools if agent file specifies tools.
# Omitting the field keeps SDK default tool behavior.
@@ -1627,7 +1643,9 @@ class SessionHandler(BaseHandler):
logger.info(f" Subagent: {effective_agent}")
if effective_model:
logger.info(f" Model: {effective_model}")
- if effective_effort:
+ if effective_effort == NO_REASONING_EFFORT:
+ logger.info(" Thinking: disabled")
+ elif effective_effort:
logger.info(f" Effort: {effective_effort}")
# Log if we're resuming a session
@@ -1651,6 +1669,7 @@ class SessionHandler(BaseHandler):
),
)
setattr(client, "_vibe_git_path_state", git_path_state)
+ setattr(client, "_vibe_reasoning_effort", effective_effort)
setattr(
client,
"_vibe_model_hub_fingerprint",
diff --git a/docs/plans/model-scoped-reasoning-off.md b/docs/plans/model-scoped-reasoning-off.md
new file mode 100644
index 000000000..27de49db6
--- /dev/null
+++ b/docs/plans/model-scoped-reasoning-off.md
@@ -0,0 +1,83 @@
+# Model-scoped reasoning Off
+
+Owner decision: 2026-09-21. Revises PR #2084's backend-wide Off proposal.
+
+## Contract
+
+- The existing backend model row's `reasoning_efforts` is the source of
+ selectable options. `none` means explicitly disabling extended thinking;
+ an absent effort still means no override. `medium` remains unchanged.
+- `none` belongs to the shared display vocabulary, not to protocol defaults,
+ backend fallbacks, or automatically populated capability lists. Recognizing
+ the value does not declare that a model supports it.
+- Users can opt an individual model into `none` through the existing model
+ editor. Merely opening or saving an existing row does not add the value.
+ Built-in model rows, stored metadata, provenance, and default selection stay
+ unchanged. No schema change or migration is needed.
+- Claude normalization uses the same exact model declaration as other efforts.
+ After selection, the Claude SDK translates `none` to
+ `thinking: {"type": "disabled"}` without an effort override.
+- OpenCode projects only declared variants. For Anthropic, a declared `none`
+ becomes `thinking: {"type": "disabled"}`; other declared values keep their
+ existing payloads. OpenAI-shaped variants keep `reasoningEffort: <value>`.
+- Codex keeps its existing model-catalog and transport behavior: this change
+ neither invents Off for native models nor prevents an explicitly configured
+ compatible model from advertising it.
+- Shared resolver intent forwarding, source discovery/provenance, routing,
+ retry, and proxy-engine policy are not changed. Model metadata controls the
+ selectable UI; it does not introduce a new gateway allowlist.
+- Unknown/custom effort strings still round-trip. Existing `supports_reasoning`
+ semantics and empty-versus-missing catalog behavior remain unchanged.
+- Existing Agent creation/model-switch default selection remains intact:
+ prefer an available `medium`, otherwise use the declared list's first option.
+ Adding the vocabulary entry never reorders that declared list.
+- Claude cache reuse compares the effective normalized reasoning choice as a
+ process-creation setting, for main sessions, subagents, and in-flight creates.
+ A changed choice waits for idle and rebuilds through the existing generation
+ lifecycle with the native resume ID; unchanged choices reuse the process.
+ Model-only control requests remain unchanged when effective reasoning matches.
+- Web channel, user, and thread route saves normalize against the same exact
+ backend model row as the picker, including an inherited Agent model. Native
+ mode keeps its native catalog. Empty declarations stay empty; another model's
+ `none` never grants support. Inherited model fields are not materialized.
+
+## Validation invariants
+
+- For all three backends, a model declaring `none` exposes it, while unrelated,
+ missing, empty, default-only, and ordinary tier lists never acquire it.
+- UI model editing persists Off only after an explicit selection, preserves
+ custom values, and does not change existing selections or default behavior.
+ English/Chinese pickers label the value as Off/关闭, not Default.
+- Claude SDK options distinguish absent, ordinary, custom, declared Off, and
+ undeclared Off requests on both native and Model Hub launch paths.
+- OpenCode native/custom-provider and Model Hub projections preserve all
+ existing ordinary-tier payloads, including custom model effort values, and
+ translate only an explicitly declared `none`.
+- Catalog serialization and existing routing/retry tests stay green. Tests use
+ isolated state and native-transport fakes; they do not prove live provider
+ support for an operator's custom model declaration.
+- Resolver tests include direct/nested `none` and disabled thinking, plus
+ provider fallback with mismatched/empty source capability metadata. Each
+ attempt preserves the caller's original payload, protocol, and headers.
+
+## Compatibility review scope decision
+
+The independent review of `5ec19f1ac` found two boundary omissions: cache
+identity did not include the selected process-level reasoning setting, and
+Web routing writes used only the generic Claude vocabulary. Both were
+reproduced with failing consumer tests before repair. Fix these two owners
+using the existing lifecycle and model catalog; do not change shared gateway
+fingerprints, provider policy, route selection, retry, or persisted schemas.
+
+## Known by design
+
+- No blanket Off backfill: support depends on the exact provider/model route.
+- No universal Off-to-medium fallback or re-enabling thinking on rejection.
+- No migration, deployment, release, host restart, or live-model invocation is
+ part of this implementation.
+- Live provider acceptance and the proxy engine's protocol translation policy
+ remain separate verification layers. The existing boundary documented in
+ `model-hub-reasoning-intent.md` is not changed by a model-menu option.
+- Exact-head automatic Codex review remains a delivery gate; a missing
+ external-fork review pickup must not be treated as a pass or manually
+ triggered contrary to the repository policy.
diff --git a/modules/agents/opencode/utils.py b/modules/agents/opencode/utils.py
index d7693b41b..ee094f2eb 100644
--- a/modules/agents/opencode/utils.py
+++ b/modules/agents/opencode/utils.py
@@ -17,6 +17,10 @@ _REASONING_FALLBACK_OPTIONS = [
_REASONING_VARIANT_ORDER = ["none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"]
+# Explicit Off is a model-declared option, distinct from an unset effort.
+# It remains truthy through the existing routing/default inheritance chain.
+NO_REASONING_EFFORT = "none"
+
_REASONING_VARIANT_LABELS = {
"none": "None",
"minimal": "Minimal",
diff --git a/tests/test_backend_model_catalog.py b/tests/test_backend_model_catalog.py
index cd29522c9..e21deeef2 100644
--- a/tests/test_backend_model_catalog.py
+++ b/tests/test_backend_model_catalog.py
@@ -50,6 +50,7 @@ def _persisted_remote_record(tmp_path: Path, url: str) -> dict:
def test_reasoning_effort_authorities_are_ordered_and_complete() -> None:
assert backend_model_catalog.REASONING_EFFORT_VOCABULARY == (
+ "none",
"minimal",
"low",
"medium",
@@ -64,7 +65,7 @@ def test_reasoning_effort_authorities_are_ordered_and_complete() -> None:
"anthropic": ("low", "medium", "high", "xhigh", "max"),
}
assert all(
- "ultra" not in efforts
+ not {"none", "ultra"}.intersection(efforts)
for efforts in backend_model_catalog.PROTOCOL_REASONING_EFFORT_DEFAULTS.values()
)
diff --git a/tests/test_claude_cli_path.py b/tests/test_claude_cli_path.py
index 2c19b9867..52fc0af10 100644
--- a/tests/test_claude_cli_path.py
+++ b/tests/test_claude_cli_path.py
@@ -184,9 +184,13 @@ def test_session_handler_passes_configured_claude_cli_path(monkeypatch, tmp_path
assert getattr(client, "_vibe_runtime_session_key") == f"slack_C123:{tmp_path}"
-def test_session_handler_uses_native_cli_launch_reasoning_catalog(
[email protected]("channel", ["hub", "native_cli"])
[email protected]("requested", [None, "none", "medium", "max", "custom-effort"])
+def test_session_handler_uses_exact_launch_reasoning_catalog(
monkeypatch,
tmp_path: Path,
+ channel: str,
+ requested: str | None,
) -> None:
from modules.agents.model_hub import ModelHubLaunch
@@ -203,14 +207,16 @@ def test_session_handler_uses_native_cli_launch_reasoning_catalog(
async def resolve(self, backend, requested_model, **_kwargs):
return ModelHubLaunch(
backend=backend,
- channel="native_cli",
+ channel=channel,
requested_model=requested_model,
target_model=requested_model,
runtime_model=requested_model,
source_id="src_native01",
+ gateway_base_url="http://127.0.0.1:9/fixture",
+ gateway_token="fixture-gateway-token",
context_window=128_000,
max_output_tokens=32_000,
- reasoning_efforts=("max",),
+ reasoning_efforts=("none", "medium", "max", "custom-effort"),
)
monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
@@ -224,17 +230,241 @@ def test_session_handler_uses_native_cli_launch_reasoning_catalog(
controller.model_hub_runtime = _Runtime()
controller.settings_manager.get_channel_routing = lambda _key: RoutingSettings(
model="claude-opus-4-6",
- reasoning_effort="max",
+ reasoning_effort=requested,
)
handler = SessionHandler(controller)
context = MessageContext(user_id="U123", channel_id="C123")
_run_session(handler, context)
- assert captured["options"].effort == "max"
+ if requested == "none":
+ assert captured["options"].thinking == {"type": "disabled"}
+ assert getattr(captured["options"], "effort", None) is None
+ else:
+ assert getattr(captured["options"], "thinking", None) is None
+ assert getattr(captured["options"], "effort", None) == requested
assert captured["options"].env["CLAUDE_CODE_MAX_CONTEXT_TOKENS"] == "128000"
assert captured["options"].env["CLAUDE_CODE_MAX_OUTPUT_TOKENS"] == "32000"
+ # Exercise the installed SDK's real argument serializer without starting a
+ # CLI or contacting a model. Capturing our own kwargs alone is insufficient.
+ from claude_agent_sdk import ClaudeAgentOptions
+ from claude_agent_sdk._internal.transport.subprocess_cli import SubprocessCLITransport
+
+ command = SubprocessCLITransport(
+ prompt="isolated parameter probe",
+ options=ClaudeAgentOptions(**vars(captured["options"])),
+ )._build_command()
+ if requested == "none":
+ assert command[command.index("--thinking") + 1] == "disabled"
+ assert "--effort" not in command
+ else:
+ assert "--thinking" not in command
+ if requested is None:
+ assert "--effort" not in command
+ else:
+ assert command[command.index("--effort") + 1] == requested
+
+
[email protected]("declared", [False, True])
+def test_session_handler_turns_thinking_off_only_when_the_model_declares_none(
+ monkeypatch,
+ tmp_path: Path,
+ declared: bool,
+) -> None:
+ """The legacy launch path follows the exact model catalog too."""
+
+ captured: dict[str, Any] = {}
+
+ class _StubClaudeSDKClient:
+ def __init__(self, options):
+ captured["options"] = options
+
+ async def connect(self) -> None:
+ return None
+
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)
+ monkeypatch.setattr(
+ "vibe.backend_model_catalog.catalog_reasoning_efforts_for_model",
+ lambda *_args: ["low", "none"] if declared else ["low"],
+ )
+
+ controller = _Controller(tmp_path)
+ controller.settings_manager.get_channel_routing = lambda _key: RoutingSettings(
+ model="claude-opus-4-6",
+ reasoning_effort="none",
+ )
+ handler = SessionHandler(controller)
+ context = MessageContext(user_id="U123", channel_id="C123")
+
+ _run_session(handler, context)
+
+ assert getattr(captured["options"], "thinking", None) == (
+ {"type": "disabled"} if declared else None
+ )
+ assert getattr(captured["options"], "effort", None) is None
+
+
[email protected]("channel", ["direct", "hub", "native_cli"])
[email protected]("subagent", [False, True])
[email protected]("waiting", [False, True])
+ ("before", "after", "next_model", "expected"),
+ [
+ ("none", "medium", "思考模型", "medium"),
+ ("medium", "none", "思考模型", "none"),
+ ("none", None, "思考模型", None),
+ (None, "none", "思考模型", "none"),
+ ("none", "none", "ordinary-model", None),
+ ("medium", "custom-effort", "思考模型", "custom-effort"),
+ ("none", "none", "思考模型", "none"),
+ ("medium", "medium", "思考模型", "medium"),
+ (None, "unsupported", "思考模型", None),
+ ],
+)
+def test_cached_claude_rechecks_effective_reasoning_and_preserves_resume(
+ monkeypatch, tmp_path, channel, subagent, waiting, before, after, next_model, expected,
+) -> None:
+ from modules.agents.model_hub import ModelHubLaunch
+
+ clients = []
+ catalogs = {
+ "思考模型": ["low", "medium", "none", "custom-effort"],
+ "ordinary-model": ["low", "medium"],
+ }
+
+ class Client:
+ def __init__(self, options):
+ self.options = options
+ self.disconnects = 0
+ self.model_calls = []
+ clients.append(self)
+
+ async def connect(self):
+ pass
+
+ async def disconnect(self):
+ self.disconnects += 1
+
+ async def set_model(self, model):
+ self.model_calls.append(model)
+
+ class Runtime:
+ async def resolve(self, backend, requested_model, **_kwargs):
+ return ModelHubLaunch(
+ backend=backend, channel=channel, requested_model=requested_model,
+ target_model=requested_model, runtime_model=requested_model,
+ source_id="src_test01", gateway_base_url="http://127.0.0.1:9/fixture",
+ gateway_token="fixture-token",
+ reasoning_efforts=tuple(catalogs[requested_model]),
+ )
+
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", Client)
+ monkeypatch.setattr(
+ "vibe.backend_model_catalog.catalog_reasoning_efforts_for_model",
+ lambda _backend, model: catalogs.get(model),
+ )
+ controller = _Controller(tmp_path)
+ controller.model_hub_runtime = Runtime()
+ routing = RoutingSettings(model="思考模型", reasoning_effort=before)
+ controller.settings_manager.get_channel_routing = lambda _key: routing
+ native_id = "native-resume-unchanged"
+ controller.settings_manager.sessions.get_claude_session_id = lambda *_args: native_id
+ controller.settings_manager.sessions.get_agent_session_id = lambda *_args, **_kw: native_id
+ handler = SessionHandler(controller)
+ monkeypatch.setattr(handler, "_load_agent_file", lambda *_args: {"prompt": "Review 中文", "model": "思考模型"})
+ context = MessageContext(user_id="U123", channel_id="C123")
+
+ async def run():
+ kwargs = {"subagent_name": "reviewer"} if subagent else {}
+ first = await handler.get_or_create_claude_session(context, **kwargs)
+ assert await handler.get_or_create_claude_session(context, **kwargs) is first
+ routing.model = next_model
+ routing.reasoning_effort = after
+ if waiting:
+ # An in-flight creator can publish an older configuration after the
+ # initial cache check. Its result must pass the same reuse policy.
+ key = first._vibe_runtime_session_key
+ controller.claude_sessions.pop(key)
+
+ async def publish_waiting_client(composite_key):
+ assert composite_key == key
+ controller.claude_sessions[key] = first
+ return first
+
+ monkeypatch.setattr(handler, "_wait_for_claude_session_create", publish_waiting_client)
+ second = await handler.get_or_create_claude_session(context, **kwargs)
+ changed = before != expected
+ assert (second is not first) is changed
+ assert first.disconnects == int(changed)
+ assert len(clients) == 1 + int(changed)
+ assert second.options.resume == native_id
+ assert second.options.fork_session is False
+ assert getattr(second.options, "thinking", None) == (
+ {"type": "disabled"} if expected == "none" else None
+ )
+ assert getattr(second.options, "effort", None) == (None if expected == "none" else expected)
+ assert await handler.get_or_create_claude_session(context, **kwargs) is second
+ assert len(clients) == 1 + int(changed)
+
+ asyncio.run(run())
+
+
+def test_claude_reasoning_change_waits_for_idle_before_recreation(monkeypatch, tmp_path) -> None:
+ clients = []
+
+ class Client:
+ def __init__(self, options):
+ self.options = options
+ self.disconnected = False
+ clients.append(self)
+
+ async def connect(self):
+ pass
+
+ async def disconnect(self):
+ assert self._vibe_runtime_session_key not in handler.active_sessions
+ self.disconnected = True
+
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", Client)
+ monkeypatch.setattr(
+ "vibe.backend_model_catalog.catalog_reasoning_efforts_for_model",
+ lambda *_args: ["none", "medium"],
+ )
+ controller = _Controller(tmp_path)
+ routing = RoutingSettings(model="claude-opus-4-6", reasoning_effort="none")
+ controller.settings_manager.get_channel_routing = lambda _key: routing
+ handler = SessionHandler(controller)
+ context = MessageContext(user_id="U123", channel_id="C123")
+
+ async def run():
+ first = await handler.get_or_create_claude_session(context)
+ key = first._vibe_runtime_session_key
+ handler.active_sessions.add(key)
+ routing.reasoning_effort = "medium"
+ entered_wait = asyncio.Event()
+ wait_for_idle = handler._wait_for_claude_session_idle
+
+ async def observe_wait(composite_key):
+ entered_wait.set()
+ await wait_for_idle(composite_key)
+
+ monkeypatch.setattr(handler, "_wait_for_claude_session_idle", observe_wait)
+ pending = asyncio.create_task(handler.get_or_create_claude_session(context))
+ await asyncio.wait_for(entered_wait.wait(), timeout=1)
+ assert not pending.done()
+ assert not first.disconnected
+ handler.active_sessions.remove(key)
+ second = await asyncio.wait_for(pending, timeout=1)
+ assert first.disconnected
+ assert second.options.effort == "medium"
+ assert len(clients) == 2
+
+ asyncio.run(run())
+
@pytest.mark.parametrize("channel", ["hub", "native_cli"])
@pytest.mark.parametrize("explicit", [None, "", "333333"])
diff --git a/tests/test_claude_reasoning_options.py b/tests/test_claude_reasoning_options.py
index e0eae0137..000ef52ab 100644
--- a/tests/test_claude_reasoning_options.py
+++ b/tests/test_claude_reasoning_options.py
@@ -132,6 +132,23 @@ def test_model_reasoning_resolver_does_not_leak_another_model_map() -> None:
assert resolve_model_reasoning_options(reasoning_options, "other-model", fallback) == fallback
+def test_normalize_claude_reasoning_effort_uses_the_model_declaration_for_off() -> None:
+ for model in ("claude-sonnet-4-5", "claude-opus-4-6", "claude-future-6"):
+ assert normalize_claude_reasoning_effort(model, "none") is None
+ assert normalize_claude_reasoning_effort(model, "none", ["low", "ultra"]) is None
+ assert normalize_claude_reasoning_effort(model, "none", []) is None
+ assert normalize_claude_reasoning_effort(model, "none", ["low", "none"]) == "none"
+ assert normalize_claude_reasoning_effort(model, None, ["low", "none"]) is None
+ assert [item["value"] for item in build_claude_reasoning_options(model, ["low", "none"])] == [
+ "__default__", "low", "none",
+ ]
+
+
+def test_claude_reasoning_options_keep_off_out_of_undeclared_defaults() -> None:
+ for model in (None, "claude-opus-5", "claude-sonnet-4-5"):
+ assert "none" not in [item["value"] for item in build_claude_reasoning_options(model)]
+
+
def test_normalize_claude_reasoning_effort_drops_invalid_efforts() -> None:
assert normalize_claude_reasoning_effort("claude-sonnet-4-5", "max") is None
assert normalize_claude_reasoning_effort("claude-opus-4-6", "xhigh") is None
diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.py
index b577b2a60..120be0252 100644
--- a/tests/test_model_hub_l3.py
+++ b/tests/test_model_hub_l3.py
@@ -5794,6 +5794,36 @@ def test_opencode_public_model_hides_preserved_efforts_when_reasoning_is_disable
}
[email protected]("protocol", ["anthropic", "openai_responses"])
[email protected]("supports_reasoning", [None, True, False])
[email protected]("efforts", [[], ["none"], ["low", "medium", "custom-tier"], ["low", "none", "custom-tier"]])
+def test_opencode_public_model_projects_only_declared_efforts(
+ protocol: str, supports_reasoning: bool | None, efforts: list[str],
+) -> None:
+ model = ModelHubBackendModelConfig(
+ id="model-with-explicit-options",
+ native_protocol=protocol,
+ supports_reasoning=supports_reasoning,
+ reasoning_efforts=efforts,
+ )
+ before = list(model.reasoning_efforts)
+
+ projected = project_opencode_public_model(model)
+
+ expected = {}
+ if supports_reasoning is not False:
+ for effort in efforts:
+ if protocol == "anthropic" and effort == "none":
+ expected[effort] = {"thinking": {"type": "disabled"}}
+ else:
+ expected[effort] = {
+ "effort" if protocol == "anthropic" else "reasoningEffort": effort,
+ }
+ assert projected.get("variants", {}) == expected
+ assert list(projected.get("variants", {})) == list(expected)
+ assert model.reasoning_efforts == before
+
+
@pytest.mark.parametrize(
("input_modalities", "output_modalities", "expected"),
[
diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.py
index 72ba886b8..9c2c7c5f4 100644
--- a/tests/test_model_hub_resolution.py
+++ b/tests/test_model_hub_resolution.py
@@ -872,7 +872,8 @@ def test_401_retry_depends_on_credential_capability_not_source_kind(tmp_path):
*[(efforts, provenance) for efforts in (["low"], ["high"])
for provenance in ("user", "catalog", "upstream")],
])
-def test_runtime_preserves_reasoning_intent_across_provider_fallback(tmp_path, efforts, provenance):
[email protected]("effort", ["high", "none"])
+def test_runtime_preserves_reasoning_intent_across_provider_fallback(tmp_path, efforts, provenance, effort):
first = _source("src_effort001", ("upstream-first",))
second = _source("src_effort002", ("upstream-second",))
first.models[0].reasoning_efforts = ["high"]
@@ -910,7 +911,7 @@ def test_runtime_preserves_reasoning_intent_across_provider_fallback(tmp_path, e
)
service, _store, _ = _service(tmp_path, config, adapter)
request = ModelHubRequest(
- {"reasoning": {"effort": "high", "summary": "auto"}},
+ {"reasoning": {"effort": effort, "summary": "auto"}},
protocol="openai_responses",
headers={"x-test": "preserved"},
)
@@ -927,11 +928,11 @@ def test_runtime_preserves_reasoning_intent_across_provider_fallback(tmp_path, e
assert resolved.source_id == second.id
assert adapter.invocation_requests[0]["reasoning"] == {
- "effort": "high",
+ "effort": effort,
"summary": "auto",
}
assert adapter.invocation_requests[1] == request
- assert request["reasoning"] == {"effort": "high", "summary": "auto"}
+ assert request["reasoning"] == {"effort": effort, "summary": "auto"}
assert adapter.invocation_requests[1].protocol == "openai_responses"
assert adapter.invocation_requests[1].headers == {"x-test": "preserved"}
started = [attempt for attempt in observed_attempts if attempt[4] is None]
@@ -942,9 +943,12 @@ def test_runtime_preserves_reasoning_intent_across_provider_fallback(tmp_path, e
@pytest.mark.parametrize("payload", [
{"reasoning_effort": "high"},
+ {"reasoning_effort": "none"},
{"reasoning_effort": "future-tier"},
{"reasoning": {"effort": "high", "summary": "auto"}},
+ {"reasoning": {"effort": "none"}},
{"thinking": {"type": "enabled", "budget_tokens": 4096}},
+ {"thinking": {"type": "disabled"}},
{"thinking": {"type": "adaptive"}, "output_config": {"effort": "max"}},
{"reasoning": {"summary": "auto"}},
{},
diff --git a/tests/test_opencode_reasoning_variants.py b/tests/test_opencode_reasoning_variants.py
index 0b4745ad4..017e5aecb 100644
--- a/tests/test_opencode_reasoning_variants.py
+++ b/tests/test_opencode_reasoning_variants.py
@@ -38,8 +38,7 @@ def _catalog_declared_tiers() -> dict[str, tuple[str, ...]]:
def test_opencode_variants_mirror_the_unified_vocabulary() -> None:
- # OpenCode adds exactly one token of its own: `none`, the opt-out.
- assert OPENCODE_REASONING_VARIANTS == ("none", *REASONING_EFFORT_VOCABULARY)
+ assert OPENCODE_REASONING_VARIANTS == REASONING_EFFORT_VOCABULARY
def test_every_vocabulary_tier_projects_to_an_openai_variant(tmp_path: Path) -> None:
@@ -66,6 +65,25 @@ def test_every_vocabulary_tier_projects_to_an_anthropic_variant(tmp_path: Path)
assert _written_model(tmp_path, "anthropic", "relay-model")["variants"] == {
effort: {"thinking": {"type": "enabled", "effort": effort}}
for effort in OPENCODE_REASONING_VARIANTS
+ if effort != "none"
+ } | {"none": {"thinking": {"type": "disabled"}}}
+
+
+def test_anthropic_none_disables_thinking_instead_of_enabling_a_bogus_level(
+ tmp_path: Path,
+) -> None:
+ """`none` is a switch, not a level: emitting `enabled` with effort `none`
+ turned thinking ON. Anthropic disables it with `{"type": "disabled"}`."""
+
+ upsert_opencode_provider_model(
+ "anthropic",
+ "relay-model",
+ reasoning_efforts=["none"],
+ home=tmp_path,
+ )
+
+ assert _written_model(tmp_path, "anthropic", "relay-model")["variants"] == {
+ "none": {"thinking": {"type": "disabled"}},
}
@@ -108,7 +126,7 @@ def test_family_default_suggestions_never_claim_ultra() -> None:
protocol_defaults = backend_model_catalog.PROTOCOL_REASONING_EFFORT_DEFAULTS
assert protocol_defaults
- assert all("ultra" not in efforts for efforts in protocol_defaults.values())
+ assert all(not {"none", "ultra"}.intersection(efforts) for efforts in protocol_defaults.values())
backend_defaults = backend_model_catalog._DEFAULT_REASONING_EFFORTS
assert backend_defaults
diff --git a/tests/test_ui_api.py b/tests/test_ui_api.py
index 79d594ddc..d59d18ba4 100644
--- a/tests/test_ui_api.py
+++ b/tests/test_ui_api.py
@@ -1694,6 +1694,100 @@ def test_normalize_backend_routing_payload_preserves_legacy_overrides_without_ba
assert result["claude_reasoning_effort"] == "max"
[email protected]("surface", ["channel", "user", "thread"])
[email protected]("inherit_model", [False, True])
+ ("efforts", "supports_reasoning", "requested", "expected"),
+ [
+ (["low", "medium", "none", "自定义"], True, "none", "none"),
+ (["low", "medium", "none", "自定义"], True, "medium", "medium"),
+ (["low", "medium", "none", "自定义"], True, "自定义", "自定义"),
+ (["low", "medium", "none"], True, None, None),
+ (["low", "medium"], True, "none", None),
+ ([], True, "none", None),
+ (["none"], False, "none", None),
+ ],
+)
+def test_routing_save_roundtrips_exact_hub_model_effort(
+ monkeypatch, surface, inherit_model, efforts, supports_reasoning, requested, expected,
+):
+ config = V2Config.default()
+ config.model_hub.agents["claude"].mode = "hub"
+ config.model_hub.agents["claude"].models = [
+ ModelHubBackendModelConfig(
+ id="中文模型", reasoning_efforts=efforts, supports_reasoning=supports_reasoning,
+ ),
+ ModelHubBackendModelConfig(id="other-model", reasoning_efforts=["none"]),
+ ]
+ monkeypatch.setattr(api.V2Config, "load", staticmethod(lambda: config))
+ monkeypatch.setattr(backend_model_catalog, "catalog_reasoning_efforts_for_model", lambda *_args: ["low", "medium"])
+ SettingsStore.reset_instance()
+ agent_store = VibeAgentStore()
+ try:
+ agent_store.create(name="routing-claude", backend="claude", model="中文模型")
+ route = {
+ "agent_name": "routing-claude",
+ "model": None if inherit_model else "中文模型",
+ "reasoning_effort": requested,
+ }
+ if surface == "channel":
+ api.save_settings({"platform": "telegram", "channels": {"-1001": {"routing": route}}})
+ elif surface == "user":
+ api.save_users({"platform": "telegram", "users": {"U123": {"routing": route}}})
+ else:
+ api.save_thread_settings({
+ "platform": "telegram", "channel_id": "-1001", "thread_id": "42",
+ "settings": {"routing": route},
+ })
+ # Read through a new store: successful API responses alone are not
+ # evidence that the requested value survived persistence.
+ SettingsStore.reset_instance()
+ if surface == "user":
+ saved = api.get_users("telegram")["users"]["U123"]["routing"]
+ else:
+ settings = api.get_settings("telegram")
+ saved = (
+ settings["channels"]["-1001"]["routing"]
+ if surface == "channel"
+ else settings["threads"]["-1001"]["42"]["routing"]
+ )
+ assert saved["reasoning_effort"] == expected
+ assert saved["model"] == route["model"]
+ assert saved["agent_name"] == "routing-claude"
+ finally:
+ SettingsStore.reset_instance()
+ agent_store.close()
+
+
[email protected]("mode", ["direct", "disabled", "hub-missing-model", "hub-empty-catalog"])
[email protected]("efforts", [None, ["low", "medium"], ["low", "medium", "none", "自定义"]])
[email protected]("requested", [None, "none", "medium", "自定义"])
+def test_routing_normalization_retains_native_fallback_without_cross_model_leaks(
+ monkeypatch, mode, efforts, requested,
+):
+ config = V2Config.default()
+ agent_catalog = config.model_hub.agents["claude"]
+ agent_catalog.mode = "direct" if mode == "direct" else "hub"
+ agent_catalog.models = (
+ [] if mode == "hub-empty-catalog" else [
+ ModelHubBackendModelConfig(id="other-model", reasoning_efforts=["none", "自定义"]),
+ ]
+ )
+ monkeypatch.setenv("VIBE_MODEL_HUB_ENABLED", "0" if mode == "disabled" else "1")
+ monkeypatch.setattr(api.V2Config, "load", staticmethod(lambda: config))
+ monkeypatch.setattr(backend_model_catalog, "catalog_reasoning_efforts_for_model", lambda *_args: efforts)
+ result = api._normalize_backend_routing_payload({
+ "agent_name": "claude", "model": "native-model", "reasoning_effort": requested,
+ })
+ allowed = (
+ efforts if mode in {"direct", "disabled"} and efforts is not None
+ else ["low", "medium", "high"]
+ )
+ expected = requested if requested in allowed else None
+ assert result["reasoning_effort"] == expected
+ assert result["model"] == "native-model"
+
+
def test_sync_start_oauth_web_keeps_background_tasks_on_persistent_loop(monkeypatch):
from core.agent_auth_service import WebAuthFlow
diff --git a/ui/e2e/model-catalog/README.md b/ui/e2e/model-catalog/README.md
index 3d006d87c..3455fb8a4 100644
--- a/ui/e2e/model-catalog/README.md
+++ b/ui/e2e/model-catalog/README.md
@@ -12,6 +12,12 @@ touch input. Cases verify picker additions, save/readback, child Cancel/Escape/
outside dismissal, editor commit, custom-editor handoff and catalog cancellation.
The host unmounts the catalog on close, matching `SettingsModelsPage`.
+`reasoning-off.spec.ts` extends `MH-MENU-COMPOSE-001`: Off is an unchecked
+per-model option until explicitly selected, existing/custom tiers retain their
+order, the catalog saves the exact declaration, and reread/cancel preserves it.
+All three backends run in English/Chinese on desktop/mobile. This proves the
+model editor's declaration flow, not live provider support for that declaration.
+
This consumes the shared `MH-MENU-COMPOSE-001` addition workflow. It guards the
React ownership of portalled child dialogs: a delayed touch click must not be
classified as outside the catalog after the child closes. Mouse-only and JSDOM
diff --git a/ui/e2e/model-catalog/fixture.tsx b/ui/e2e/model-catalog/fixture.tsx
index 021c31c7b..dfdd26005 100644
--- a/ui/e2e/model-catalog/fixture.tsx
+++ b/ui/e2e/model-catalog/fixture.tsx
@@ -19,6 +19,14 @@ const backend = params.get('backend') as AgentBackend;
const language = createInstance();
await language.init({ lng: params.get('lang') ?? 'en', resources: { en: { translation: en }, zh: { translation: zh } }, interpolation: { escapeValue: false } });
let saved: BackendModel[] = [{ ...blankBackendModel(), id: 'claude-existing-model', display_name: 'Existing model', context_window: 200000 }];
+if (params.has('reasoning-off')) {
+ saved = [{
+ ...saved[0],
+ supports_reasoning: true,
+ reasoning_efforts: ['high', 'medium', '自定义'],
+ native_protocol: backend === 'opencode' ? 'anthropic' : undefined,
+ }];
+}
const writes: BackendModelsPut[] = [];
const supply = (): AgentSupply => ({
backend, cli_present: true, mode: 'hub', menu_kind: backend === 'opencode' ? 'open' : 'fixed',
diff --git a/ui/e2e/model-catalog/reasoning-off.spec.ts b/ui/e2e/model-catalog/reasoning-off.spec.ts
new file mode 100644
index 000000000..371fff667
--- /dev/null
+++ b/ui/e2e/model-catalog/reasoning-off.spec.ts
@@ -0,0 +1,53 @@
+import { expect, test, type Locator, type Page } from '@playwright/test';
+import { hub } from '../support/copy';
+import type { BackendModel, BackendModelsPut } from '../../src/components/settings/models/types';
+
+const savedState = async (page: Page): Promise<{ saved: BackendModel[]; writes: BackendModelsPut[] }> =>
+ JSON.parse(await page.getByTestId('saved').innerText());
+
+for (const backend of ['claude', 'codex', 'opencode']) {
+ for (const lang of ['en', 'zh'] as const) {
+ test(`MH-MENU-COMPOSE-001: explicit model Off preserves old tiers (${backend}/${lang})`, async ({ page, isMobile }, testInfo) => {
+ const text = (key: string, vars?: Record<string, string | number>) => hub(`gateway.${key}`, vars, lang);
+ const activate = (locator: Locator) => isMobile ? locator.tap() : locator.click();
+ const offLabel = lang === 'zh' ? '关闭' : 'Off';
+ await page.route('**/api/**', (route) => route.abort());
+ await page.goto(`/e2e/model-catalog/fixture.html?backend=${backend}&lang=${lang}&reasoning-off=1`);
+ const initial = await savedState(page);
+
+ await activate(page.getByRole('button', { name: 'Manage models', exact: true }));
+ const edit = () => page.getByRole('button', { name: text('catalog.edit', { model: 'Existing model' }), exact: true });
+ await activate(edit());
+ await expect(page.getByRole('checkbox', { name: offLabel, exact: true })).not.toBeChecked();
+ for (const effort of initial.saved[0].reasoning_efforts) {
+ await expect(page.getByRole('checkbox', { name: effort, exact: true })).toBeChecked();
+ }
+ await activate(page.getByRole('button', { name: text('modelEditor.apply'), exact: true }));
+ expect(await savedState(page)).toEqual(initial);
+
+ await activate(edit());
+ await activate(page.getByRole('checkbox', { name: offLabel, exact: true }));
+ await expect(page.getByRole('checkbox', { name: offLabel, exact: true })).toBeChecked();
+ await page.screenshot({ path: testInfo.outputPath('model-declared-off.png'), scale: 'css' });
+ await activate(page.getByRole('button', { name: text('modelEditor.apply'), exact: true }));
+ expect(await savedState(page)).toEqual(initial);
+ await activate(page.getByRole('button', { name: text('catalog.save'), exact: true }));
+
+ const result = await savedState(page);
+ expect(result.writes).toHaveLength(1);
+ expect(result.writes[0].baseline).toEqual(initial.saved);
+ expect(result.saved).toEqual([{
+ ...initial.saved[0],
+ reasoning_efforts: [...initial.saved[0].reasoning_efforts, 'none'],
+ }]);
+
+ await activate(page.getByRole('button', { name: 'Manage models', exact: true }));
+ await activate(edit());
+ await expect(page.getByRole('checkbox', { name: offLabel, exact: true })).toBeChecked();
+ await activate(page.getByRole('checkbox', { name: offLabel, exact: true }));
+ await activate(page.getByRole('button', { name: text('modelEditor.cancel'), exact: true }));
+ await activate(page.getByRole('button', { name: text('catalog.cancel'), exact: true }));
+ expect(await savedState(page)).toEqual(result);
+ });
+ }
+}
diff --git a/ui/src/components/settings/models/BackendModelEditorDialog.test.tsx b/ui/src/components/settings/models/BackendModelEditorDialog.test.tsx
index 9477a6e3d..588c5df55 100644
--- a/ui/src/components/settings/models/BackendModelEditorDialog.test.tsx
+++ b/ui/src/components/settings/models/BackendModelEditorDialog.test.tsx
@@ -85,6 +85,46 @@ afterEach(() => {
});
describe('BackendModelEditorDialog', () => {
+ it.each(['claude', 'codex', 'opencode'] as const)('does not add Off when saving an existing %s model', async (backend) => {
+ const user = userEvent.setup();
+ const model: BackendModel = {
+ ...blankBackendModel(),
+ id: '模型/unchanged',
+ supports_reasoning: true,
+ native_protocol: backend === 'opencode' ? 'openai_responses' : undefined,
+ reasoning_efforts: ['high', 'medium', '自定义'],
+ };
+ const { onCommit } = renderEditor({ backend, model });
+
+ expect(screen.getByRole('checkbox', { name: 'Off' }).getAttribute('aria-checked')).toBe('false');
+ await user.click(screen.getByRole('button', { name: 'Save model' }));
+
+ expect(onCommit).toHaveBeenCalledWith(model);
+ });
+
+ it.each(['en', 'zh'] as const)('persists Off only after an explicit model choice (%s)', async (language) => {
+ const previous = i18n.language;
+ await i18n.changeLanguage(language);
+ try {
+ const user = userEvent.setup();
+ const model: BackendModel = {
+ ...blankBackendModel(),
+ id: '模型/opt-in',
+ supports_reasoning: true,
+ reasoning_efforts: ['high', '自定义'],
+ };
+ const { onCommit } = renderEditor({ model });
+ const off = screen.getByRole('checkbox', { name: language === 'zh' ? '关闭' : 'Off' });
+ await user.click(off);
+ expect(off.getAttribute('aria-checked')).toBe('true');
+ await user.click(screen.getByRole('button', { name: i18n.t('settings.models.gateway.modelEditor.apply') }));
+ expect(onCommit).toHaveBeenCalledWith({ ...model, reasoning_efforts: ['high', '自定义', 'none'] });
+ } finally {
+ cleanup();
+ await i18n.changeLanguage(previous);
+ }
+ });
+
it('refuses an empty or already-taken model ID', async () => {
const user = userEvent.setup();
const { onCommit } = renderEditor({ takenIds: new Set(['taken']) });
diff --git a/ui/src/components/settings/models/BackendModelEditorDialog.tsx b/ui/src/components/settings/models/BackendModelEditorDialog.tsx
index 421ef0c88..46a3033f9 100644
--- a/ui/src/components/settings/models/BackendModelEditorDialog.tsx
+++ b/ui/src/components/settings/models/BackendModelEditorDialog.tsx
@@ -19,6 +19,7 @@ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, D
import { Input } from '@/components/ui/input';
import { SegmentedRadio } from '@/components/ui/segmented';
import { isComposingKey } from '@/lib/imeComposition';
+import { NO_REASONING_EFFORT } from '@/lib/effortOptions';
import { cn } from '@/lib/utils';
import { applyModelsDevMatch, backendModelId, blankBackendModel, draftWithId, retireModelsDevMatch } from './backendCatalog';
import { Field } from './dialogFields';
@@ -392,7 +393,9 @@ export const BackendModelEditorDialog: React.FC<{
});
};
- const efforts = [...new Set([...effortSuggestions, ...draft.reasoning_efforts])];
+ // A suggestion is not a capability declaration: Off stays unchecked until
+ // the operator adds it to this exact model, just like any custom effort.
+ const efforts = [...new Set([NO_REASONING_EFFORT, ...effortSuggestions, ...draft.reasoning_efforts])];
const backendName = t(`settings.models.backends.${backend}`, { defaultValue: backend });
const protocolLabel = t('settings.models.gateway.modelEditor.nativeProtocol.label') as string;
const idHint = submitted && idError ? t(`settings.models.gateway.modelEditor.id.${idError}`) as string : null;
@@ -625,7 +628,7 @@ export const BackendModelEditorDialog: React.FC<{
<div className="flex flex-wrap gap-2" role="group" aria-labelledby="model-hub-efforts">
{efforts.map((effort) => (
<ChipButton key={effort} on={draft.reasoning_efforts.includes(effort)} onClick={() => toggleEffort(effort)}>
- {effort}
+ {effort === NO_REASONING_EFFORT ? t('chat.picker.effortOptions.none') : effort}
</ChipButton>
))}
{customOpen ? (
diff --git a/ui/src/components/settings/models/reasoningEffortVocabulary.mirror.test.ts b/ui/src/components/settings/models/reasoningEffortVocabulary.mirror.test.ts
index 9691a5da8..554827ada 100644
--- a/ui/src/components/settings/models/reasoningEffortVocabulary.mirror.test.ts
+++ b/ui/src/components/settings/models/reasoningEffortVocabulary.mirror.test.ts
@@ -20,6 +20,7 @@ const CATALOG_PY = resolve(HERE, '../../../../..', 'vibe/backend_model_catalog.p
* never a silent skip.
*/
const FROZEN_VOCABULARY = [
+ 'none',
'minimal',
'low',
'medium',
@@ -68,7 +69,7 @@ describe('reasoning-effort vocabulary UI ↔ backend mirror', () => {
expect(namesVocabulary).toBe(namesDefaults);
});
- it('holds REASONING_EFFORTS equal to the backend export, or the frozen 7-list while that name is absent', () => {
+ it('holds REASONING_EFFORTS equal to the backend export, including model-scoped Off', () => {
expect([...REASONING_EFFORTS]).toEqual(exportedVocabulary ?? [...FROZEN_VOCABULARY]);
});
diff --git a/ui/src/components/settings/models/tierSuggestions.test.ts b/ui/src/components/settings/models/tierSuggestions.test.ts
index 6c62992ab..8c38b6a73 100644
--- a/ui/src/components/settings/models/tierSuggestions.test.ts
+++ b/ui/src/components/settings/models/tierSuggestions.test.ts
@@ -43,9 +43,9 @@ describe('unified reasoning-effort vocabulary', () => {
// The UI-side pin of the frozen vocabulary. The cross-file mirror in
// `reasoningEffortVocabulary.mirror.test.ts` holds this list equal to the
// backend export when that name exists on the branch, and to this same
- // frozen 7-list while it does not.
+ // frozen vocabulary while it does not.
expect([...REASONING_EFFORTS]).toEqual([
- 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra',
+ 'none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra',
]);
});
@@ -60,6 +60,7 @@ describe('unified reasoning-effort vocabulary', () => {
// Family defaults are rung-1 over-claim protection, not the catalog
// superset: an unknown relay must not be handed `ultra`.
expect(tiers, protocol).not.toContain('ultra');
+ expect(tiers, protocol).not.toContain('none');
}
});
diff --git a/ui/src/components/settings/providers/OpencodeProviderConfig.tsx b/ui/src/components/settings/providers/OpencodeProviderConfig.tsx
index dbb528fe6..240ea3f8f 100644
--- a/ui/src/components/settings/providers/OpencodeProviderConfig.tsx
+++ b/ui/src/components/settings/providers/OpencodeProviderConfig.tsx
@@ -43,7 +43,7 @@ import type {
import { useToast } from '@/context/ToastContext';
import { errorMessage } from '@/lib/errorMessage';
import { isNativeAuthHubOwned } from '@/lib/nativeAuthOwnership';
-import { EFFORT_BY_BACKEND, sortEffortsByVocabulary } from '@/lib/effortOptions';
+import { EFFORT_BY_BACKEND, NO_REASONING_EFFORT, sortEffortsByVocabulary } from '@/lib/effortOptions';
import { HubOwnedAuthNotice } from '../shared/HubOwnedAuthNotice';
type FilterMode = 'all' | 'configured' | 'oauth' | 'local';
@@ -92,13 +92,10 @@ const SERVER_START_RETRY_DELAY_MS = 3000;
const FILTER_MODES: ReadonlyArray<FilterMode> = ['all', 'configured', 'oauth', 'local'];
-// This form's save path is `_normalize_reasoning_variants` in
-// `vibe/opencode_config.py`, which accepts `none` plus the OpenCode family
-// fallback (`minimal`..`max`). `ultra` is in the unified vocabulary because
-// catalog rows declare it, but offering it here would send a value the
-// save path rejects. Checkboxes and the default-checked list are the same set.
-const OPENCODE_PROVIDER_EFFORTS = EFFORT_BY_BACKEND.opencode;
-const defaultReasoningEfforts = () => [...OPENCODE_PROVIDER_EFFORTS];
+// Off is available as an explicit per-model declaration. Keep the existing
+// default-checked tiers unchanged; offering a choice must not enable it.
+const OPENCODE_PROVIDER_EFFORTS = [NO_REASONING_EFFORT, ...EFFORT_BY_BACKEND.opencode];
+const defaultReasoningEfforts = () => [...EFFORT_BY_BACKEND.opencode];
const notifyOpenCodeModelOptionsChanged = () => {
window.dispatchEvent(new CustomEvent('avibe:opencode-model-options-changed'));
@@ -1396,7 +1393,7 @@ export const OpencodeProviderConfig: React.FC<{
checked={edit.reasoningEfforts.includes(effort)}
presentational
/>
- {effort}
+ {effort === NO_REASONING_EFFORT ? t('chat.picker.effortOptions.none') : effort}
</Button>
))}
</div>
diff --git a/ui/src/components/settings/providers/OpencodeProviderReasoning.test.tsx b/ui/src/components/settings/providers/OpencodeProviderReasoning.test.tsx
new file mode 100644
index 000000000..d488bd97f
--- /dev/null
+++ b/ui/src/components/settings/providers/OpencodeProviderReasoning.test.tsx
@@ -0,0 +1,64 @@
+// @vitest-environment jsdom
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { EFFORT_BY_BACKEND } from '@/lib/effortOptions';
+import { OpencodeProviderConfig } from './OpencodeProviderConfig';
+
+const mocks = vi.hoisted(() => ({
+ getOpencodeProviders: vi.fn(),
+ saveOpencodeProviderModel: vi.fn(),
+ setPermissionAllowed: vi.fn(),
+ showToast: vi.fn(),
+}));
+vi.mock('@/context/ApiContext', () => ({ useApi: () => mocks }));
+vi.mock('@/context/ToastContext', () => ({ useToast: () => mocks }));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key === 'chat.picker.effortOptions.none' ? 'Off' : key }),
+}));
+vi.mock('../shared/useBackendRuntime', () => ({
+ useBackendRuntime: () => ({ loaded: true, enabled: true, cliStatus: 'ok' }),
+}));
+vi.mock('../shared/useOpencodePermission', () => ({ useOpencodePermission: () => mocks }));
+vi.mock('../models/useModelHubCapability', () => ({ useModelHubCapability: () => false }));
+vi.mock('../shared/BackendRuntimeCard', () => ({ BackendRuntimeCard: () => null }));
+vi.mock('./BackendConnectionForm', () => ({ BackendConnectionForm: () => null }));
+vi.mock('../OpencodeProviderTestPanel', () => ({ OpencodeProviderTestPanel: () => null }));
+
+afterEach(() => {
+ cleanup();
+ vi.resetAllMocks();
+});
+
+describe('OpenCode per-model reasoning declarations', () => {
+ it.each([false, true])('only saves Off after opting in and resets for the next model (optIn=%s)', async (optIn) => {
+ mocks.getOpencodeProviders.mockResolvedValue({
+ ok: true,
+ permission_allowed: true,
+ providers: [{
+ id: 'fixture', name: 'Fixture provider', description: '', models: [],
+ configured: true, custom: true, local: false, oauth_available: false,
+ }],
+ });
+ mocks.saveOpencodeProviderModel.mockResolvedValue({ ok: true });
+ render(<OpencodeProviderConfig />);
+ fireEvent.click(await screen.findByRole('button', { name: /Fixture provider/ }));
+ const off = () => screen.getByRole('button', { name: 'Off', exact: true });
+ expect(off().className).not.toContain('bg-cyan-soft');
+ for (const effort of EFFORT_BY_BACKEND.opencode) {
+ expect(screen.getByRole('button', { name: effort, exact: true }).className).toContain('bg-cyan-soft');
+ }
+ expect(mocks.saveOpencodeProviderModel).not.toHaveBeenCalled();
+ if (optIn) fireEvent.click(off());
+ fireEvent.change(screen.getByPlaceholderText('settings.backends.opencodeProviderModelPlaceholder'), {
+ target: { value: '模型/declared' },
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'settings.backends.opencodeProviderModelAdd' }));
+ await waitFor(() => expect(mocks.saveOpencodeProviderModel).toHaveBeenCalledWith('fixture', {
+ model_id: '模型/declared',
+ reasoning_efforts: optIn ? ['none', ...EFFORT_BY_BACKEND.opencode] : EFFORT_BY_BACKEND.opencode,
+ }));
+ await waitFor(() => expect(off().className).not.toContain('bg-cyan-soft'));
+ expect(mocks.saveOpencodeProviderModel).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/ui/src/components/workbench/AgentRoutePicker.test.tsx b/ui/src/components/workbench/AgentRoutePicker.test.tsx
index 7425f3f7e..dd11f6e50 100644
--- a/ui/src/components/workbench/AgentRoutePicker.test.tsx
+++ b/ui/src/components/workbench/AgentRoutePicker.test.tsx
@@ -142,6 +142,25 @@ describe('AgentRoutePicker', () => {
expect(highlighted('sonnet')).toBe(false);
});
+ it('selects declared Off without changing the model or leaking it to another model', async () => {
+ catalogReasoning = {
+ sonnet: [{ value: 'low', label: 'Low' }, { value: 'none', label: 'Off' }],
+ opus: [{ value: 'low', label: 'Low' }],
+ };
+ const user = userEvent.setup();
+ const onWrite = vi.fn();
+ render(<OptimisticOwner onWrite={onWrite} />);
+ await openMenu(user);
+
+ await user.click(screen.getByRole('button', { name: 'chat.picker.effortOptions.none' }));
+ expect(onWrite).toHaveBeenCalledExactlyOnceWith({ reasoning_effort: 'none' });
+ expect(highlighted('chat.picker.effortOptions.none')).toBe(true);
+
+ await user.click(screen.getByRole('button', { name: 'opus' }));
+ expect(onWrite).toHaveBeenLastCalledWith({ model: 'opus', reasoning_effort: null });
+ expect(screen.queryByRole('button', { name: 'chat.picker.effortOptions.none' })).toBeNull();
+ });
+
it('keeps the menu clickable while a write is in flight, so the next pick is not lost', async () => {
const user = userEvent.setup();
const onWrite = vi.fn();
diff --git a/ui/src/components/workbench/AgentsPage.test.tsx b/ui/src/components/workbench/AgentsPage.test.tsx
index 859d8de04..9785f3112 100644
--- a/ui/src/components/workbench/AgentsPage.test.tsx
+++ b/ui/src/components/workbench/AgentsPage.test.tsx
@@ -1522,6 +1522,33 @@ describe('AgentsPage reconnect reconciliation', () => {
expect(screen.getByRole('button', { name: 'medium', exact: true }).className).toContain('bg-mint-soft');
});
+ it('preserves a declared Off while editing another Agent field, and allows selecting medium', async () => {
+ modelCatalog = {
+ models: [],
+ reasoningOptions: {
+ 'with-off': [{ value: 'none', label: 'Off' }, { value: 'medium', label: 'Medium' }],
+ },
+ };
+ const initial = { ...brief('agent-a', 'description'), model: 'with-off', reasoning_effort: 'none' };
+ const updateVibeAgent = vi.fn().mockResolvedValue({ ok: true });
+ const getVibeAgent = vi.fn().mockResolvedValue(fullAgent(initial, 'initial prompt'));
+ renderPage(makeApi(
+ vi.fn().mockResolvedValue(listResult(initial)), getVibeAgent, undefined, undefined, updateVibeAgent,
+ ), { canManageAgents: true });
+
+ const description = await screen.findByDisplayValue('description');
+ expect(screen.getByRole('button', { name: 'chat.picker.effortOptions.none' }).className).toContain('bg-mint-soft');
+ expect(screen.getByRole('button', { name: 'medium', exact: true }).className).not.toContain('bg-mint-soft');
+ expect(updateVibeAgent).not.toHaveBeenCalled();
+ fireEvent.change(description, { target: { value: 'updated description' } });
+ fireEvent.blur(description);
+ await waitFor(() => expect(updateVibeAgent).toHaveBeenCalledWith('agent-a', { description: 'updated description' }));
+ expect(updateVibeAgent).toHaveBeenCalledTimes(1);
+
+ fireEvent.click(screen.getByRole('button', { name: 'medium', exact: true }));
+ await waitFor(() => expect(updateVibeAgent).toHaveBeenCalledWith('agent-a', { reasoning_effort: 'medium' }));
+ });
+
it.each(['model', 'effort'] as const)('restores the authoritative value after a failed %s mutation', async (field) => {
const initial = {
...brief('agent-a', 'description'),
diff --git a/ui/src/components/workbench/AgentsPage.tsx b/ui/src/components/workbench/AgentsPage.tsx
index 5345cc205..5d6af20eb 100644
--- a/ui/src/components/workbench/AgentsPage.tsx
+++ b/ui/src/components/workbench/AgentsPage.tsx
@@ -2411,7 +2411,7 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, ca
!canEdit && !active && 'opacity-70 hover:text-muted',
)}
>
- {opt}
+ {opt === 'none' ? t('chat.picker.effortOptions.none') : opt}
</button>
);
})}
diff --git a/ui/src/components/workbench/NewAgentDialog.test.tsx b/ui/src/components/workbench/NewAgentDialog.test.tsx
index 64d230f66..4093f0ae8 100644
--- a/ui/src/components/workbench/NewAgentDialog.test.tsx
+++ b/ui/src/components/workbench/NewAgentDialog.test.tsx
@@ -115,4 +115,24 @@ describe('NewAgentDialog', () => {
reasoning_effort: 'medium',
})));
});
+
+ it.each([false, true])('keeps medium unless the user selects declared Off (selected=%s)', async (selectOff) => {
+ modelCatalog = {
+ models: [],
+ reasoningOptions: {
+ 'with-off': [{ value: 'none', label: 'Off' }, { value: 'medium', label: 'Medium' }],
+ },
+ };
+ const { createVibeAgent } = renderDialog();
+ fireEvent.change(screen.getByPlaceholderText('agents.create.namePlaceholder'), { target: { value: 'router' } });
+ chooseModel('with-off');
+ const off = screen.getByRole('button', { name: 'chat.picker.effortOptions.none' });
+ if (selectOff) fireEvent.click(off);
+ submit();
+
+ await waitFor(() => expect(createVibeAgent).toHaveBeenCalledWith(expect.objectContaining({
+ model: 'with-off',
+ reasoning_effort: selectOff ? 'none' : 'medium',
+ })));
+ });
});
diff --git a/ui/src/components/workbench/NewAgentDialog.tsx b/ui/src/components/workbench/NewAgentDialog.tsx
index 79fa70ce2..ba24c9bfe 100644
--- a/ui/src/components/workbench/NewAgentDialog.tsx
+++ b/ui/src/components/workbench/NewAgentDialog.tsx
@@ -286,7 +286,7 @@ export const NewAgentDialog: React.FC<NewAgentDialogProps> = ({ open, onClose, o
effort === opt ? 'bg-mint-soft font-bold text-mint-ink' : 'font-medium text-muted hover:text-foreground',
)}
>
- {opt}
+ {opt === 'none' ? t('chat.picker.effortOptions.none') : opt}
</button>
))}
</div>
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index d62eca17f..37c34e93b 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1035,7 +1035,7 @@
"reasoningEfforts": "Reasoning effort",
"customEffort": "Custom effort",
"customEffortPlaceholder": "e.g. medium",
- "effortNote": "Efforts are sent to the provider verbatim; with none selected, the request omits the effort parameter.",
+ "effortNote": "List only options this model supports. Selecting Off in an Agent disables extended thinking; an empty option list does not mean Off. Other effort values are forwarded unchanged.",
"nativeProtocol": {
"label": "API",
"openai_responses": "OpenAI Responses",
@@ -4211,6 +4211,7 @@
"searchModels": "Search models",
"noModelMatch": "No matching models",
"effortOptions": {
+ "none": "Off",
"minimal": "Minimal",
"low": "Low",
"medium": "Medium",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 469c5dfc7..6e539644a 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1035,7 +1035,7 @@
"reasoningEfforts": "推理强度",
"customEffort": "自定义档位",
"customEffortPlaceholder": "如 medium",
- "effortNote": "档位按原样发送给供应商;不选则请求不带 effort 参数。",
+ "effortNote": "仅声明该模型支持的选项。在 Agent 中选择“关闭”才会禁用扩展思考;选项列表为空不等于关闭。其他档位按原样转发。",
"nativeProtocol": {
"label": "API",
"openai_responses": "OpenAI Responses",
@@ -4211,6 +4211,7 @@
"searchModels": "搜索模型",
"noModelMatch": "无匹配模型",
"effortOptions": {
+ "none": "关闭",
"minimal": "极简",
"low": "低",
"medium": "中",
diff --git a/ui/src/lib/effortOptions.test.ts b/ui/src/lib/effortOptions.test.ts
index 2bb7ed518..22bd577d3 100644
--- a/ui/src/lib/effortOptions.test.ts
+++ b/ui/src/lib/effortOptions.test.ts
@@ -39,6 +39,32 @@ describe('effort options', () => {
expect(isEffortSupported('codex', 'future-model', 'ultra', reasoningOptions)).toBe(true);
});
+ it.each(['claude', 'codex', 'opencode'])('offers Off only from the selected %s model declaration', (backend) => {
+ const reasoningOptions = {
+ 'with-off': [
+ { value: '__default__', label: 'Default' },
+ { value: 'high', label: 'High' },
+ { value: 'none', label: 'Off' },
+ { value: 'custom-effort', label: 'Custom' },
+ ],
+ 'without-off': [{ value: 'high', label: 'High' }],
+ 'empty': [],
+ 'default-only': [{ value: '__default__', label: 'Default' }],
+ };
+
+ // Preserve declared order and custom values, rather than changing the first
+ // option (which existing callers may use as their suggested default).
+ expect(resolveEffortOptions(backend, 'with-off', reasoningOptions)).toEqual(['high', 'none', 'custom-effort']);
+ expect(isEffortSupported(backend, 'with-off', 'none', reasoningOptions)).toBe(true);
+ for (const model of ['without-off', 'empty', 'default-only', 'unknown']) {
+ expect(isEffortSupported(backend, model, 'none', reasoningOptions)).toBe(false);
+ expect(isEffortSupported(backend, model, null, reasoningOptions)).toBe(true);
+ }
+ expect(resolveEffortOptions(backend, 'without-off', reasoningOptions)).toEqual(['high']);
+ expect(resolveEffortOptions(backend, 'empty', reasoningOptions)).toEqual([]);
+ expect(resolveEffortOptions(backend, 'unknown', undefined)).not.toContain('none');
+ });
+
it('treats an explicitly empty entry as "no efforts", not as a missing answer', () => {
const reasoningOptions = {
'': [{ value: 'low', label: 'Low' }],
@@ -101,7 +127,8 @@ describe('effort options', () => {
});
it('orders selected efforts by the unified vocabulary, unknowns last', () => {
- expect(sortEffortsByVocabulary(['ultra', 'low', 'custom-b', 'max', 'custom-a'])).toEqual([
+ expect(sortEffortsByVocabulary(['ultra', 'low', 'custom-b', 'none', 'max', 'custom-a'])).toEqual([
+ 'none',
'low',
'max',
'ultra',
@@ -113,6 +140,9 @@ describe('effort options', () => {
it('keeps the OpenCode family fallback inside the vocabulary without ultra', () => {
// Same set the OpenCode provider form offers and the save path accepts
// (`vibe/opencode_config.py:_VALID_REASONING_VARIANTS` minus `none`).
- expect(EFFORT_BY_BACKEND.opencode).toEqual([...REASONING_EFFORTS].filter((effort) => effort !== 'ultra'));
+ expect(EFFORT_BY_BACKEND.opencode).toEqual(
+ [...REASONING_EFFORTS].filter((effort) => effort !== 'ultra' && effort !== 'none'),
+ );
+ for (const efforts of Object.values(EFFORT_BY_BACKEND)) expect(efforts).not.toContain('none');
});
});
diff --git a/ui/src/lib/effortOptions.ts b/ui/src/lib/effortOptions.ts
index ff68e1ab0..5b59b7afc 100644
--- a/ui/src/lib/effortOptions.ts
+++ b/ui/src/lib/effortOptions.ts
@@ -25,10 +25,18 @@
* declare it. Protocol-family defaults and backend fallbacks still omit it: an
* unknown relay model must not be over-claimed.
*/
-export const REASONING_EFFORTS = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'] as const;
+// `none` is a known explicit Off value, not a backend/family default. Only a
+// model that declares it may offer it; recognizing it does not add capability.
+export const REASONING_EFFORTS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'] as const;
export type ReasoningEffort = (typeof REASONING_EFFORTS)[number];
+/**
+ * Explicit Off in a model's declared options, distinct from an unset effort.
+ * Adapters translate this value; they never add it to a model's capabilities.
+ */
+export const NO_REASONING_EFFORT = 'none';
+
// Typed against the vocabulary rather than `string[]`: a backend list that
// drifts away from it then fails to compile, which is the check the spec asks
// for stated where it cannot be forgotten.
diff --git a/vibe/api.py b/vibe/api.py
index c55fa0ce1..8ced93486 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -5309,32 +5309,50 @@ def get_settings(platform: Optional[str] = None, *, user_context: Any = None) ->
def _normalize_backend_routing_payload(routing_payload: dict) -> dict:
+ from config.v2_config import is_model_hub_enabled
+ from core.handlers.model_hub.service import V2ModelHubConfigStore
from modules.agents.opencode.utils import normalize_claude_reasoning_effort
routing = _parse_routing(routing_payload or {})
- if _backend_for_routing_agent(routing.agent_name) == "claude":
+ backend, agent_model = _routing_agent_backend_and_model(routing.agent_name)
+ if backend == "claude" and routing.reasoning_effort:
+ model = routing.model or agent_model
+ catalog_efforts = None
+ agent_catalog = (
+ V2ModelHubConfigStore().load().agents["claude"] if is_model_hub_enabled() else None
+ )
+ if agent_catalog is not None and agent_catalog.mode == "hub":
+ row = next((row for row in agent_catalog.models if row.id == model), None)
+ if row is not None:
+ # Match the picker: a present empty list (or non-reasoning
+ # model) is authoritative, not a request for backend tiers.
+ catalog_efforts = [] if row.supports_reasoning is False else row.reasoning_efforts
+ # Unknown Hub rows retain the existing generic normalization;
+ # a same-named native model must not grant them Off support.
+ else:
+ catalog_efforts = backend_model_catalog.catalog_reasoning_efforts_for_model("claude", model)
routing.reasoning_effort = normalize_claude_reasoning_effort(
- routing.model,
+ model,
routing.reasoning_effort,
+ catalog_efforts,
)
return _routing_to_dict(routing)
-def _backend_for_routing_agent(agent_name: Optional[str]) -> Optional[str]:
+def _routing_agent_backend_and_model(agent_name: Optional[str]) -> tuple[Optional[str], Optional[str]]:
name = str(agent_name or "").strip()
if not name:
- return None
- if is_agent_backend(name):
- return name
+ return None, None
store = VibeAgentStore()
try:
agent = store.get(name)
- return agent.backend if agent is not None else None
+ if agent is not None:
+ return agent.backend, agent.model
except Exception:
logger.debug("Failed to resolve Agent backend while normalizing routing payload", exc_info=True)
- return None
finally:
store.close()
+ return (name, None) if is_agent_backend(name) else (None, None)
def _normalize_show_message_types_for_platform(show_message_types: Optional[list], platform: str) -> list[str]:
diff --git a/vibe/backend_model_catalog.py b/vibe/backend_model_catalog.py
index bf2a3acfb..4f73a0e5c 100644
--- a/vibe/backend_model_catalog.py
+++ b/vibe/backend_model_catalog.py
@@ -58,6 +58,7 @@ _DEFAULT_REASONING_EFFORTS = {
"codex": ["minimal", "low", "medium", "high", "xhigh"],
}
REASONING_EFFORT_VOCABULARY: Final[tuple[str, ...]] = (
+ "none",
"minimal",
"low",
"medium",
diff --git a/vibe/opencode_config.py b/vibe/opencode_config.py
index d5b568eae..a416f69c4 100644
--- a/vibe/opencode_config.py
+++ b/vibe/opencode_config.py
@@ -11,10 +11,8 @@ from typing import Any, Dict, Final, Optional
logger = logging.getLogger(__name__)
-# Every reasoning tier OpenCode accepts, in ascending order: the unified Model
-# Hub vocabulary (``vibe.backend_model_catalog.REASONING_EFFORT_VOCABULARY``)
-# plus OpenCode's own ``none``, which names the absence of reasoning rather
-# than a level.
+# Known OpenCode reasoning options, including explicitly declared Off, mirrored
+# from ``vibe.backend_model_catalog.REASONING_EFFORT_VOCABULARY``.
#
# Mirrored rather than imported: this module is stdlib-only so the OpenCode
# read path can stay cheap, while the catalog module pulls in the whole
@@ -31,6 +29,11 @@ OPENCODE_REASONING_VARIANTS: Final[tuple[str, ...]] = (
"max",
"ultra",
)
+# OpenCode's own token for the absence of reasoning. It is a switch, not a
+# level, so Anthropic-compatible providers translate it to a disabled thinking
+# block rather than an enabled one naming this value.
+_NO_REASONING_VARIANT: Final[str] = "none"
+
_CUSTOM_PROVIDER_META_KEY = "vibe_remote"
_CUSTOM_PROVIDER_ADAPTERS = {
"openai-compatible": "@ai-sdk/openai-compatible",
@@ -689,7 +692,14 @@ def _normalize_reasoning_variants(
if effort not in OPENCODE_REASONING_VARIANTS:
raise ValueError(f"unsupported reasoning effort: {effort}")
if uses_anthropic_thinking:
- variants[effort] = {"thinking": {"type": "enabled", "effort": effort}}
+ # ``none`` is a switch, not a level. Emitting it as
+ # ``{"type": "enabled", "effort": "none"}`` turned thinking ON with a
+ # bogus level; Anthropic disables it with ``{"type": "disabled"}``.
+ variants[effort] = (
+ {"thinking": {"type": "disabled"}}
+ if effort == _NO_REASONING_VARIANT
+ else {"thinking": {"type": "enabled", "effort": effort}}
+ )
else:
variants[effort] = {"reasoningEffort": effort}
return variants