Python
Reasoning effort and thinking controls beside the model
Rohit C Prasad833bb291d2fc
diff --git a/coworker/providers/local_server.py b/coworker/providers/local_server.pyindex 3f87df26..f33f9154 100644--- a/coworker/providers/local_server.py+++ b/coworker/providers/local_server.py@@ -177,12 +177,16 @@ def _row(name: str, item: dict[str, Any], props: dict[str, Any], tools: Optionalsize = Nonerec = recommendation_for(model_id)chosen = model_config.context_size_for(model_id)+ # A chat template that reads `enable_thinking` has a thinking switch (Nemotron, Qwen3);+ # the recommendation table says so for the models it knows.+ template = str(props.get("chat_template") or "")+ thinking = True if "enable_thinking" in template else (rec.thinking_available if rec else None)return {"model": model_id,"name": served_id,"size_bytes": size,"tools": tools,- "thinking": rec.thinking_available if rec else None,+ "thinking": thinking,"vision": None,"remote": False,"parameter_size": None,@@ -198,3 +202,24 @@ def _row(name: str, item: dict[str, Any], props: dict[str, Any], tools: Optionaldef _int(value: Any) -> Optional[int]:return int(value) if isinstance(value, (int, float)) and not isinstance(value, bool) and value > 0 else None+++def thinking_as_template_kwargs(settings: dict[str, Any]) -> dict[str, Any]:+ """The thinking switch travels as Ollama's `think` field (model_config.py); llama.cpp+ and vLLM read it from the chat template's `enable_thinking` instead. Rewrites one into+ the other and leaves everything else alone."""+ extra = settings.get("extra_body")+ if not isinstance(extra, dict) or "think" not in extra:+ return settings+ extra = dict(extra)+ think = extra.pop("think")+ if isinstance(think, bool):+ kwargs = dict(extra.get("chat_template_kwargs") or {})+ kwargs["enable_thinking"] = think+ extra["chat_template_kwargs"] = kwargs+ out = dict(settings)+ if extra:+ out["extra_body"] = extra+ else:+ out.pop("extra_body", None)+ return outdiff --git a/coworker/providers/model_controls.json b/coworker/providers/model_controls.jsonnew file mode 100644index 00000000..7fd54680--- /dev/null+++ b/coworker/providers/model_controls.json@@ -0,0 +1,51 @@+{+ "version": 1,+ "about": "Which per-session controls a cloud model has: a thinking switch and/or reasoning-effort levels. Read by coworker/providers/model_controls.py. Patterns match the model id without its provider prefix; `providers` limits a row to those providers; the first matching row wins. Local models (Ollama, llama.cpp, vLLM) are filled in from what their server reports, so they are listed here only where the server's answer is not enough. Anything not listed has neither control. Edit in git; give a source.",+ "models": [+ {+ "match": ["claude-fable-5*", "claude-mythos-5*", "claude-opus-5*", "claude-sonnet-5*", "claude-opus-4-8*", "claude-opus-4-7*"],+ "providers": ["anthropic"],+ "thinking": {"support": "not_supported"},+ "reasoning": {"support": "supported", "levels": ["low", "medium", "high", "xhigh", "max"], "default": "high"},+ "notes": "Adaptive thinking is always on; effort sets how much. The API's default effort is high.",+ "source": "https://platform.claude.com/docs/en/build-with-claude/effort"+ },+ {+ "match": ["claude-mythos-preview*", "claude-opus-4-6*", "claude-sonnet-4-6*"],+ "providers": ["anthropic"],+ "thinking": {"support": "not_supported"},+ "reasoning": {"support": "supported", "levels": ["low", "medium", "high", "max"], "default": "high"},+ "source": "https://platform.claude.com/docs/en/build-with-claude/effort"+ },+ {+ "match": ["claude-opus-4-5*"],+ "providers": ["anthropic"],+ "thinking": {"support": "not_supported"},+ "reasoning": {"support": "supported", "levels": ["low", "medium", "high"], "default": "high"},+ "source": "https://platform.claude.com/docs/en/build-with-claude/effort"+ },+ {+ "match": ["gpt-5*"],+ "providers": ["openai", "openai-codex"],+ "thinking": {"support": "not_supported"},+ "reasoning": {"support": "supported", "levels": ["low", "medium", "high"], "default": "medium"},+ "notes": "Native OpenAI runs through the Responses API, where effort applies with tools. The server's default is medium.",+ "source": "https://platform.openai.com/docs/guides/reasoning"+ },+ {+ "match": ["moonshotai/kimi-k3*", "kimi-k3*"],+ "thinking": {"support": "not_supported"},+ "reasoning": {"support": "supported", "levels": ["low", "high", "max"], "default": "max"},+ "notes": "Moonshot and Together document low, high and max; the default is max.",+ "source": "https://platform.moonshot.ai/docs"+ },+ {+ "match": ["gpt-oss*", "openai/gpt-oss*"],+ "providers": ["ollama"],+ "thinking": {"support": "not_supported"},+ "reasoning": {"support": "supported", "levels": ["low", "medium", "high"], "default": "medium"},+ "notes": "gpt-oss takes a reasoning level, not an on/off switch (Ollama's think accepts low, medium, high).",+ "source": "https://docs.ollama.com/capabilities/thinking"+ }+ ]+}diff --git a/coworker/providers/model_controls.py b/coworker/providers/model_controls.pynew file mode 100644index 00000000..4972cd5e--- /dev/null+++ b/coworker/providers/model_controls.py@@ -0,0 +1,181 @@+"""What a user can set per session for a model: a thinking switch and reasoning effort.++Two separate controls, each either supported or not (UX-056):++- Thinking: an on/off switch, for models that have one (Qwen3, Nemotron). Current Claude+ models think adaptively and cannot turn it off, so they do not have this control.+- Reasoning: a level from the model's own list, Faster to Smarter (Claude, GPT-5.x,+ Kimi K3, gpt-oss). There is no "off" level.++Cloud models come from `model_controls.json` next to this file, edited in git with a+source per row. Local models are filled in from what their server reports (Ollama's+capabilities, the llama.cpp chat template) and the recommendation table, unless a row in+the JSON says otherwise. Anything not known to support a control gets `not_supported`:+a control that silently does nothing is worse than no control.++The model's default is the user's saved setting for that model (model_config.py) when+there is one, else the table's.+"""++from __future__ import annotations++import fnmatch+import functools+import json+from dataclasses import dataclass+from enum import Enum+from pathlib import Path+from typing import Any, Optional++from ..config import EFFORT_LEVELS++_TABLE = Path(__file__).with_name("model_controls.json")+++class Support(str, Enum):+ SUPPORTED = "supported"+ NOT_SUPPORTED = "not_supported"+++class EffortLevel(str, Enum):+ """Ordered from faster to smarter."""++ LOW = "low"+ MEDIUM = "medium"+ HIGH = "high"+ XHIGH = "xhigh"+ MAX = "max"+++assert tuple(e.value for e in EffortLevel) == tuple(EFFORT_LEVELS)+++@dataclass(frozen=True)+class ThinkingControl:+ support: Support = Support.NOT_SUPPORTED+ default: Optional[bool] = None++ def as_dict(self) -> dict[str, Any]:+ out: dict[str, Any] = {"support": self.support.value}+ if self.support is Support.SUPPORTED:+ out["default"] = self.default+ return out+++@dataclass(frozen=True)+class ReasoningControl:+ support: Support = Support.NOT_SUPPORTED+ levels: tuple[EffortLevel, ...] = ()+ default: Optional[EffortLevel] = None++ def as_dict(self) -> dict[str, Any]:+ out: dict[str, Any] = {"support": self.support.value}+ if self.support is Support.SUPPORTED:+ out["levels"] = [lvl.value for lvl in self.levels]+ out["default"] = self.default.value if self.default else None+ return out+++@dataclass(frozen=True)+class ModelControls:+ thinking: ThinkingControl = ThinkingControl()+ reasoning: ReasoningControl = ReasoningControl()++ def as_dict(self) -> dict[str, Any]:+ return {"thinking": self.thinking.as_dict(), "reasoning": self.reasoning.as_dict()}+++NONE = ModelControls()+++@dataclass(frozen=True)+class _Row:+ match: tuple[str, ...]+ providers: tuple[str, ...]+ controls: ModelControls+++def _parse_row(raw: dict[str, Any]) -> _Row:+ t = raw.get("thinking") or {}+ r = raw.get("reasoning") or {}+ thinking = ThinkingControl(Support(t.get("support", "not_supported")), t.get("default"))+ levels = tuple(EffortLevel(x) for x in (r.get("levels") or []))+ default = EffortLevel(r["default"]) if r.get("default") else None+ if default is not None and default not in levels:+ raise ValueError(f"default {default.value!r} is not one of the levels {raw.get('match')}")+ reasoning = ReasoningControl(Support(r.get("support", "not_supported")), levels, default)+ if reasoning.support is Support.SUPPORTED and not levels:+ raise ValueError(f"reasoning supported without levels {raw.get('match')}")+ return _Row(+ tuple(p.lower() for p in raw.get("match") or ()),+ tuple(raw.get("providers") or ()),+ ModelControls(thinking, reasoning),+ )++[email protected]_cache(maxsize=1)+def _rows() -> tuple[_Row, ...]:+ try:+ raw = json.loads(_TABLE.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ return ()+ return tuple(_parse_row(r) for r in raw.get("models") or ())+++def table_row(provider: str, bare_model: str) -> Optional[ModelControls]:+ """The JSON row for a model, or None. `bare_model` has no provider prefix."""+ name = bare_model.lower()+ for row in _rows():+ if row.providers and provider not in row.providers:+ continue+ if any(fnmatch.fnmatch(name, pattern) for pattern in row.match):+ return row.controls+ return None+++def controls_for(+ provider: str,+ bare_model: str,+ *,+ local: bool = False,+ server_thinking: Optional[bool] = None,+ recommended_thinking: Optional[tuple[bool, bool]] = None,+ saved: Optional[dict[str, Any]] = None,+) -> ModelControls:+ """The controls a model has, with its defaults.++ `local`: the provider is a server on the user's machine. Then `server_thinking` is+ what the server said about thinking (None when it did not say) and+ `recommended_thinking` is the recommendation table's (available, default).+ `saved`: the user's saved settings for this model (model_config.get), whose+ `thinking` / `reasoning_effort` become the defaults."""+ saved = saved or {}+ row = table_row(provider, bare_model)+ if row is not None:+ controls = row+ elif local:+ available = server_thinking+ rec_default = None+ if recommended_thinking is not None:+ rec_available, rec_default = recommended_thinking+ if available is None:+ available = rec_available+ if available:+ # A thinking model thinks unless told not to (Ollama, llama.cpp templates).+ default = True if rec_default is None else bool(rec_default)+ controls = ModelControls(ThinkingControl(Support.SUPPORTED, default), ReasoningControl())+ else:+ controls = NONE+ else:+ controls = NONE+ return _with_saved_defaults(controls, saved)+++def _with_saved_defaults(controls: ModelControls, saved: dict[str, Any]) -> ModelControls:+ thinking, reasoning = controls.thinking, controls.reasoning+ if thinking.support is Support.SUPPORTED and isinstance(saved.get("thinking"), bool):+ thinking = ThinkingControl(Support.SUPPORTED, saved["thinking"])+ effort = saved.get("reasoning_effort")+ if reasoning.support is Support.SUPPORTED and effort in {lvl.value for lvl in reasoning.levels}:+ reasoning = ReasoningControl(Support.SUPPORTED, reasoning.levels, EffortLevel(effort))+ return ModelControls(thinking, reasoning)diff --git a/coworker/providers/registry.py b/coworker/providers/registry.pyindex 411fe522..e75b62bf 100644--- a/coworker/providers/registry.py+++ b/coworker/providers/registry.py@@ -213,12 +213,20 @@ def _local_server(name: str):"""Builder for llama.cpp and vLLM (providers/local_server.py): the user's own server,reached through its `/v1`, with an optional key. Without a key the server takes anyvalue, so a placeholder goes out."""- from .local_server import PLACEHOLDER_KEY, remember_server, v1_base+ from .local_server import PLACEHOLDER_KEY, remember_server, thinking_as_template_kwargs, v1_base++ class _LocalServerProvider(OpenAIProvider):+ # The thinking switch, in the form these servers read.+ def complete(self, **kwargs: Any):+ return super().complete(**thinking_as_template_kwargs(kwargs))++ def stream(self, **kwargs: Any):+ return super().stream(**thinking_as_template_kwargs(kwargs))def build(profile: dict[str, Any], secrets: Any) -> ProviderClient:key = ((profile or {}).get("api_key") or "").strip() or PLACEHOLDER_KEYremember_server(name, (profile or {}).get("base_url"), key if key != PLACEHOLDER_KEY else None)- return OpenAIProvider(api_key=key, base_url=v1_base(name, (profile or {}).get("base_url")))+ return _LocalServerProvider(api_key=key, base_url=v1_base(name, (profile or {}).get("base_url")))return builddiff --git a/coworker/server/app.py b/coworker/server/app.pyindex 86aa10b8..df526eed 100644--- a/coworker/server/app.py+++ b/coworker/server/app.py@@ -481,8 +481,8 @@ def create_app(manager: SessionManager) -> FastAPI:return manager.set_unattended(session_id, value)@app.get("/v1/sessions/{session_id}/model-settings")- def session_model_settings(session_id: str) -> dict[str, Any]:- return manager.session_model_settings(session_id)+ def session_model_settings(session_id: str, model: str = "") -> dict[str, Any]:+ return manager.session_model_settings(session_id, model)@app.post("/v1/sessions/{session_id}/model-settings")def set_session_model_settings(session_id: str, body: dict) -> dict[str, Any]:diff --git a/coworker/server/manager.py b/coworker/server/manager.pyindex 89ec1e56..b4298ea0 100644--- a/coworker/server/manager.py+++ b/coworker/server/manager.py@@ -6146,58 +6146,103 @@ class SessionManager:passdef set_session_model_settings(self, session_id: str, values: dict[str, Any]) -> dict[str, Any]:- """This session's thinking switch or effort level (UX-055: the ⚙ beside the model- in the composer). Overrides the model's saved setting for this session only;- None puts the model's setting back. Other sessions are untouched."""+ """This session's thinking switch or reasoning effort (UX-056: the brain and the+ effort pill in the composer). Overrides the model's setting for this session only;+ None puts the model's setting back. Other sessions are untouched. A value the model+ does not take is refused."""engine = self._engines.get(session_id)if engine is None:return {"ok": False, "error": "session not running"}+ controls = self.model_controls(engine.model)+ defaults = _model_config.model_settings_for(engine.model)settings = dict(engine.model_settings)if "reasoning_effort" in values:effort = values["reasoning_effort"]if effort is None:- settings.pop("reasoning_effort", None)- elif isinstance(effort, str) and effort.strip():- settings["reasoning_effort"] = effort.strip()+ if defaults.get("reasoning_effort"):+ settings["reasoning_effort"] = defaults["reasoning_effort"]+ else:+ settings.pop("reasoning_effort", None)+ elif controls["reasoning"]["support"] == "supported" and effort in controls["reasoning"]["levels"]:+ settings["reasoning_effort"] = effortelse:- return {"ok": False, "error": "reasoning_effort must be text"}+ return {"ok": False, "error": f"{engine.model} does not take reasoning effort {effort!r}"}if "thinking" in values:think = values["thinking"]extra = dict(settings.get("extra_body") or {})if think is None:- extra.pop("think", None)- elif isinstance(think, bool):+ default_think = (defaults.get("extra_body") or {}).get("think")+ if isinstance(default_think, bool):+ extra["think"] = default_think+ else:+ extra.pop("think", None)+ elif isinstance(think, bool) and controls["thinking"]["support"] == "supported":extra["think"] = thinkelse:- return {"ok": False, "error": "thinking must be true or false"}+ return {"ok": False, "error": f"{engine.model} has no thinking switch"}if extra:settings["extra_body"] = extraelse:settings.pop("extra_body", None)- if "thinking" in values or "reasoning_effort" in values:- session_model = _model_config.model_settings_for(engine.model)- # Nothing overridden any more → back to the model's own settings.- if "reasoning_effort" not in settings and not (settings.get("extra_body") or {}).get("think") in (True, False):- for key in ("reasoning_effort",):- if key in session_model:- settings[key] = session_model[key]- if "extra_body" in session_model and "extra_body" not in settings:- settings["extra_body"] = session_model["extra_body"]engine.model_settings = settingsreturn {"ok": True, "session_id": session_id, **self.session_model_settings(session_id)}- def session_model_settings(self, session_id: str) -> dict[str, Any]:- """What this session sends for thinking and effort right now."""+ def session_model_settings(self, session_id: str, model: str = "") -> dict[str, Any]:+ """What this session sends for thinking and reasoning effort right now (None = the+ model's default), and which of the two controls the model has (UX-056). `model`+ is asked about when the session has not started yet."""engine = self._engines.get(session_id)- if engine is None:- return {"thinking": None, "reasoning_effort": None}- settings = engine.model_settings or {}+ settings = (engine.model_settings if engine else None) or {}think = (settings.get("extra_body") or {}).get("think")+ controls = self.model_controls((engine.model if engine else "") or model)+ session_model = _model_config.model_settings_for(engine.model) if engine else {}+ default_think = (session_model.get("extra_body") or {}).get("think")return {- "thinking": think if isinstance(think, bool) else None,- "reasoning_effort": settings.get("reasoning_effort"),+ # Only what this session changed; the model's own setting reads as None.+ "thinking": think if isinstance(think, bool) and think != default_think else None,+ "reasoning_effort": (+ settings.get("reasoning_effort")+ if settings.get("reasoning_effort") != session_model.get("reasoning_effort")+ else None+ ),+ "controls": controls,}+ def model_controls(self, model: str) -> dict[str, Any]:+ """The thinking switch and reasoning-effort levels a model has, with its defaults+ (providers/model_controls.py). Local models: from what their server reports."""+ from ..providers import local_server, model_controls, ollama_facts+ from ..providers.recommended import recommendation_for++ if not model:+ return model_controls.NONE.as_dict()+ provider = self._model_provider(model)+ bare = model.split(":", 1)[1] if (provider != "openai" or model.startswith("openai:")) else model+ d = get_descriptor(provider)+ local = d is not None and d.kind == "local"+ server_thinking = None+ if local:+ try:+ profile = self.secrets.get(f"provider:{provider}") or {}+ rows = (+ ollama_facts.model_facts(profile.get("base_url"))+ if provider == "ollama"+ else local_server.model_facts(provider, profile.get("base_url"), profile.get("api_key"))+ )+ server_thinking = next((r.get("thinking") for r in rows if r.get("model") == model), None)+ except Exception:+ server_thinking = None+ rec = recommendation_for(model)+ controls = model_controls.controls_for(+ provider,+ bare,+ local=local,+ server_thinking=server_thinking,+ recommended_thinking=(rec.thinking_available, rec.thinking_default) if rec else None,+ saved=_model_config.get(model),+ )+ return controls.as_dict()+def set_unattended(self, session_id: str, value: Any) -> dict[str, Any]:"""Set the session's attendance (attended / inbox / auto, or the legacy boolean),with an audit row. Note this changes only WHO ANSWERS when the agent asks, neverdiff --git a/pyproject.toml b/pyproject.tomlindex e08065bf..68880fda 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -72,6 +72,7 @@ coworker = ["personas/builtin/*/manifest.md","personas/builtin/*/skills/*/SKILL.md","headless/*.yaml",+ "providers/*.json",][tool.pytest.ini_options]diff --git a/surfaces/gui/e2e/session-model-settings.spec.ts b/surfaces/gui/e2e/session-model-settings.spec.tsnew file mode 100644index 00000000..3bfcdaa2--- /dev/null+++ b/surfaces/gui/e2e/session-model-settings.spec.ts@@ -0,0 +1,97 @@+import { expect, type Page } from "@playwright/test";+import { test } from "./fixtures";++// UX-056: beside the model, a grey reasoning-effort pill (slider over the model's own+// levels) and a brain for the thinking switch — each only when the model has it.+const NONE = { thinking: { support: "not_supported" }, reasoning: { support: "not_supported" } };+const CLAUDE = {+ thinking: { support: "not_supported" },+ reasoning: { support: "supported", levels: ["low", "medium", "high", "xhigh", "max"], default: "high" },+};+const NEMOTRON = { thinking: { support: "supported", default: true }, reasoning: { support: "not_supported" } };++async function serve(page: Page, controls: object) {+ const state = { thinking: null as boolean | null, reasoning_effort: null as string | null };+ const posted: object[] = [];+ await page.route(/\/v1\/sessions\/[^/]+\/model-settings/, async (route) => {+ if (route.request().method() === "POST") {+ const body = route.request().postDataJSON();+ posted.push(body);+ Object.assign(state, body);+ return route.fulfill({ json: { ok: true, ...state, controls } });+ }+ return route.fulfill({ json: { ...state, controls } });+ });+ return posted;+}++test("nothing beside the model when it has neither control", async ({ page }) => {+ await serve(page, NONE);+ await page.goto("/");+ await expect(page.getByPlaceholder(/Ask the coworker/)).toBeVisible();+ await expect(page.getByTestId("effort-pill")).toHaveCount(0);+ await expect(page.getByTestId("thinking-toggle")).toHaveCount(0);+});++test("reasoning effort: the pill shows the level; the slider marks the default and resets", async ({ page }) => {+ const posted = await serve(page, CLAUDE);+ await page.goto("/");+ const pill = page.getByTestId("effort-pill");+ await expect(pill).toHaveText("High");+ await pill.click();+ const menu = page.getByTestId("effort-menu");+ await expect(menu).toContainText("Reasoning effort");+ await expect(menu).toContainText("Extra high");+ await expect(menu).toContainText("Default");+ await expect(menu).not.toContainText("Off");+ await expect(page.getByTestId("effort-reset")).toHaveCount(0);+ // The lowest level sits at the very left end of the track: the thumb touches it.+ const slider = page.getByTestId("effort-slider");+ const track = (await slider.boundingBox())!;+ await page.mouse.click(track.x + 4, track.y + track.height / 2);+ await expect(pill).toHaveText("Low");+ const thumb = (await page.getByTestId("effort-thumb").boundingBox())!;+ expect(thumb.x - track.x).toBeLessThanOrEqual(4);+ await expect(page.getByTestId("effort-reset")).toHaveText("Reset to High");+ await page.getByTestId("effort-reset").click();+ await expect(pill).toHaveText("High");+ expect(posted).toEqual([{ reasoning_effort: "low" }, { reasoning_effort: null }]);+});++test("reasoning effort: drag to the far right end, and the keys step and jump", async ({ page }) => {+ const posted = await serve(page, CLAUDE);+ await page.goto("/");+ await page.getByTestId("effort-pill").click();+ const slider = page.getByTestId("effort-slider");+ const track = (await slider.boundingBox())!;+ const y = track.y + track.height / 2;+ // Drag from the default all the way past the right end.+ await page.mouse.move(track.x + track.width / 2, y);+ await page.mouse.down();+ await page.mouse.move(track.x + track.width + 40, y, { steps: 5 });+ await page.mouse.up();+ await expect(page.getByTestId("effort-pill")).toHaveText("Max");+ const thumb = (await page.getByTestId("effort-thumb").boundingBox())!;+ expect(track.x + track.width - (thumb.x + thumb.width)).toBeLessThanOrEqual(4);+ await slider.focus();+ await page.keyboard.press("ArrowLeft");+ await expect(page.getByTestId("effort-pill")).toHaveText("Extra high");+ await page.keyboard.press("Home");+ await expect(page.getByTestId("effort-pill")).toHaveText("Low");+ await expect(slider).toHaveAttribute("aria-valuetext", "Low");+ expect(posted).toEqual([{ reasoning_effort: "max" }, { reasoning_effort: "xhigh" }, { reasoning_effort: "low" }]);+ await expect(page.getByTestId("thinking-toggle")).toHaveCount(0);+});++test("thinking: the brain flips it and back to the default", async ({ page }) => {+ const posted = await serve(page, NEMOTRON);+ await page.goto("/");+ const brain = page.getByTestId("thinking-toggle");+ await expect(brain).toHaveAttribute("aria-pressed", "true");+ await brain.click();+ await expect(brain).toHaveAttribute("aria-pressed", "false");+ await brain.click();+ await expect(brain).toHaveAttribute("aria-pressed", "true");+ expect(posted).toEqual([{ thinking: false }, { thinking: null }]);+ await expect(page.getByTestId("effort-pill")).toHaveCount(0);+});diff --git a/surfaces/gui/src/api.ts b/surfaces/gui/src/api.tsindex fbb3fb9d..4591d423 100644--- a/surfaces/gui/src/api.ts+++ b/surfaces/gui/src/api.ts@@ -2545,15 +2545,29 @@ export async function removeModelConfig(model: string): Promise<{ ok: boolean }>}/** This session's thinking switch and effort level (UX-055, the ⚙ beside the model). */-export async function getSessionModelSettings(sessionId: string): Promise<{ thinking: boolean | null; reasoning_effort: string | null }> {- const res = await fetch(`${httpBase()}/v1/sessions/${encodeURIComponent(sessionId)}/model-settings`);+// UX-056: what a model lets the user set per session (providers/model_controls.py).+export interface ModelControls {+ thinking: { support: "supported" | "not_supported"; default?: boolean | null };+ reasoning: { support: "supported" | "not_supported"; levels?: string[]; default?: string | null };+}++export interface SessionModelControls {+ // What this session changed; null = the model's default.+ thinking: boolean | null;+ reasoning_effort: string | null;+ controls: ModelControls;+}++export async function getSessionModelSettings(sessionId: string, model = ""): Promise<SessionModelControls> {+ const q = model ? `?model=${encodeURIComponent(model)}` : "";+ const res = await fetch(`${httpBase()}/v1/sessions/${encodeURIComponent(sessionId)}/model-settings${q}`);return res.json();}export async function setSessionModelSettings(sessionId: string,values: { thinking?: boolean | null; reasoning_effort?: string | null },-): Promise<{ ok: boolean; error?: string; thinking?: boolean | null; reasoning_effort?: string | null }> {+): Promise<{ ok: boolean; error?: string } & Partial<SessionModelControls>> {const res = await fetch(`${httpBase()}/v1/sessions/${encodeURIComponent(sessionId)}/model-settings`, {method: "POST",headers: { "Content-Type": "application/json" },diff --git a/surfaces/gui/src/components/Composer.tsx b/surfaces/gui/src/components/Composer.tsxindex ea7639b3..06aa1a45 100644--- a/surfaces/gui/src/components/Composer.tsx+++ b/surfaces/gui/src/components/Composer.tsx@@ -3,7 +3,7 @@ import { getI18n, useTranslation } from "react-i18next";import type { Attachment, SessionUsage } from "../types";import { isPdfFile, readFile } from "../attach";import { ProjectBindMenu } from "./ProjectBindMenu";-import { getSessionModelSettings, getSettings, inspectPdf, sessionSkills, setSessionModelSettings, type SessionSkillRow } from "../api";+import { getSessionModelSettings, getSettings, inspectPdf, sessionSkills, setSessionModelSettings, type ModelControls, type SessionSkillRow } from "../api";import { formatTokens, totalTokens } from "../usage";import { Dropdown, type Option } from "./Dropdown";import { Icon } from "./Icon";@@ -846,7 +846,7 @@ export function Composer(props: Props) {))}{!props.compact && modelsLoaded && props.sessionId && (- <SessionModelSettings sessionId={props.sessionId} model={props.model} local={isLocalModel(props.model)} onPickModel={props.onPickModel} />+ <SessionModelControls sessionId={props.sessionId} model={props.model} onPickModel={props.onPickModel} />)}{/* mic — immediately before send (owner call, DMG #28 walkthrough) */}@@ -1113,80 +1113,191 @@ function AttachChip({ a, onRemove }: { a: Attachment; onRemove: () => void }) {}-// UX-055: the ⚙ beside the model pill. This session's thinking switch (a local model)-// or effort level (a cloud model), over the model's own setting; other sessions keep-// theirs. The link at the bottom opens the model's defaults in Models & Keys.-function SessionModelSettings({+// UX-056: beside the model, this session's reasoning effort (a grey pill showing the+// level; click for a slider over the model's own levels) and thinking switch (a brain;+// click to flip). Each appears only when the model has it — the server says which+// (providers/model_controls.py). The model's default is a tick on the track and+// "Default" under its name; a session that differs gets a small dot and a Reset.+// No accent colour here: the composer stays muted.+function SessionModelControls({sessionId,model,- local,onPickModel,}: {sessionId: string;model: string;- local: boolean;onPickModel?: () => void;}) {const { t } = useTranslation();const [open, setOpen] = useState(false);- const [state, setState] = useState<{ thinking: boolean | null; reasoning_effort: string | null } | null>(null);+ const [controls, setControls] = useState<ModelControls | null>(null);+ const [thinking, setThinking] = useState<boolean | null>(null);+ const [effort, setEffort] = useState<string | null>(null);+ const [drag, setDrag] = useState<number | null>(null);useEffect(() => {- if (!open) return;- getSessionModelSettings(sessionId).then(setState).catch(() => setState({ thinking: null, reasoning_effort: null }));- }, [open, sessionId, model]);+ let live = true;+ setControls(null);+ getSessionModelSettings(sessionId, model)+ .then((s) => {+ if (!live) return;+ setControls(s.controls || null);+ setThinking(s.thinking ?? null);+ setEffort(s.reasoning_effort ?? null);+ })+ .catch(() => live && setControls(null));+ return () => {+ live = false;+ };+ }, [sessionId, model]);const apply = (values: { thinking?: boolean | null; reasoning_effort?: string | null }) =>setSessionModelSettings(sessionId, values).then((r) => {- if (r.ok) setState({ thinking: r.thinking ?? null, reasoning_effort: r.reasoning_effort ?? null });+ if (!r.ok) return;+ setThinking(r.thinking ?? null);+ setEffort(r.reasoning_effort ?? null);});- const seg = (on: boolean, label: string, onClick: () => void) => (- <button className={"px-2.5 py-0.5 text-meta " + (on ? "bg-accent text-panel" : "text-muted hover:text-ink")} onClick={onClick}>- {label}- </button>- );+ if (!controls) return null;+ const think = controls.thinking.support === "supported" ? controls.thinking : null;+ const reason = controls.reasoning.support === "supported" && (controls.reasoning.levels || []).length ? controls.reasoning : null;+ if (!think && !reason) return null;+ const levels = reason?.levels || [];+ const label = (lvl: string) => t(`composer.model.effort_${lvl}`, { defaultValue: lvl });++ const thinkOn = thinking ?? !!think?.default;+ const thinkChanged = thinking !== null && thinking !== !!think?.default;+ const level = effort ?? reason?.default ?? levels[0];+ const effortChanged = effort !== null && effort !== reason?.default;+ const at = Math.max(0, levels.indexOf(level));+ // While dragging, the thumb follows the pointer's nearest level; it saves on release.+ const shown = drag ?? at;+ // The first and last levels sit at the very ends of the track: the thumb (30px, 3px+ // inset) touches the edge there. A stop's centre is 18px in from each end at most.+ const frac = (i: number) => (levels.length > 1 ? i / (levels.length - 1) : 0.5);+ const centre = (i: number) => `calc(18px + (100% - 36px) * ${frac(i)})`;+ const choose = (i: number) => {+ const lvl = levels[Math.max(0, Math.min(levels.length - 1, i))];+ if (lvl && lvl !== level) apply({ reasoning_effort: lvl === reason?.default ? null : lvl });+ };+ const nearest = (clientX: number, el: HTMLElement) => {+ const r = el.getBoundingClientRect();+ const f = (clientX - r.left - 18) / Math.max(1, r.width - 36);+ return Math.max(0, Math.min(levels.length - 1, Math.round(f * (levels.length - 1))));+ };+ const dot = <span className="w-[5px] h-[5px] rounded-full bg-muted" aria-hidden />;+return (- <div className="relative shrink-0">- <button- className={"w-7 h-7 grid place-items-center rounded-md hover:bg-paper " + (open ? "text-accent" : "text-faint hover:text-ink")}- title={t("composer.model.session_settings")}- aria-label={t("composer.model.session_settings")}- onClick={() => setOpen((v) => !v)}- data-testid="session-model-settings"- >- ⚙- </button>- {open && (- <>- <div className="fixed inset-0 z-30" onClick={() => setOpen(false)} />- <div className="absolute z-40 bottom-full mb-1 right-0 w-[300px] rounded-xl border border-line bg-panel shadow-2xl p-3" data-testid="session-model-settings-menu">- <div className="text-label text-faint font-semibold tracking-wide uppercase mb-2">{t("composer.model.this_session")}</div>- {state && local && (- <div className="flex items-center text-ui">- {t("composer.model.thinking_label")}- <span className="ml-auto flex rounded-md border border-lineStrong overflow-hidden">- {seg(state.thinking === false, t("composer.model.off"), () => apply({ thinking: false }))}- {seg(state.thinking === true, t("composer.model.on"), () => apply({ thinking: true }))}- {seg(state.thinking === null, t("composer.model.models_setting"), () => apply({ thinking: null }))}- </span>- </div>- )}- {state && !local && (- <div className="flex items-center text-ui">- {t("composer.model.effort_label")}- <span className="ml-auto flex rounded-md border border-lineStrong overflow-hidden">- {(["low", "medium", "high"] as const).map((lvl) => seg(state.reasoning_effort === lvl, t(`composer.model.effort_${lvl}`), () => apply({ reasoning_effort: lvl })))}- {seg(state.reasoning_effort === null, t("composer.model.models_setting"), () => apply({ reasoning_effort: null }))}- </span>+ <>+ {reason && (+ <div className="relative shrink-0">+ <button+ className={"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-meta text-ink " + (open ? "bg-lineStrong/60" : "bg-paper hover:bg-line")}+ title={t("composer.model.effort_label")}+ onClick={() => setOpen((v) => !v)}+ data-testid="effort-pill"+ >+ {effortChanged && dot}+ {label(level)}+ </button>+ {open && (+ <>+ <div className="fixed inset-0 z-30" onClick={() => setOpen(false)} />+ <div className="absolute z-40 bottom-full mb-2 right-0 w-[340px] rounded-2xl border border-line bg-panel shadow-2xl px-[18px] pt-4 pb-3" data-testid="effort-menu">+ <div className="flex items-baseline gap-2 text-ui">+ <span className="text-faint">{t("composer.model.effort_label")}</span>+ <span className="font-semibold">{label(levels[shown] || level)}</span>+ {effortChanged && (+ <button className="ml-auto text-meta text-muted underline underline-offset-2 hover:text-ink" onClick={() => apply({ reasoning_effort: null })} data-testid="effort-reset">+ {t("composer.model.reset_to", { level: label(reason.default || "") })}+ </button>+ )}+ </div>+ <div className="flex justify-between text-meta text-faint mt-3.5 mb-1.5">+ <span>{t("composer.model.faster")}</span>+ <span>{t("composer.model.smarter")}</span>+ </div>+ <div+ className="relative h-[34px] rounded-[10px] bg-paper cursor-pointer touch-none outline-none focus-visible:ring-1 focus-visible:ring-lineStrong"+ role="slider"+ tabIndex={0}+ aria-label={t("composer.model.effort_label")}+ aria-valuemin={0}+ aria-valuemax={levels.length - 1}+ aria-valuenow={shown}+ aria-valuetext={label(levels[shown])}+ onPointerDown={(e) => {+ e.currentTarget.setPointerCapture(e.pointerId);+ setDrag(nearest(e.clientX, e.currentTarget));+ }}+ onPointerMove={(e) => {+ if (drag !== null) setDrag(nearest(e.clientX, e.currentTarget));+ }}+ onPointerUp={(e) => {+ const i = nearest(e.clientX, e.currentTarget);+ setDrag(null);+ choose(i);+ }}+ onPointerCancel={() => setDrag(null)}+ onKeyDown={(e) => {+ const step = { ArrowLeft: -1, ArrowDown: -1, ArrowRight: 1, ArrowUp: 1 }[e.key];+ if (step) choose(at + step);+ else if (e.key === "Home") choose(0);+ else if (e.key === "End") choose(levels.length - 1);+ else return;+ e.preventDefault();+ }}+ data-testid="effort-slider"+ >+ <div className="absolute inset-y-0 left-0 rounded-[10px] bg-lineStrong" style={{ width: `calc(${centre(shown)} + 15px)` }} />+ {levels.map((lvl, i) =>+ i === shown ? null : lvl === reason.default ? (+ <span key={lvl} className="absolute top-1/2 w-[2px] h-3 -mt-1.5 -ml-px rounded-sm bg-muted" style={{ left: centre(i) }} />+ ) : (+ <span key={lvl} className="absolute top-1/2 w-1 h-1 -mt-0.5 -ml-0.5 rounded-full bg-faint" style={{ left: centre(i) }} />+ ),+ )}+ <span+ className={"absolute top-[3px] w-[30px] h-[28px] -ml-[15px] rounded-[9px] bg-panel shadow pointer-events-none " + (drag === null ? "transition-[left]" : "")}+ style={{ left: centre(shown) }}+ data-testid="effort-thumb"+ />+ </div>+ <div className="relative h-[34px] text-[12px] text-faint">+ {levels.map((lvl, i) => (+ <span key={lvl} className={"absolute top-1.5 -translate-x-1/2 whitespace-nowrap text-center " + (i === shown ? "text-ink font-semibold" : "")} style={{ left: centre(i) }}>+ {label(lvl)}+ {lvl === reason.default && <small className="block text-[10.5px] font-normal text-muted">{t("composer.model.default")}</small>}+ </span>+ ))}+ </div>+ <div className="flex justify-between border-t border-line mt-1.5 pt-2.5 text-meta">+ <span className="text-faint">{t("composer.model.this_session_only")}</span>+ {onPickModel && (+ <button className="text-muted hover:text-ink" onClick={() => { setOpen(false); onPickModel(); }}>+ {t("composer.model.model_defaults")}+ </button>+ )}+ </div></div>- )}- <p className="text-meta text-faint mt-2">{t("composer.model.session_only_note")}</p>- {onPickModel && (- <button className="mt-2 text-meta text-accent" onClick={() => { setOpen(false); onPickModel(); }}>- {t("composer.model.change_defaults")}- </button>- )}- </div>- </>+ </>+ )}+ </div>)}- </div>+ {think && (+ <button+ className={"relative w-7 h-7 grid place-items-center rounded-md hover:bg-paper shrink-0 " + (thinkOn ? "text-ink" : "text-faint")}+ title={t(thinkOn ? "composer.model.thinking_on" : "composer.model.thinking_off") + (thinkChanged ? "" : ` · ${t("composer.model.default")}`)}+ aria-label={t("composer.model.thinking_label")}+ aria-pressed={thinkOn}+ onClick={() => {+ const next = !thinkOn;+ apply({ thinking: next === !!think.default ? null : next });+ }}+ data-testid="thinking-toggle"+ >+ <Icon name="brain" size={16} />+ {!thinkOn && <span className="absolute w-[18px] h-[1.6px] bg-faint rotate-[-45deg] rounded-sm" aria-hidden />}+ {thinkChanged && <span className="absolute top-[3px] right-[3px] w-[5px] h-[5px] rounded-full bg-muted" aria-hidden />}+ </button>+ )}+ </>);}diff --git a/surfaces/gui/src/components/Icon.tsx b/surfaces/gui/src/components/Icon.tsxindex 0e17504c..ff476e03 100644--- a/surfaces/gui/src/components/Icon.tsx+++ b/surfaces/gui/src/components/Icon.tsx@@ -15,6 +15,7 @@ export type IconName =| "folder"| "folderPlus"| "plus"+ | "brain"| "clock"| "sliders"| "gear"@@ -233,6 +234,15 @@ export function Icon({<path d="M19 14v6M16 17h6" /></svg>);+ case "brain":+ // Adapted from Lucide's "brain" (ISC licence).+ return (+ <svg {...s}>+ <path d="M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z" />+ <path d="M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z" />+ <path d="M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4" />+ </svg>+ );case "plus":return (<svg {...s}>diff --git a/surfaces/gui/src/locales/en.json b/surfaces/gui/src/locales/en.jsonindex 62a05b9f..0d6849a5 100644--- a/surfaces/gui/src/locales/en.json+++ b/surfaces/gui/src/locales/en.json@@ -199,18 +199,21 @@"thinking": "thinking","search": "Search models…","pick_or_configure": "Pick or configure a model…",- "session_settings": "Settings for this session",- "this_session": "This session","thinking_label": "Thinking",- "effort_label": "Effort",- "on": "On",- "off": "Off",- "models_setting": "Default",+ "effort_label": "Reasoning effort","effort_low": "Low","effort_medium": "Medium","effort_high": "High",- "session_only_note": "Other sessions keep the model's own setting.",- "change_defaults": "Change the model's defaults…"+ "effort_xhigh": "Extra high",+ "effort_max": "Max",+ "faster": "Faster",+ "smarter": "Smarter",+ "default": "Default",+ "reset_to": "Reset to {{level}}",+ "this_session_only": "This session only",+ "model_defaults": "Model defaults…",+ "thinking_on": "Thinking on",+ "thinking_off": "Thinking off"},"placeholder_question": "Type your answer — or pick an option above","placeholder_gate": "Reply to adjust the proposal — or use the buttons above",diff --git a/surfaces/gui/src/locales/zh.json b/surfaces/gui/src/locales/zh.jsonindex 18d12c06..dfeef038 100644--- a/surfaces/gui/src/locales/zh.json+++ b/surfaces/gui/src/locales/zh.json@@ -197,18 +197,21 @@"thinking": "思考","search": "搜索模型…","pick_or_configure": "选择或配置模型…",- "session_settings": "此会话的设置",- "this_session": "此会话","thinking_label": "思考","effort_label": "推理强度",- "on": "开",- "off": "关",- "models_setting": "默认","effort_low": "低","effort_medium": "中","effort_high": "高",- "session_only_note": "其他会话保持模型自身的设置。",- "change_defaults": "更改模型的默认设置…"+ "effort_xhigh": "超高",+ "effort_max": "最高",+ "faster": "更快",+ "smarter": "更聪明",+ "default": "默认",+ "reset_to": "恢复为{{level}}",+ "this_session_only": "仅此会话",+ "model_defaults": "模型默认设置…",+ "thinking_on": "思考:开",+ "thinking_off": "思考:关"},"placeholder_question": "输入你的回答 —— 或选择上方的选项","placeholder_gate": "回复以调整提案 —— 或使用上方按钮",diff --git a/tests/test_local_server.py b/tests/test_local_server.pyindex 57e1daa5..d896372d 100644--- a/tests/test_local_server.py+++ b/tests/test_local_server.py@@ -111,3 +111,35 @@ def test_the_server_offers_and_adopts_a_local_servers_model(tmp_path, monkeypatc# A server started without tool calling offers nothing to the picker.rows[0]["tools"] = Falseassert mgr._local_server_models("llamacpp") == []+++def test_thinking_switch_reaches_llama_cpp_and_vllm_as_template_kwargs(monkeypatch):+ """Ollama reads `think`; llama.cpp and vLLM read the chat template's enable_thinking."""+ from coworker.providers import openai_provider++ sent = {}+ monkeypatch.setattr(openai_provider.OpenAIProvider, "complete", lambda self, **kw: sent.update(kw) or "ok")+ for name in ("llamacpp", "vllm"):+ client = get_descriptor(name).build({}, None)+ client.complete(model="m", messages=[], max_tokens=10, extra_body={"think": False})+ assert sent["extra_body"] == {"chat_template_kwargs": {"enable_thinking": False}}+ assert sent["max_tokens"] == 10+ sent.clear()+ client.complete(model="m", messages=[])+ assert "extra_body" not in sent+ assert local_server.thinking_as_template_kwargs(+ {"extra_body": {"think": True, "chat_template_kwargs": {"x": 1}}}+ ) == {"extra_body": {"chat_template_kwargs": {"x": 1, "enable_thinking": True}}}+++def test_a_chat_template_with_enable_thinking_means_a_thinking_switch(monkeypatch):+ def handler(request: httpx.Request) -> httpx.Response:+ if request.url.path == "/v1/models":+ return httpx.Response(200, json={"data": [{"id": "some-unlisted-model.gguf", "meta": {}}]})+ if request.url.path == "/props":+ return httpx.Response(200, json={"chat_template": "{% if enable_thinking %}<think>{% endif %}"})+ return httpx.Response(404)++ _fake_http(monkeypatch, handler)+ (row,) = local_server.model_facts("llamacpp", "http://localhost:8080", fresh=True)+ assert row["thinking"] is True and row["recommendation"] is Nonediff --git a/tests/test_model_config.py b/tests/test_model_config.pyindex d96a5562..dc8e2e25 100644--- a/tests/test_model_config.py+++ b/tests/test_model_config.py@@ -230,7 +230,7 @@ def test_only_tool_capable_ollama_models_join_the_picker(tmp_path, monkeypatch):assert mgr._ollama_models() == ["ollama:qwen3-coder:30b", "ollama:old-server-model"]-def test_a_session_can_switch_thinking_and_effort_for_itself(tmp_path):+def test_a_session_can_switch_thinking_for_itself(tmp_path):from types import SimpleNamespacefrom coworker.server.manager import SessionManager@@ -238,15 +238,39 @@ def test_a_session_can_switch_thinking_and_effort_for_itself(tmp_path):mgr = SessionManager(data_dir=tmp_path)engine = SimpleNamespace(model="ollama:nemotron-3.5-lightning:30b", model_settings={"max_tokens": 16000, "extra_body": {"think": True}})mgr._engines["s1"] = engine- assert mgr.session_model_settings("s1") == {"thinking": True, "reasoning_effort": None}+ got = mgr.session_model_settings("s1")+ assert (got["thinking"], got["reasoning_effort"]) == (None, None) # at the model's default+ assert got["controls"]["thinking"] == {"support": "supported", "default": True}out = mgr.set_session_model_settings("s1", {"thinking": False})- assert out["ok"] and engine.model_settings["extra_body"] == {"think": False}+ assert out["ok"] and out["thinking"] is False+ assert engine.model_settings["extra_body"] == {"think": False}assert engine.model_settings["max_tokens"] == 16000 # the rest stays- out = mgr.set_session_model_settings("s1", {"reasoning_effort": "high"})- assert out["reasoning_effort"] == "high"- # Back to the model's own settings.- mgr.set_session_model_settings("s1", {"thinking": None, "reasoning_effort": None})- assert engine.model_settings.get("extra_body") == {"think": True}- assert "reasoning_effort" not in engine.model_settings+ # Nemotron has no effort levels: refused, nothing changes.+ assert mgr.set_session_model_settings("s1", {"reasoning_effort": "high"})["ok"] is False+ # Back to the model's own setting.+ out = mgr.set_session_model_settings("s1", {"thinking": None})+ assert out["thinking"] is None and engine.model_settings["extra_body"] == {"think": True}assert mgr.set_session_model_settings("nope", {"thinking": True}) == {"ok": False, "error": "session not running"}assert mgr.set_session_model_settings("s1", {"thinking": "yes"})["ok"] is False+++def test_a_session_can_set_reasoning_effort_within_the_model_levels(tmp_path):+ from types import SimpleNamespace++ from coworker.server.manager import SessionManager++ mgr = SessionManager(data_dir=tmp_path)+ engine = SimpleNamespace(model="anthropic:claude-fable-5-1", model_settings={})+ mgr._engines["s1"] = engine+ controls = mgr.session_model_settings("s1")["controls"]+ assert controls["reasoning"] == {"support": "supported", "levels": ["low", "medium", "high", "xhigh", "max"], "default": "high"}+ assert controls["thinking"] == {"support": "not_supported"}+ out = mgr.set_session_model_settings("s1", {"reasoning_effort": "low"})+ assert out["ok"] and out["reasoning_effort"] == "low" and engine.model_settings["reasoning_effort"] == "low"+ assert mgr.set_session_model_settings("s1", {"reasoning_effort": "none"})["ok"] is False # no Off+ assert mgr.set_session_model_settings("s1", {"thinking": False})["ok"] is False # no switch+ out = mgr.set_session_model_settings("s1", {"reasoning_effort": None})+ assert out["reasoning_effort"] is None and "reasoning_effort" not in engine.model_settings+ # A level saved for the model becomes its default, and Reset goes back to it.+ model_config.set("anthropic:claude-fable-5-1", {"reasoning_effort": "max"})+ assert mgr.model_controls("anthropic:claude-fable-5-1")["reasoning"]["default"] == "max"diff --git a/tests/test_model_controls.py b/tests/test_model_controls.pynew file mode 100644index 00000000..2f621234--- /dev/null+++ b/tests/test_model_controls.py@@ -0,0 +1,69 @@+"""Which per-session controls a model has (UX-056): a thinking switch and reasoning effort."""++from __future__ import annotations++import pytest++from coworker.providers import model_controls as mc+from coworker.providers import effort+++def test_the_table_parses_and_every_default_is_one_of_its_levels():+ rows = mc._rows()+ assert rows, "model_controls.json did not load"+ for row in rows:+ r = row.controls.reasoning+ if r.support is mc.Support.SUPPORTED:+ assert r.levels and r.default in r.levels+++ "provider, model, levels, default",+ [+ ("anthropic", "claude-fable-5-1", ["low", "medium", "high", "xhigh", "max"], "high"),+ ("anthropic", "claude-opus-4-6", ["low", "medium", "high", "max"], "high"),+ ("anthropic", "claude-opus-4-5-20251101", ["low", "medium", "high"], "high"),+ ("openai", "gpt-5.6-sol", ["low", "medium", "high"], "medium"),+ ("openai-codex", "gpt-5.6-terra", ["low", "medium", "high"], "medium"),+ ("openrouter", "moonshotai/kimi-k3", ["low", "high", "max"], "max"),+ ("together", "moonshotai/Kimi-K3", ["low", "high", "max"], "max"),+ ("ollama", "gpt-oss:20b", ["low", "medium", "high"], "medium"),+ ],+)+def test_cloud_and_listed_models_have_reasoning_effort_and_no_switch(provider, model, levels, default):+ c = mc.controls_for(provider, model, local=provider == "ollama", server_thinking=True).as_dict()+ assert c["reasoning"] == {"support": "supported", "levels": levels, "default": default}+ assert c["thinking"] == {"support": "not_supported"}+++def test_claude_levels_agree_with_what_the_provider_sends():+ """The table and effort.py's wire mapping must not drift apart."""+ for model in ("claude-fable-5-1", "claude-opus-4-6", "claude-opus-4-5"):+ levels = tuple(lvl.value for lvl in mc.controls_for("anthropic", model).reasoning.levels)+ assert levels == effort._anthropic_supported(model)+++def test_local_thinking_models_get_a_switch_from_the_server_or_the_table():+ on = mc.controls_for("ollama", "qwen3:8b", local=True, server_thinking=True).as_dict()+ assert on == {"thinking": {"support": "supported", "default": True}, "reasoning": {"support": "not_supported"}}+ # The server did not say; the recommendation table knows the model thinks.+ rec = mc.controls_for("llamacpp", "nemotron-3.5-lightning", local=True, recommended_thinking=(True, True))+ assert rec.thinking.support is mc.Support.SUPPORTED and rec.thinking.default is True+ # Not a thinking model, or nobody says: no switch.+ assert mc.controls_for("ollama", "llama3.1:8b", local=True, server_thinking=False) == mc.NONE+ assert mc.controls_for("vllm", "some-model", local=True) == mc.NONE+++def test_unknown_or_unverified_models_have_neither_control():+ assert mc.controls_for("deepseek", "deepseek-chat") == mc.NONE+ assert mc.controls_for("bedrock", "anthropic.claude-fable-5-1") == mc.NONE # not verified there+ assert mc.controls_for("llamacpp", "gpt-oss-20b.gguf", local=True) == mc.NONE+++def test_saved_settings_become_the_defaults_only_when_valid():+ c = mc.controls_for("anthropic", "claude-fable-5-1", saved={"reasoning_effort": "max"})+ assert c.reasoning.default is mc.EffortLevel.MAX+ c = mc.controls_for("openai", "gpt-5.6-sol", saved={"reasoning_effort": "max"}) # not a GPT level+ assert c.reasoning.default is mc.EffortLevel.MEDIUM+ c = mc.controls_for("ollama", "qwen3:8b", local=True, server_thinking=True, saved={"thinking": False})+ assert c.thinking.default is False