Skip to content

The agent that grows with you

fix: Desktop model and reasoning picks apply to a messaging chat

Teknium18197369663c
diff --git a/gateway/session_local.py b/gateway/session_local.py
index db068586639..f161314395a 100644
--- a/gateway/session_local.py
+++ b/gateway/session_local.py
@@ -365,10 +365,8 @@ def _reasoning_fields(agent, policy, model, authority=None, override=None):
"""Main's session-info effort/tier fields, from the built agent or (lazy) what the policy's next turn
resolves (a following session's current profile): a resumed Desktop slice holds its reasoning pill
pending until ``reasoning_effort`` arrives."""
- from agent.fast_mode import STATIC_TIERS, parse_service_tier
- from agent.reasoning_effort import clamp_effort, route_supported_efforts
+ from agent.fast_mode import parse_service_tier
from agent.voice_turn_route import session_runtime_view
- from hermes_cli.models import resolve_fast_mode_overrides
if agent is None and policy is None:
return {}
view = session_runtime_view(agent) if agent is not None else None
@@ -382,13 +380,21 @@ def _reasoning_fields(agent, policy, model, authority=None, override=None):
else parse_service_tier((effective.get('agent') or {}).get('service_tier'))) or ''
provider = getattr(view, 'provider', None) if view is not None else route.get('provider')
base_url = getattr(view, 'base_url', None) if view is not None else route.get('base_url')
+ return effort_fields(config, tier, model, provider, base_url, getattr(view, 'api_mode', None))
+
+
+def effort_fields(config, tier, model, provider, base_url, api_mode=None):
+ """Session-info ``reasoning_effort`` / ``_wire`` / ``service_tier`` / ``fast`` for one resolved route."""
+ from agent.fast_mode import STATIC_TIERS
+ from agent.reasoning_effort import clamp_effort, route_supported_efforts
+ from hermes_cli.models import resolve_fast_mode_overrides
+ tier = tier or ''
effort = ''
if isinstance(config, dict):
effort = 'none' if config.get('enabled') is False else str(config.get('effort') or '')
wire = ''
if effort and effort != 'none':
- wire = str(clamp_effort(effort, route_supported_efforts(
- provider, model, getattr(view, 'api_mode', None))) or '')
+ wire = str(clamp_effort(effort, route_supported_efforts(provider, model, api_mode)) or '')
try:
fast = tier in STATIC_TIERS and resolve_fast_mode_overrides(
model, provider=provider or None, base_url=base_url or None, tier=tier) is not None
@@ -416,7 +422,13 @@ def local_session_info(authority, ref):
peek = getattr(authority.runner, '_peek_session_state', None)
state = peek(live.route) if peek is not None else None
override = state.conversation.reasoning_override if state is not None else None # a typed /reasoning
- info.update(_reasoning_fields(agent, policy, info['model'], authority, override))
+ if agent is None and policy is None and live.source.platform != Platform.LOCAL:
+ # A messaging chat not built yet: what its next turn resolves (its /model and /reasoning picks
+ # included), so a viewer's model and reasoning pill never wait on a field that never comes.
+ from gateway.session_messaging_picks import messaging_route_info
+ info.update(messaging_route_info(authority.runner, live))
+ else:
+ info.update(_reasoning_fields(agent, policy, info['model'], authority, override))
if policy:
# The creation request the route was frozen with (secrets already extracted), so a
# resuming client can tell "same flags again" from a real override attempt.
diff --git a/gateway/session_messaging_picks.py b/gateway/session_messaging_picks.py
new file mode 100644
index 00000000000..b0f708855b7
--- /dev/null
+++ b/gateway/session_messaging_picks.py
@@ -0,0 +1,120 @@
+"""A viewer's model and reasoning picks on a messaging chat (Telegram, Discord, ...), #141152.
+
+Desktop and the TUI send ``session.mutate`` ``model`` / ``reasoning`` for whatever session they show.
+A LOCAL session commits the pick into its frozen policy; a messaging chat has no frozen policy, so
+that path refused it with ``runtime_coordination_required`` and the reasoning pill waited forever for
+a level. The chat's own ``/model`` and ``/reasoning`` set a per-chat override that its next turn
+resolves (``_record_model_switch``, ``_apply_reasoning_selection``). A viewer's pick sets that same
+override, so the chat and every viewer see one setting.
+
+The mutation names the session a viewer resumed, which for a compressed chat is its lineage root
+(``messaging_owner_ref``): the fences are checked on that row and the override is keyed by the lane's
+route, so it applies to the compression tip the next turn writes.
+"""
+import asyncio
+
+from hermes_state_runtime import RuntimeStoreError
+
+CHAT_PICKS = frozenset({'model', 'reasoning'})
+
+
+def is_chat_pick(live, operation):
+ from gateway.config import Platform
+ return operation in CHAT_PICKS and live is not None and live.source.platform != Platform.LOCAL
+
+
+def _require_fences(authority, ref, params):
+ row = authority.db.get_session(ref.session_id)
+ if row is None:
+ raise RuntimeStoreError('not_found')
+ if row['runtime_revision'] != params['expected_revision']:
+ raise RuntimeStoreError('revision_conflict')
+ if row['runtime_generation'] != params['expected_generation']:
+ raise RuntimeStoreError('stale_generation')
+ return row
+
+
+def _platform_key(live):
+ from gateway.run import _platform_config_key
+ return _platform_config_key(live.source.platform)
+
+
+def _apply_reasoning(runner, live, effort):
+ """``/reasoning <level>`` (``None``: ``/reasoning reset``) as the chat would run it."""
+ return runner._apply_reasoning_selection(live.route, _platform_key(live), 'reset' if effort is None else effort)
+
+
+async def _pick_model(authority, owner, live, payload, row):
+ """The chat's ``/model <name> [--provider p]`` resolution, guarded like a LOCAL pick, then committed
+ as its session override. Returns the receipt fields, or the guard's confirmation request."""
+ from gateway.session_mutation_model import _Route, _selection_guard_refusal
+ from gateway.slash_commands_model import _ModelSwitchContext
+ from hermes_constants import get_hermes_home
+ runner = authority.runner
+ ctx = _ModelSwitchContext(session_key=live.route, source=live.source,
+ config_path=get_hermes_home() / 'config.yaml', persist_global=False)
+ ctx.read_config()
+ ctx.apply_override(runner._session_model_override(live.route) or {})
+ result, error = await runner._perform_model_switch(ctx, payload['model'], payload.get('provider', ''), live.source)
+ if error is not None:
+ raise RuntimeStoreError('model_resolution_failed', detail=error)
+ snapshot = {'target': owner.session_id, 'target_revision': row['runtime_revision']}
+ current = _Route(ctx.current_provider, ctx.current_model, ctx.current_base_url, ctx.current_api_key)
+ refusal = await _selection_guard_refusal(authority, live, payload, snapshot, current, result)
+ if refusal is not None:
+ return refusal
+ # No in-place swap of the cached agent: a turn may be running on it. The override is what the
+ # next turn builds from, and the record step evicts the cached agent.
+ await runner._record_model_switch(result, ctx, source=live.source, one_turn=False, picker=True)
+ fields = {'model': result.new_model, 'provider': result.target_provider}
+ if 'reasoning' in payload:
+ _apply_reasoning(runner, live, payload['reasoning'])
+ fields['effort'] = payload['reasoning']
+ return fields
+
+
+async def apply_chat_pick(authority, ref, owner, live, params):
+ """Apply a ``model`` / ``reasoning`` mutation to the messaging chat *live* mounted on *owner* (the
+ caller authorized control and holds its mutation lock). The fences are the mount's, the ones
+ ``session.resume`` handed the viewer; comparing them with a compression segment's row refused a
+ pick on a compressed chat with ``stale_generation``."""
+ from hermes_state_mutations import validate_action
+ operation, payload = params['operation'], params['payload']
+ validate_action(operation, payload)
+ row = await asyncio.to_thread(_require_fences, authority, owner, params)
+ runner = authority.runner
+ if operation == 'reasoning':
+ await asyncio.to_thread(_apply_reasoning, runner, live, payload['effort'])
+ fields = {'effort': payload['effort']}
+ else:
+ async with runner._model_switch_lock():
+ fields = await _pick_model(authority, owner, live, payload, row)
+ result = {'session_id': ref.session_id, 'operation': operation, 'revision': row['runtime_revision'],
+ 'execution_generation': row['runtime_generation'], **fields}
+ if fields.get('status') == 'confirmation_required':
+ return {'session_id': ref.session_id, 'operation': operation, **fields}
+ from gateway.session_local import local_session_info
+ # Every viewer repaints its model and reasoning pill, as after a LOCAL pick.
+ live.event_stream.publish(owner.session_id, local_session_info(authority, owner), event_type='session.info')
+ return result
+
+
+def messaging_route_info(runner, live):
+ """``model`` and the effort fields a messaging chat's next turn resolves, without building an agent
+ or resolving credentials: session ``/model`` > ``channel_overrides`` > config.yaml, and the session
+ ``/reasoning`` > per-model > global level (``_resolve_session_reasoning_config``)."""
+ from gateway.run import _load_gateway_config, _resolve_gateway_model
+ from gateway.session_local import effort_fields
+ config = _load_gateway_config()
+ block = config.get('model')
+ block = block if isinstance(block, dict) else {}
+ model, provider, base_url = _resolve_gateway_model(config), block.get('provider'), block.get('base_url')
+ channel = runner._channel_override_for(live.source)
+ if channel is not None:
+ model, provider = channel.model or model, channel.provider or provider
+ override = runner._session_model_override(live.route) or runner.session_store.get_model_override(live.route) or {}
+ model = override.get('model') or model
+ provider, base_url = override.get('provider') or provider, override.get('base_url') or base_url
+ reasoning = runner._resolve_session_reasoning_config(source=live.source, session_key=live.route, model=model)
+ tier = runner._resolve_session_service_tier(source=live.source, session_key=live.route)
+ return {'model': model, **effort_fields(reasoning, tier, model, provider, base_url)}
diff --git a/gateway/session_mutations.py b/gateway/session_mutations.py
index cb04183f797..bff02d4a2ea 100644
--- a/gateway/session_mutations.py
+++ b/gateway/session_mutations.py
@@ -9,6 +9,7 @@ import logging
from contextlib import nullcontext
from functools import partial
+from gateway.session_messaging_picks import CHAT_PICKS, is_chat_pick
from hermes_state_mutation_guards import MUTATION_GUARD_REFUSALS
from hermes_state_runtime import RuntimeStoreError, mutate_runtime_session
@@ -78,8 +79,13 @@ def _owner_ref(authority, ref, params):
listed id: its busy gate, generation fence and eviction are keyed by the session it writes, so
authorizing it on the owner while writing the segment would bypass the owner's FIFO. A segment
of a live owner therefore stays a named refusal for those, as on main. A delete of a messaging
- conversation's later compression segment resolves to its lineage root, where its lane's
- session lives (``messaging_owner_ref``, as resume does)."""
+ conversation's later compression segment, or a model/reasoning pick on it, resolves to its
+ lineage root, where its lane's session lives (``messaging_owner_ref``, as resume does)."""
+ if params.get('operation') in CHAT_PICKS:
+ # A messaging chat's picks are its lane's (route-keyed) overrides: a compression segment names
+ # the lineage root its lane is mounted on. Any other row keeps its id.
+ from gateway.session_route_recovery import messaging_owner_ref
+ return messaging_owner_ref(authority, ref)
if params.get('operation') not in _OWNER_AUTHORIZED:
return ref
from gateway.session_contract import SessionRef
@@ -128,7 +134,7 @@ async def _owned_mutation(authority, actor, ref, params):
from gateway.session_deferred_pick import defer_pick
# Its own BEGIN IMMEDIATE: off the loop, like the receipt commit.
return await asyncio.to_thread(defer_pick, authority, actor, ref, params)
- if params.get('operation') in {*_POLICY, 'compress', 'reset'}:
+ if params.get('operation') in {*_POLICY, 'compress', 'reset'} and not is_chat_pick(live, params['operation']):
authority._schedule(ref)
return result
@@ -153,6 +159,11 @@ async def _mutate_session(authority, actor, ref, params, *, commit_lock=None, ow
if operation == 'branch' and 'session:create' not in actor.capabilities:
raise RuntimeStoreError('permission_denied')
authority._require_admission_open()
+ live = authority.sessions.get((owner or ref).session_id)
+ if is_chat_pick(live, operation):
+ # No frozen policy to commit into: the chat's own /model and /reasoning override (#141152).
+ from gateway.session_messaging_picks import apply_chat_pick
+ return await apply_chat_pick(authority, ref, owner or ref, live, params)
def authorize_write(conn):
from hermes_state_mutation_binding import authorize_history, import_history_control
diff --git a/tests/gateway/test_messaging_session_picks.py b/tests/gateway/test_messaging_session_picks.py
new file mode 100644
index 00000000000..128f4e855c3
--- /dev/null
+++ b/tests/gateway/test_messaging_session_picks.py
@@ -0,0 +1,93 @@
+"""Desktop/TUI model and reasoning picks on a messaging chat (#141152).
+
+``session.mutate`` ``model`` / ``reasoning`` on a Telegram chat a viewer opened was refused with
+``runtime_coordination_required`` (only LOCAL sessions have a frozen policy), and the reasoning pill
+never got a level. The pick is the chat's own ``/model`` / ``/reasoning`` override, so the chat's next
+turn runs it and every viewer reads it back, also when the chat was compressed and the viewer named
+the compression segment. Real GatewayRunner, SessionAuthority and SQLite store.
+"""
+import pytest
+
+from gateway.run import GatewayRunner
+
+
[email protected](autouse=True)
+def _home(tmp_path, monkeypatch):
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+
+
+async def _compressed_chat(tmp_path):
+ """A Telegram chat compressed once; the viewer resumes it by its segment id, as history pickers do."""
+ import json
+ from gateway.config import GatewayConfig, Platform
+ from gateway.session import SessionSource
+ from gateway.session_authority import initialize_session_authority
+ from gateway.session_controls import AuthorityConnection
+ runner = GatewayRunner(GatewayConfig())
+ authority = await initialize_session_authority(runner, profile_id='default', instance_id='owner')
+ source = SessionSource(platform=Platform.TELEGRAM, chat_id='4242', user_id='u-4242', chat_type='dm')
+ root = authority.register(source).session_id
+ route = runner.session_store._generate_session_key(source)
+ db = authority.db
+ db.append_message(root, 'user', 'first')
+ db.publish_compression_child(parent_session_id=root, child_session_id='seg-1', source='telegram',
+ messages=[{'role': 'user', 'content': 'summary'}], require_compression_lease=False)
+ assert runner.session_store.advance_compression_session(route, root, 'seg-1') is not None
+ db.record_gateway_session_peer('seg-1', source='telegram', user_id=source.user_id, session_key=route,
+ chat_id=source.chat_id, chat_type='dm', origin_json=json.dumps(source.to_dict()))
+ # The segment's own fences moved on (its turns ran there); the viewer holds the mount's.
+ db._execute_write(lambda conn: conn.execute(
+ "UPDATE sessions SET runtime_revision=7, runtime_generation=3 WHERE id='seg-1'"))
+ viewer = AuthorityConnection(authority, object(), {
+ 'provider': 'local', 'user_id': 'viewer', 'profile_id': 'default', 'instance_id': 'owner',
+ 'capabilities': ['session:read', 'session:control']})
+ resumed = await viewer.dispatch({'id': 1, 'method': 'session.resume', 'params': {'session_id': 'seg-1'}})
+ assert resumed.get('result', {}).get('session_id') == root, resumed
+ return runner, source, route, viewer, root, resumed['result']
+
+
+def _mutate(sid, fences, operation, payload, request_id):
+ return {'id': request_id, 'method': 'session.mutate', 'params': {
+ 'session_id': sid, 'request_id': request_id, 'operation': operation, 'payload': payload,
+ 'expected_revision': fences['revision'], 'expected_generation': fences['execution_generation']}}
+
+
+async def test_a_reasoning_pick_on_a_compressed_messaging_chat_is_the_chats_next_turn_level(tmp_path):
+ runner, source, route, viewer, root, fences = await _compressed_chat(tmp_path)
+ try:
+ before = await viewer.dispatch({'id': 2, 'method': 'session.info', 'params': {'session_id': root}})
+ assert isinstance(before.get('result', {}).get('reasoning_effort'), str), before # the pill resolves
+
+ picked = await viewer.dispatch(_mutate('seg-1', fences, 'reasoning', {'effort': 'high'}, 'pick-high'))
+
+ assert picked.get('result', {}).get('effort') == 'high', picked
+ level = runner._resolve_session_reasoning_config(source=source, session_key=route, model='')
+ assert level and level.get('effort') == 'high', level
+ info = await viewer.dispatch({'id': 3, 'method': 'session.info', 'params': {'session_id': root}})
+ assert info['result']['reasoning_effort'] == 'high', info
+ finally:
+ await viewer.close()
+ runner.session_store.close_all_db_handles()
+
+
+async def test_a_model_pick_on_a_messaging_chat_is_the_chats_next_turn_model(tmp_path, monkeypatch):
+ from hermes_cli import model_selection_guards, model_switch
+ monkeypatch.setattr(model_switch, 'switch_model', lambda **k: model_switch.ModelSwitchResult(
+ success=True, new_model=k['raw_input'], target_provider='custom', base_url='http://127.0.0.1:9/v1'))
+ monkeypatch.setattr(model_selection_guards, 'selection_warnings', lambda *a, **k: [])
+ runner, source, route, viewer, root, fences = await _compressed_chat(tmp_path)
+ try:
+ picked = await viewer.dispatch(_mutate(root, fences, 'model', {'model': 'picked', 'reasoning': 'low'}, 'pick'))
+
+ assert picked.get('result', {}).get('model') == 'picked', picked
+ assert runner._session_model_override(route)['model'] == 'picked'
+ assert runner.session_store.get_model_override(route)['model'] == 'picked' # survives a restart
+ level = runner._resolve_session_reasoning_config(source=source, session_key=route, model='picked')
+ assert level and level.get('effort') == 'low', level
+ info = await viewer.dispatch({'id': 3, 'method': 'session.info', 'params': {'session_id': root}})
+ assert (info['result']['model'], info['result']['reasoning_effort']) == ('picked', 'low'), info
+ finally:
+ await viewer.close()
+ runner.session_store.close_all_db_handles()