Skip to content

The agent that grows with you

fix(gateway): keep a session's reasoning choice on a profile-following chat

David Dudok de Witb003b6c8d96e
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index 9a53a629dae..89b91b9364a 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -65,6 +65,9 @@ class LiveSession:
settling: dict = field(default_factory=dict)
# A viewer attached while a guarded deferred pick awaits consent: the next boundary asks again.
reask_pick: bool = False
+ # (principal, effort) of a ``/reasoning`` command that arrived while a turn ran: applied in memory at
+ # once, committed to the policy at the next boundary (gateway/session_setting_commands.py).
+ pending_reasoning: tuple | None = None
# A historic messaging row mounted for reading after its lane moved on (``/new``): ``route`` is
# the lane's CURRENT key, which names another conversation, so nothing route-keyed (agent, Stop,
# turns, eviction) may act through it (gateway/session_route_recovery.py). The lane publishing
@@ -938,8 +941,11 @@ class SessionAuthority:
first = next((row for row in pending if row['status'] == 'queued'), None)
from gateway.config import Platform
if live.source.platform == Platform.LOCAL:
- # A model pick made while the previous turn ran lands here, at the turn boundary.
+ # A reasoning command or a model pick made while the previous turn ran lands here, at the
+ # turn boundary.
from gateway.session_deferred_pick import apply_deferred_pick
+ from gateway.session_setting_commands import apply_pending_reasoning
+ await apply_pending_reasoning(self, ref, live)
await apply_deferred_pick(self, ref, live)
if first is not None and live.source.platform == Platform.LOCAL:
from gateway.session_local_recovery import restore_local_session
diff --git a/gateway/session_commands.py b/gateway/session_commands.py
index 2490004d23d..0eeeb89ce41 100644
--- a/gateway/session_commands.py
+++ b/gateway/session_commands.py
@@ -454,6 +454,11 @@ async def execute_command(connection, ref, params, *, dispatch=False):
prompt = event.text
else:
await before()
+ if canonical == 'reasoning':
+ from gateway.run_config_loaders import GatewayConfigLoadersMixin
+ from gateway.session_setting_commands import commit_reasoning_command
+ await commit_reasoning_command(authority, actor, ref,
+ *GatewayConfigLoadersMixin._parse_reasoning_command_args(arg))
handler = runner._command_handler_table((canonical,))[canonical]
output = await handler(event)
if canonical in _APPROVAL_COMMANDS:
diff --git a/gateway/session_mutation_model.py b/gateway/session_mutation_model.py
index 3a729e61a1f..ef29b6d99a8 100644
--- a/gateway/session_mutation_model.py
+++ b/gateway/session_mutation_model.py
@@ -86,7 +86,7 @@ async def prepare_model(authority, live, payload, prepared):
if 'reasoning' in payload:
# The level picked with the model lands in the same commit (as prepare_reasoning writes it).
from gateway.session_policy import pin_reasoning_effort
- pin_reasoning_effort(frozen, payload['reasoning'])
+ pin_reasoning_effort(frozen, payload['reasoning'], session=True)
if old.follows_profile:
# A committed /model holds while the profile still targets what it targets now (main's
# composer_override_profile); a later profile edit supersedes it.
diff --git a/gateway/session_mutation_policy.py b/gateway/session_mutation_policy.py
index 4d5ee04fcd5..3f99a255952 100644
--- a/gateway/session_mutation_policy.py
+++ b/gateway/session_mutation_policy.py
@@ -20,11 +20,21 @@ def _rebind(authority, prepared, old, policy, **extra):
async def prepare_reasoning(authority, live, payload, prepared):
- """``/reasoning <level>`` for this session: the level ``build_policy`` freezes at creation."""
- from gateway.session_policy import pin_reasoning_effort, restore_policy
+ """``/reasoning <level>`` for this session: the level ``build_policy`` freezes at creation. ``None``
+ (``/reasoning reset``) gives the level back to the profile."""
+ from gateway.session_policy import pin_reasoning_effort, restore_policy, unpin_reasoning
old = restore_policy(prepared['snapshot']['receipt']['policy'])
frozen = old.config()
- pin_reasoning_effort(frozen, payload['effort'])
+ if payload['effort'] is not None:
+ pin_reasoning_effort(frozen, payload['effort'], session=True)
+ else:
+ from pathlib import Path
+ from gateway.run import _load_gateway_config
+ from gateway.session_policy import present_sections
+ # A bypass launch never reads the profile: its reset is the built-in default.
+ profile = {} if old.ignore_user_config else await asyncio.to_thread(lambda: present_sections(
+ _load_gateway_config(Path(authority.db.db_path).resolve().parent / 'config.yaml')))
+ unpin_reasoning(frozen, profile)
return _rebind(authority, prepared, old, replace(old, config_json=json.dumps(frozen)))
diff --git a/gateway/session_mutations.py b/gateway/session_mutations.py
index 3eaf712558e..fa9d10693c5 100644
--- a/gateway/session_mutations.py
+++ b/gateway/session_mutations.py
@@ -283,8 +283,10 @@ def _project_committed(authority, ref, operation, result):
# the next submit or restart.
authority._schedule(ref)
if operation == 'reasoning' or (operation == 'model' and 'effort' in result):
- # The picked level is the policy's now; a typed /reasoning override must not shadow it.
+ # The picked level is the policy's now; a typed /reasoning override must not shadow it, nor an older
+ # command still waiting for a turn boundary.
authority.runner._set_session_reasoning_override(authority.sessions[ref.session_id].route, None)
+ authority.sessions[ref.session_id].pending_reasoning = None
if operation in {'model', 'reasoning', 'workspace'}:
# Every viewer repaints its model, reasoning pill or workspace from the published policy,
# as main's _emit_session_info did after the live change.
diff --git a/gateway/session_policy.py b/gateway/session_policy.py
index 81f51972748..f289bba88d3 100644
--- a/gateway/session_policy.py
+++ b/gateway/session_policy.py
@@ -37,11 +37,27 @@ def session_pinned(config, field, launched):
return pins[field] if isinstance(pins, dict) and isinstance(pins.get(field), bool) else launched
-def pin_reasoning_effort(config, effort):
+def pin_reasoning_effort(config, effort, *, session=False):
"""Write an explicit session reasoning level into *config*: it wins over a per-model default
- (``reasoning_overrides``), at creation, on ``/reasoning`` and on a model pick that carries one."""
+ (``reasoning_overrides``), at creation, on ``/reasoning`` and on a model pick that carries one.
+ A *session* edit also records the pin."""
config.setdefault('agent', {})['reasoning_effort'] = effort
config['agent'].pop('reasoning_overrides', None)
+ if session:
+ config[SESSION_PINS] = {**(config.get(SESSION_PINS) or {}), 'reasoning': True}
+
+
+def unpin_reasoning(config, profile):
+ """``/reasoning reset``: the level is *profile*'s (its current config) again, re-read every turn by a
+ following session and on each resume by any other; a create-time ``reasoning`` included."""
+ followed = profile.get('agent') if isinstance(profile.get('agent'), dict) else {}
+ agent = config.setdefault('agent', {})
+ for key in ('reasoning_effort', 'reasoning_overrides'):
+ if key in followed:
+ agent[key] = followed[key]
+ else:
+ agent.pop(key, None)
+ config[SESSION_PINS] = {**(config.get(SESSION_PINS) or {}), 'reasoning': False}
FOLLOW_AGENT_KEYS = ('reasoning_effort', 'reasoning_overrides', 'service_tier', 'disabled_toolsets', 'coding_context')
@@ -117,8 +133,9 @@ class LocalSessionPolicy:
def effective(self, authority=None, *, secrets=True):
"""``(config, model)`` the next turn runs, both from ONE read of the owning profile when following
(the turn's policy scope holds that read): a route never pairs one profile's model with another's
- endpoint. Explicit choices (create-time reasoning / tier / toolsets, a pick that still holds) are
- applied over the followed defaults; frozen secrets of followed sections are never recovered."""
+ endpoint. Explicit choices (create-time reasoning / tier / toolsets, a session ``/reasoning`` until
+ reset, a pick that still holds) are applied over the followed defaults; frozen secrets of followed
+ sections are never recovered."""
config = present_sections(json.loads(self.config_json))
live = self.read_profile(authority)
if self.config_secret_ref is not None and authority is not None and secrets:
diff --git a/gateway/session_policy_refresh.py b/gateway/session_policy_refresh.py
index 58105d8f0ce..929d97e51fa 100644
--- a/gateway/session_policy_refresh.py
+++ b/gateway/session_policy_refresh.py
@@ -52,12 +52,14 @@ def refreshed_policy(policy, live, terminal, *, picked=(), mcp_only=False):
def _settings(policy, config, live, picked):
"""Follow the config-derived settings into *config*; the toolsets they select."""
- from gateway.session_policy import _resolve_toolsets
+ from gateway.session_policy import _resolve_toolsets, session_pinned
request = json.loads(policy.request_json)
live_agent = live.get('agent') or {}
agent = dict(config.get('agent') or {})
keys = [] if 'max_turns' in request else ['max_turns']
- keys += [] if 'reasoning' in request or 'reasoning' in picked else ['reasoning_effort', 'reasoning_overrides']
+ # The session's own record (a pick, or a reset back to the profile) wins over the receipt history.
+ chosen = session_pinned(config, 'reasoning', 'reasoning' in request or 'reasoning' in picked)
+ keys += [] if chosen else ['reasoning_effort', 'reasoning_overrides']
toolsets = policy.toolsets
if 'toolsets' not in request and policy.editor_mcp_json is None:
keys.append('disabled_toolsets')
diff --git a/gateway/session_setting_commands.py b/gateway/session_setting_commands.py
index 1608374057d..6aa937ac385 100644
--- a/gateway/session_setting_commands.py
+++ b/gateway/session_setting_commands.py
@@ -5,8 +5,11 @@ next turn reads its settings from its live session and frozen policy, not from t
per-platform snapshot, so a handler that changes a setting also applies it here: one behaviour
for every surface, held by the gateway.
"""
+import logging
from types import SimpleNamespace
+logger = logging.getLogger(__name__)
+
def local_live(runner, source):
"""The ``LiveSession`` of the local session ``source`` belongs to, else None (messaging chats)."""
@@ -65,6 +68,70 @@ def local_authority_live(runner, source):
return None, None
+async def commit_reasoning_command(authority, actor, ref, value, persist_global):
+ """``/reasoning <level>`` in either scope, or ``reset``, on a LOCAL session (``config.set`` and
+ ``slash.exec``): the owner's fenced ``reasoning`` mutation, before the handler replies or writes
+ config.yaml (``--global``). The level is the session's durable choice and a reset gives it back to the
+ profile, whatever an older pick said, after an owner restart too. Display words and reads commit nothing,
+ and so does a messaging chat (no session policy). While a turn runs, the handler applies it for the next
+ turn as on main and the drain commits it at that turn's end (``apply_pending_reasoning``)."""
+ import asyncio
+ import uuid
+ from gateway.config import Platform
+ from gateway.session_mutations import mutate_session
+ from hermes_constants import parse_reasoning_effort
+ from hermes_state_mutation_guards import MUTATION_GUARD_REFUSALS
+ from hermes_state_runtime import RuntimeStoreError
+ if value == 'reset' and not persist_global: # ``reset --global`` is the handler's named refusal
+ effort = None
+ elif value != 'reset' and parse_reasoning_effort(value) is not None:
+ effort = value
+ else:
+ return
+ live = authority.sessions[ref.session_id]
+ if live.source.platform != Platform.LOCAL:
+ return
+ row = await asyncio.to_thread(authority.db.get_session, ref.session_id)
+ if row is None:
+ raise RuntimeStoreError('not_found')
+ try:
+ await mutate_session(authority, actor, ref, {
+ 'session_id': ref.session_id, 'request_id': 'reasoning-command:' + uuid.uuid4().hex,
+ 'expected_revision': row['runtime_revision'], 'expected_generation': row['runtime_generation'],
+ 'operation': 'reasoning', 'payload': {'effort': effort}})
+ except (RuntimeStoreError, *MUTATION_GUARD_REFUSALS) as exc:
+ if getattr(exc, 'reason', 'session_busy') not in ('session_busy', 'unknown_execution'):
+ raise
+ live.pending_reasoning = (actor.subject, effort)
+
+
+async def apply_pending_reasoning(authority, ref, live):
+ """Commit a reasoning command that arrived while a turn ran. The drain calls this at the turn boundary,
+ under the claim gate and mutation lock, before a deferred model pick (whose level wins, as on main)."""
+ import asyncio
+ import uuid
+ from gateway.session_mutations import write_mutation
+ from hermes_state_mutation_guards import MUTATION_GUARD_REFUSALS
+ from hermes_state_runtime import RuntimeStoreError
+ pending, live.pending_reasoning = live.pending_reasoning, None
+ if pending is None:
+ return
+ try:
+ row = await asyncio.to_thread(authority.db.get_session, ref.session_id)
+ await write_mutation(authority, ref, {
+ 'session_id': ref.session_id, 'request_id': 'reasoning-command:' + uuid.uuid4().hex,
+ 'expected_revision': row['runtime_revision'], 'expected_generation': row['runtime_generation'],
+ 'operation': 'reasoning', 'payload': {'effort': pending[1]}}, None, principal_id=pending[0])
+ except (RuntimeStoreError, *MUTATION_GUARD_REFUSALS) as exc:
+ if getattr(exc, 'reason', 'session_busy') in ('session_busy', 'unknown_execution'):
+ live.pending_reasoning = live.pending_reasoning or pending # a worker still runs: the next boundary
+ else:
+ logger.warning('Reasoning command on %s not committed: %s', ref.session_id, exc.reason)
+ except Exception:
+ # Before the claim: escaping would kill or wedge the drain (the in-memory level still applies).
+ logger.exception('Reasoning command on %s failed to commit', ref.session_id)
+
+
def defer_local_model_pick(authority, live, result, effort=''):
"""A typed ``/model`` on a local session: the resolved target becomes the session's canonical
``model`` mutation, committed by the owner at the next turn boundary (the typed command is
diff --git a/gateway/session_tui_config.py b/gateway/session_tui_config.py
index fccfb55dc0d..006f31df8b8 100644
--- a/gateway/session_tui_config.py
+++ b/gateway/session_tui_config.py
@@ -341,6 +341,8 @@ async def _set_command_setting(connection, ref, params):
if value not in _REASONING_DISPLAY_TOGGLES and value != 'reset' and parse_reasoning_effort(value) is None:
raise RuntimeStoreError('invalid_params')
live, runner = connection.authority.sessions[ref.session_id], connection.authority.runner
+ from gateway.session_setting_commands import commit_reasoning_command
+ await commit_reasoning_command(connection.authority, connection.actor, ref, value, scope == 'global')
def apply():
with _profile_runtime_scope(Path(connection.authority.profile_id)):
diff --git a/hermes_cli/cli_model_switch_mixin.py b/hermes_cli/cli_model_switch_mixin.py
index fc5915703b3..a0f3b253e79 100644
--- a/hermes_cli/cli_model_switch_mixin.py
+++ b/hermes_cli/cli_model_switch_mixin.py
@@ -258,7 +258,12 @@ def _apply_reasoning_after_switch(cli, effort: str, *, persist_global: bool) ->
cli.reasoning_config = parsed
cli._reasoning_user_set = True
if cli.agent is not None:
- cli.agent.reasoning_config = parsed
+ # The gateway session's agent commits an explicit level even when it equals the inherited one.
+ pin = getattr(cli.agent, "pin_reasoning", None)
+ if pin is not None:
+ pin(parsed)
+ else:
+ cli.agent.reasoning_config = parsed
saved = persist_global and save_config_value("agent.reasoning_effort", effort)
if saved:
CLI_CONFIG.setdefault("agent", {})["reasoning_effort"] = effort
diff --git a/hermes_cli/gateway_agent.py b/hermes_cli/gateway_agent.py
index 9afebd01044..a2caf7c7611 100644
--- a/hermes_cli/gateway_agent.py
+++ b/hermes_cli/gateway_agent.py
@@ -164,7 +164,7 @@ class GatewayAgent:
# Only a user-picked effort (/reasoning, a model pick's --reasoning) is committed at build; the
# config-resolved level must never override the session's frozen launch policy on resume.
if push_reasoning:
- self.reasoning_config = reasoning_config
+ self.pin_reasoning(reasoning_config)
else:
self._reasoning_config = reasoning_config
# Main's /moa rebuilds its agent on the MoA virtual provider for one turn (the session's info
@@ -203,14 +203,23 @@ class GatewayAgent:
@reasoning_config.setter
def reasoning_config(self, config):
- """``/reasoning <level>`` (session scope; main rebuilds its agent with the new config) and /new's
- re-derived effort: ``session.mutate reasoning`` when it differs from the session's effort."""
+ """/new's re-derived effort and a one-turn restore: ``session.mutate reasoning`` when it differs from
+ the session's effort (an inherited level stays inherited)."""
+ self._set_reasoning(config, explicit=False)
+
+ def pin_reasoning(self, config):
+ """``/reasoning <level>`` (session scope; main rebuilds its agent with the new config) and a model
+ pick's ``--reasoning``: always ``session.mutate reasoning``, even when the session already runs that
+ level by inheritance, so it becomes the session's own choice."""
+ self._set_reasoning(config, explicit=True)
+
+ def _set_reasoning(self, config, *, explicit):
self._reasoning_config = config
effort = _effort_word(config)
if effort is None:
return
info = self._state().info or {}
- if info.get("reasoning_effort") == effort:
+ if not explicit and info.get("reasoning_effort") == effort:
return
try:
snapshot = self.connection.call("session.resume", session_id=self.session_id)
diff --git a/hermes_state_mutations.py b/hermes_state_mutations.py
index 95afd1629cb..d34edad67e2 100644
--- a/hermes_state_mutations.py
+++ b/hermes_state_mutations.py
@@ -19,6 +19,8 @@ def validate_action(operation, payload):
return
# Session-scope ``/reasoning <level>`` and Desktop's Move to project: revision-fenced edits of
# the frozen policy (gateway/session_mutation_policy.py).
+ if operation == 'reasoning' and set(payload) == {'effort'} and payload['effort'] is None:
+ return # ``/reasoning reset``: the session's level goes back to the profile
if operation == 'reasoning' and set(payload) == {'effort'} and isinstance(payload['effort'], str):
from hermes_constants import parse_reasoning_effort
if parse_reasoning_effort(payload['effort']) is not None:
diff --git a/tests/gateway/test_follow_profile_followups.py b/tests/gateway/test_follow_profile_followups.py
index f38795ac5e4..03132c295a4 100644
--- a/tests/gateway/test_follow_profile_followups.py
+++ b/tests/gateway/test_follow_profile_followups.py
@@ -106,6 +106,107 @@ def _ref(authority, live):
return SimpleNamespace(session_id=sid)
+async def _pick_reasoning(owner, authority, live, effort):
+ """Desktop's reasoning selector, Ink's and the classic CLI's ``/reasoning <level>``: the owner's verb."""
+ sid = _ref(authority, live).session_id
+ row = authority.db.get_session(sid)
+ reply = await owner.dispatch({'id': 'r', 'method': 'session.mutate', 'params': {
+ 'session_id': sid, 'request_id': 'reasoning-' + effort, 'operation': 'reasoning', 'payload': {'effort': effort},
+ 'expected_revision': row['runtime_revision'], 'expected_generation': row['runtime_generation']}})
+ assert reply['result']['effort'] == effort, reply
+ return sid
+
+
+async def test_a_session_reasoning_pick_wins_over_the_followed_default_after_a_restart(home):
+ """Desktop's reasoning picker and ``/reasoning <level>`` on a Bot Chat (created without ``reasoning``):
+ the acknowledged level is the next turn's, through a profile edit and a fresh owner; an unpicked
+ following chat still runs the profile's current level."""
+ from gateway.session_local import local_session_info
+ from gateway.session_local_recovery import restore_local_session
+ from gateway.session_policy import policy_for_source
+ _profile(home, 'm', 1, 'k', agent={'reasoning_effort': 'low'})
+ store, runner, authority, owner = _owner(home)
+ runner._peek_session_state = lambda key: None
+ runner._set_session_reasoning_override = lambda key, value: None
+ try:
+ picked = await _create_bot_chat(owner, authority, home, 'picked')
+ plain = await _create_bot_chat(owner, authority, home, 'plain')
+ sid = await _pick_reasoning(owner, authority, picked, 'high')
+ _profile(home, 'm', 1, 'k', agent={'reasoning_effort': 'minimal'})
+ for live, effort in ((picked, 'high'), (plain, 'minimal')):
+ info = local_session_info(authority, _ref(authority, live))
+ assert (policy_for_source(runner, live.source).current_reasoning_config(runner)['effort'],
+ info['reasoning_effort']) == (effort, effort)
+ finally:
+ await owner.close()
+ store.close_all_db_handles()
+ store, runner, authority, owner = _owner(home) # a fresh owner: only the durable receipt carries the pick
+ runner._peek_session_state = lambda key: None
+ try:
+ restore_local_session(authority, sid)
+ assert policy_for_source(runner, authority.sessions[sid].source).current_reasoning_config(runner)['effort'] == 'high'
+ finally:
+ await owner.close()
+ store.close_all_db_handles()
+
+
[email protected]('method,params,expected', [
+ ('config.set', {'key': 'reasoning', 'value': 'minimal', 'scope': 'global'}, 'minimal'),
+ ('slash.exec', {'command': '/reasoning minimal'}, 'minimal'),
+ ('config.set', {'key': 'reasoning', 'value': 'reset'}, 'medium'),
+ ('slash.exec', {'command': '/reasoning reset'}, 'medium'),
+], ids=['config.set-global', 'slash.exec-level', 'config.set-reset', 'slash.exec-reset'])
+async def test_a_later_reasoning_command_replaces_the_pick_after_a_restart(home, tmp_path, monkeypatch, method, params,
+ expected):
+ """After a pick, ``/reasoning <level> [--global]`` or ``/reasoning reset`` from Desktop, Ink or
+ ``slash.exec`` is the session's level from then on: a fresh owner and a resume keep the command's level,
+ and a reset follows the profile (here moved to ``medium``), on a Bot Chat and on a frozen session."""
+ from gateway.session_contract import SessionRef
+ from gateway.session_local_recovery import restore_local_session
+ from gateway.session_policy import policy_for_source
+ from gateway.session_policy_refresh import commit_refresh
+
+ from gateway import session_local
+
+ async def reply(event): # the messaging handler: its reply and --global's config.yaml write
+ return 'ok'
+ monkeypatch.setattr(session_local, 'authorize_local_source', lambda runner, source: True)
+ monkeypatch.chdir(tmp_path) # the commands' profile scope is ``_owner``'s relative profile id
+ _profile(home, 'm', 1, 'k', agent={'reasoning_effort': 'low'})
+ store, runner, authority, owner = _owner(home)
+ runner._peek_session_state = lambda key: None
+ runner._set_session_reasoning_override = lambda key, value: None
+ runner._apply_reasoning_selection = lambda *args, **kwargs: 'ok'
+ runner._command_handler_table = lambda names: {'reasoning': reply}
+ try:
+ follow = await _create_bot_chat(owner, authority, home, 'follow')
+ created = await owner.dispatch({'id': 'c', 'method': 'session.create', 'params': {
+ 'request_id': 'frozen', 'source': 'gui', 'cwd': str(home)}})
+ sids = [await _pick_reasoning(owner, authority, live, 'high')
+ for live in (follow, authority.sessions[created['result']['session_id']])]
+ for sid in sids:
+ answer = await owner.dispatch({'id': 'x', 'method': method, 'params': {'session_id': sid, **params}})
+ assert 'result' in answer, answer
+ finally:
+ await owner.close()
+ store.close_all_db_handles()
+ _profile(home, 'm', 1, 'k', agent={'reasoning_effort': 'medium'})
+ store, runner, authority, owner = _owner(home)
+ runner._peek_session_state = lambda key: None
+ runner._set_session_reasoning_override = lambda key, value: None
+ try:
+ for sid in sids:
+ restore_local_session(authority, sid)
+ await commit_refresh(authority, SessionRef(authority.profile_id, sid)) # the resume's re-read
+ assert [policy_for_source(runner, authority.sessions[sid].source).current_reasoning_config(runner)['effort']
+ for sid in sids] == [expected, expected]
+ finally:
+ await owner.close()
+ store.close_all_db_handles()
+
+
@pytest.mark.asyncio
async def test_follow_session_runs_the_profiles_current_toolsets_and_a_frozen_one_does_not(home):
"""C03 (main #124211): ``hermes tools disable`` reaches a following Bot Chat's next turn."""
diff --git a/tests/gateway/test_session_mutation_model_busy.py b/tests/gateway/test_session_mutation_model_busy.py
index 13ac0ec1b1a..b30cb6353f7 100644
--- a/tests/gateway/test_session_mutation_model_busy.py
+++ b/tests/gateway/test_session_mutation_model_busy.py
@@ -414,3 +414,51 @@ async def test_a_deferred_model_and_reasoning_pick_commits_both_together(tmp_pat
release.set()
await owner.close()
store.close_all_db_handles()
+
+
+async def test_a_reasoning_command_during_a_running_turn_is_committed_for_the_next_turn(tmp_path, monkeypatch):
+ """Desktop's and Ink's ``/reasoning <level> --global`` and ``/reasoning reset`` while a turn runs reach
+ the owner as ``config.set``: run by the messaging handler as on main (never refused ``session_busy``),
+ then committed to the session's policy when the turn ends, so the next turn and an owner restart run
+ them. A messaging chat viewed in Desktop has no policy: its handler alone runs, as on main."""
+ from gateway.config import Platform
+ from gateway.session import SessionSource
+ from gateway.session_authority import LiveSession
+ from gateway.session_contract import Submission
+ from gateway.session_policy import policy_for_source
+ started, release = threading.Event(), asyncio.Event()
+ seen, handled, state = [], [], {}
+
+ async def handle(event):
+ live = state['authority'].sessions[state['ref'].session_id]
+ seen.append((policy_for_source(state['authority'].runner, live.source).reasoning_config or {}).get('effort'))
+ if event.text == 'RUNNING':
+ started.set()
+ await release.wait()
+ return 'ok'
+ monkeypatch.chdir(tmp_path) # the handler's profile scope is the owner's relative profile id
+ store, db, authority, owner, ref = _owner(tmp_path, monkeypatch, handle)
+ state.update(authority=authority, ref=ref)
+ authority.runner._set_session_reasoning_override = lambda *a: None
+ authority.runner._apply_reasoning_selection = lambda route, platform, value, persist_global=False: handled.append(value)
+ db.create_session('telegram-row', 'telegram')
+ authority.sessions['telegram-row'] = LiveSession(SessionSource(platform=Platform.TELEGRAM, chat_id='42'), 'tg:42')
+ try:
+ for value, scope in (('minimal', 'global'), ('reset', 'session')):
+ started.clear()
+ release.clear()
+ await authority.submit(owner.actor, Submission('run-' + value, ref, {'text': 'RUNNING'}, 'queue'))
+ await async_wait_until(started.is_set, timeout=10, what='a turn is running')
+ for sid in (ref.session_id, 'telegram-row'):
+ reply = await owner.dispatch({'id': 1, 'method': 'config.set', 'params': {
+ 'session_id': sid, 'key': 'reasoning', 'value': value, 'scope': scope}})
+ assert reply.get('result', {}).get('value') == value, reply
+ release.set()
+ await _run_turn(authority, owner, db, ref, 'NEXT-' + value)
+ assert handled == ['minimal', 'minimal', 'reset', 'reset']
+ assert seen[1:] == ['minimal', 'minimal', seen[0]] and seen[0] != 'minimal', seen
+ finally:
+ release.set()
+ await owner.close()
+ store.close_all_db_handles()
diff --git a/tests/gateway/test_session_mutation_model_route.py b/tests/gateway/test_session_mutation_model_route.py
index 77b42cbacd6..7b1a7575c91 100644
--- a/tests/gateway/test_session_mutation_model_route.py
+++ b/tests/gateway/test_session_mutation_model_route.py
@@ -359,3 +359,34 @@ async def test_a_named_entry_that_moves_never_sends_its_old_launch_key_to_the_ne
finally:
await owner.close()
store.close_all_db_handles()
+
+
+async def test_a_level_picked_with_the_model_survives_a_profile_edit_and_a_resume_refresh(home, endpoints):
+ """Desktop's model picker sends the reasoning level with the model. On a following session that level
+ is the next turn's, after the profile's default moves and after a resume re-reads the profile."""
+ from gateway.session_contract import SessionRef
+ from gateway.session_policy import policy_for_source
+ from gateway.session_policy_refresh import commit_refresh
+ (_, url), _ = endpoints
+
+ def profile(effort):
+ (home / 'config.yaml').write_text(json.dumps({
+ 'model': {'provider': 'custom', 'default': 'original', 'base_url': url, 'api_key': 'key-a'},
+ 'agent': {'reasoning_effort': effort}}), encoding='utf-8')
+ profile('low')
+ store, runner, authority, owner = _owner(home)
+ _bind_resolver(runner)
+ runner._set_session_reasoning_override = lambda key, value: None
+ try:
+ live = await _create(owner, authority, home, 'follow')
+ sid = next(sid for sid, value in authority.sessions.items() if value is live)
+ response = await _pick(owner, authority, sid, {'model': 'picked', 'provider': 'custom', 'reasoning': 'high'})
+ assert 'result' in response, response
+ profile('minimal')
+ assert policy_for_source(runner, live.source).current_reasoning_config(runner)['effort'] == 'high'
+ await commit_refresh(authority, SessionRef(authority.profile_id, sid))
+ assert policy_for_source(runner, live.source).current_reasoning_config(runner)['effort'] == 'high'
+ finally:
+ await owner.close()
+ store.close_all_db_handles()
diff --git a/tests/gateway/test_session_setting_commands.py b/tests/gateway/test_session_setting_commands.py
index f1d7b33dac4..40cccf8162e 100644
--- a/tests/gateway/test_session_setting_commands.py
+++ b/tests/gateway/test_session_setting_commands.py
@@ -117,7 +117,8 @@ def test_local_session_settings_run_the_messaging_handlers_and_read_back_through
out, home, config = _run(tmp_path, steps)
saved = _yaml(home)
# /reasoning: a session level is this session's next turn, config.yaml untouched; --global saves
- # AND applies to this session (which never re-reads config.yaml); reset falls back to its policy.
+ # AND applies to this session (which never re-reads config.yaml); reset gives the level back to the
+ # profile (config.yaml, now low), as its reply says and a resume would re-read it.
assert 'medium' in out['reasoning'] and 'Scope' in out['reasoning'], out['reasoning']
assert 'session only' in out['reasoning high'] and out['get high']['value'] == 'high', out
assert out['get show']['value'] == '1' and 'Display:** on' in out['reasoning status'], out
@@ -127,7 +128,7 @@ def test_local_session_settings_run_the_messaging_handlers_and_read_back_through
assert out['turn low'].get('reasoning_effort') == 'low', out['turn low']
assert 'saved to config' in out['reasoning --global low'] and out['get low']['value'] == 'low', out
assert saved['agent']['reasoning_effort'] == 'low'
- assert out['get reset']['value'] == 'medium', out['get reset']
+ assert out['get reset']['value'] == 'low', out['get reset']
# /busy: saved like the messaging handler and applied to this session.
assert '`queue`' in out['busy queue'] and out['get busy']['value'] == 'queue', out
assert '`queue`' in out['busy'] and saved['display']['busy_input_mode'] == 'queue', out['busy']
diff --git a/tests/hermes_cli/test_gateway_agent.py b/tests/hermes_cli/test_gateway_agent.py
index 7b2701fe036..50fa438fef4 100644
--- a/tests/hermes_cli/test_gateway_agent.py
+++ b/tests/hermes_cli/test_gateway_agent.py
@@ -438,6 +438,21 @@ def test_reasoning_level_change_is_the_session_reasoning_mutation(make_agent):
assert agent2.reasoning_config == {"enabled": False}
+def test_an_explicit_level_the_session_already_inherits_is_still_committed(make_agent):
+ """``/reasoning high`` (the rebuilt agent) or a model pick's ``--reasoning high`` while the session runs
+ high by inheritance: still the owner's reasoning mutation, so a later profile change can't move it. An
+ implicit re-derivation (/new, a one-turn restore) of the same level commits nothing."""
+ from types import SimpleNamespace
+ from hermes_cli.cli_model_switch_mixin import _apply_reasoning_after_switch
+ agent, client = make_agent([])
+ agent.connection.state(SID).info["reasoning_effort"] = "high"
+ GatewayAgent(connection=agent.connection, session_id=SID, reasoning_config={"enabled": True, "effort": "high"},
+ push_reasoning=True)
+ _apply_reasoning_after_switch(SimpleNamespace(agent=agent), "high", persist_global=False)
+ agent.reasoning_config = {"enabled": True, "effort": "high"}
+ assert [p["payload"] for m, p in client.calls if m == "session.mutate"] == [{"effort": "high"}] * 2
+
+
def test_a_config_resolved_effort_never_overrides_the_sessions_launch_policy(make_agent):
"""Building the agent with the CLI's config-resolved effort (no /reasoning pick) commits nothing:
a resumed `-q --resume` must keep the session's frozen --reasoning, not the profile default."""