Skip to content

The agent that grows with you

fix: /model reset on the session owner (canonical TUI, Desktop, attached CLI)

Teknium65effb1e9fcc
diff --git a/apps/desktop/src/api/canonical-protocol.ts b/apps/desktop/src/api/canonical-protocol.ts
index 4450f76eb6a..b17df23bfbb 100644
--- a/apps/desktop/src/api/canonical-protocol.ts
+++ b/apps/desktop/src/api/canonical-protocol.ts
@@ -92,7 +92,10 @@ export function pickerModelMutation(value: unknown): { model: string; provider:
}
function mutationSummary(operation: string, value: Record<string, unknown>): string {
- if (operation === 'model') { return `model: ${value.model}${value.provider ? ` (${value.provider})` : ''}` }
+ if (operation === 'model') {
+ // `/model reset` already on the configured default answers with the owner's note.
+ return typeof value.note === 'string' ? value.note : `model: ${value.model}${value.provider ? ` (${value.provider})` : ''}`
+ }
if (operation === 'branch') { return `branch: ${value.branched_session_id}` }
diff --git a/gateway/session_deferred_pick.py b/gateway/session_deferred_pick.py
index e4ae51e3a21..0feb96f29f0 100644
--- a/gateway/session_deferred_pick.py
+++ b/gateway/session_deferred_pick.py
@@ -26,6 +26,11 @@ def defer_pick(authority, actor, ref, params):
from hermes_state_runtime import _epoch, _json, mutation_receipt_key, replay_mutation_receipt
operation = params.get('operation', 'model')
validate_action(operation, params['payload'])
+ shown = None
+ if operation == 'model':
+ from gateway.session_mutation_model import configured_default, is_model_reset
+ if is_model_reset(params['payload']): # a queued reset shows the default it adopts, not "reset"
+ shown = configured_default(authority)[0]
key, digest = mutation_receipt_key(actor.subject, ref.session_id, params['request_id'], operation=operation,
payload=params['payload'], expected_revision=params.get('expected_revision'),
expected_generation=params.get('expected_generation'))
@@ -51,7 +56,7 @@ def defer_pick(authority, actor, ref, params):
# slot never holds both, so committing the slot's level never strips the model's own.
older = 'reasoning' in current and 'reasoning' not in params['payload']
value = {**pick, **({'reasoning': current['reasoning']} if older else {})}
- picked = {'model': params['payload']['model']}
+ picked = {'model': shown or params['payload']['model']}
result = {'session_id': ref.session_id, 'operation': operation, 'status': 'deferred', **picked,
'revision': row[0], 'execution_generation': row[1]}
conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value',
diff --git a/gateway/session_messaging_picks.py b/gateway/session_messaging_picks.py
index 52c4fda274a..5e535e0e326 100644
--- a/gateway/session_messaging_picks.py
+++ b/gateway/session_messaging_picks.py
@@ -36,13 +36,16 @@ def _apply_reasoning(runner, live, 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.session_mutation_model import _Route, _selection_guard_refusal, is_model_reset
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()
+ if is_model_reset(payload): # the chat's own `/model reset`: its override goes, its reply is the note
+ note = await runner._handle_model_reset(None, ctx)
+ return {'model': (await asyncio.to_thread(messaging_route_info, runner, live))['model'], 'note': note}
# After a restart the chat's saved provider/base_url is only on disk: resolve against it, not
# config.yaml's provider, or the record step overwrites it (as run_turn_prepare rehydrates).
runner._rehydrate_session_model_override(live.route)
diff --git a/gateway/session_mutation_model.py b/gateway/session_mutation_model.py
index a1c8128acdc..0d11ba59e21 100644
--- a/gateway/session_mutation_model.py
+++ b/gateway/session_mutation_model.py
@@ -49,6 +49,11 @@ async def prepare_model(authority, live, payload, prepared):
from hermes_cli.config import get_compatible_custom_providers
old = restore_policy(prepared['snapshot']['receipt']['policy'])
config, current = _current_route(authority, live, old)
+ reset = is_model_reset(payload)
+ if reset:
+ payload = await asyncio.to_thread(_reset_payload, authority, old, current)
+ if 'status' in payload:
+ return payload
# A pick is an explicit user action: it resolves against the owning profile's CURRENT named
# providers, as CLI/TUI ``/model`` do (#139740). A following session's ``config`` already is
# the profile's current read; every other session keeps ``config`` for its own route below.
@@ -65,7 +70,9 @@ async def prepare_model(authority, live, payload, prepared):
custom_providers=get_compatible_custom_providers(resolution))
if not result.success:
raise RuntimeStoreError('model_resolution_failed')
- refusal = await _selection_guard_refusal(authority, live, payload, prepared['snapshot'], current, result)
+ # The configured default is the user's own choice: a reset is never held behind a cost ask.
+ refusal = None if reset else await _selection_guard_refusal(
+ authority, live, payload, prepared['snapshot'], current, result)
if refusal is not None:
return refusal
frozen = old.config()
@@ -146,6 +153,45 @@ async def prepare_model(authority, live, payload, prepared):
return dict(prepared, policy=asdict(policy))
+def is_model_reset(payload):
+ """``/model reset`` as a ``model`` mutation; with any other selection field it is refused, as on
+ every surface (``parse_model_switch_args``)."""
+ from hermes_cli.model_switch import (
+ MODEL_SWITCH_ERR_RESET_WITH_FLAGS, MODEL_SWITCH_ERROR_TEXT, MODEL_SWITCH_RESET_TOKEN)
+ if payload['model'].strip().lower() != MODEL_SWITCH_RESET_TOKEN:
+ return False
+ if set(payload) - {'model', 'confirm'}:
+ raise RuntimeStoreError('invalid_params', field='payload',
+ detail=MODEL_SWITCH_ERROR_TEXT[MODEL_SWITCH_ERR_RESET_WITH_FLAGS])
+ return True
+
+
+def configured_default(authority):
+ """``(model, provider)`` the owning profile's config.yaml names now (``auto`` reads as no provider)."""
+ from gateway.run import _resolve_gateway_model
+ from gateway.session_policy import profile_config
+ profile = profile_config(authority)
+ block = profile.get('model')
+ if not block:
+ return '', ''
+ provider = str(block.get('provider') or '') if isinstance(block, dict) else ''
+ return _resolve_gateway_model(profile), '' if provider.lower() == 'auto' else provider
+
+
+def _reset_payload(authority, old, current):
+ """``/model reset``: the pick becomes the owning profile's configured model, read fresh, so the
+ session runs (and, when following, keeps following) its profile again; history is kept. Returns a
+ ``noop`` report when the session already runs that model. A safe-mode session never read the
+ profile, so it has no configured default to return to."""
+ from agent.i18n import t
+ model, provider = ('', '') if old.ignore_user_config else configured_default(authority)
+ if not model:
+ raise RuntimeStoreError('invalid_params', field='payload.model', detail=t('cli.model.reset_no_default'))
+ if model == current.model and provider in ('', current.provider):
+ return {'status': 'noop', 'model': model, 'note': t('cli.model.reset_none', model=model)}
+ return {'model': model, **({'provider': provider} if provider else {})}
+
+
def _provider_resolution_config(authority, config, bypass=False):
"""*config* with the owning profile's CURRENT named providers over its frozen ones, used only to
resolve and freeze a pick. Reads this owner's own config.yaml (never another profile's); a
diff --git a/hermes_cli/gateway_chat_view.py b/hermes_cli/gateway_chat_view.py
index 1dd34a8d902..e9ea49802b7 100644
--- a/hermes_cli/gateway_chat_view.py
+++ b/hermes_cli/gateway_chat_view.py
@@ -400,9 +400,10 @@ class GatewayChatView:
print('\n'.join(result['lines']))
return True
if result.get('status') == 'noop':
- # Nothing removable: main's report, nothing committed (gateway/session_mutation_compress.py).
+ # Nothing removable (gateway/session_mutation_compress.py), or a `/model reset` already
+ # on the configured default (its note): main's report, nothing committed.
self.mutations.acknowledge(original, operation, payload)
- summary = result.get('summary') or {}
+ summary = result.get('summary') or {'note': result.get('note')}
print('\n'.join(filter(None, (summary.get('headline'), summary.get('token_line'), summary.get('note')))))
return True
target = result.get('branched_session_id', original)
diff --git a/tests/gateway/test_model_reset_command.py b/tests/gateway/test_model_reset_command.py
index f3c9547f4d8..fe8447374ca 100644
--- a/tests/gateway/test_model_reset_command.py
+++ b/tests/gateway/test_model_reset_command.py
@@ -1,4 +1,5 @@
-"""Gateway ``/model reset``: a persisted session override is cleared without losing the chat."""
+"""``/model reset``: a messaging chat's persisted override is cleared, and a local (TUI/Desktop/CLI) session's
+owner pin returns to the profile's configured default, without losing the conversation."""
import json
from types import SimpleNamespace
@@ -54,3 +55,49 @@ async def test_reset_clears_a_persisted_override_after_restart(tmp_path, monkeyp
again = await runner._handle_model_command(_event("/model reset", source))
assert again != reply and "cfg-model" in again # nothing left to clear: the "none active" copy
assert evicted == [key]
+
+
+async def test_owner_reset_returns_a_local_session_to_the_configured_default_read_fresh(monkeypatch):
+ """The TUI, Desktop and the attached CLI send ``session.mutate model {model: 'reset'}`` to the owner."""
+ from gateway.run_turn_prepare import GatewayTurnPrepareMixin
+ from gateway.session_policy import policy_for_source
+ from hermes_constants import get_hermes_home
+ from tests.gateway.test_follow_profile_followups import _profile
+ from tests.gateway.test_session_follow_profile_config import _owner
+ import gateway.run as gateway_run
+
+ home = get_hermes_home()
+ home.mkdir(parents=True, exist_ok=True)
+ monkeypatch.setattr(gateway_run, "_hermes_home", home)
+ _profile(home, "cfg-a", 1, "k")
+ store, runner, authority, owner = _owner(home)
+ runner._peek_session_state = lambda key: None
+ runner._resolve_session_agent_runtime = (
+ lambda **kw: GatewayTurnPrepareMixin._resolve_session_agent_runtime(runner, **kw))
+ try:
+ created = await owner.dispatch({"id": "c", "method": "session.create", "params": dict(
+ request_id="c", source="tui", cwd=str(home), toolsets=[])})
+ sid = created["result"]["session_id"]
+ live = authority.sessions[sid]
+
+ async def pick(model):
+ snap = authority.db.get_session(sid)
+ response = await owner.dispatch({"id": model, "method": "session.mutate", "params": dict(
+ session_id=sid, request_id=f"{model}-{snap['runtime_revision']}", operation="model",
+ payload={"model": model}, expected_revision=snap["runtime_revision"],
+ expected_generation=snap["runtime_generation"])})
+ return response["result"]
+
+ await pick("other-model")
+ assert policy_for_source(runner, live.source).model == "other-model"
+ _profile(home, "cfg-b", 1, "k") # edited after launch: reset reads config.yaml now
+ await pick("reset")
+ assert policy_for_source(runner, live.source).model == "cfg-b"
+ revision = authority.db.get_session(sid)["runtime_revision"]
+ again = await pick("reset")
+ assert again["status"] == "noop" and "cfg-b" in again["note"] # nothing to reset, nothing written
+ assert authority.db.get_session(sid)["runtime_revision"] == revision
+ finally:
+ await owner.close()
+ store.close_all_db_handles()
diff --git a/ui-tui/src/app/slash/canonicalSessionControls.ts b/ui-tui/src/app/slash/canonicalSessionControls.ts
index 023fea43a9b..300d68cb818 100644
--- a/ui-tui/src/app/slash/canonicalSessionControls.ts
+++ b/ui-tui/src/app/slash/canonicalSessionControls.ts
@@ -289,7 +289,8 @@ function applyModelResult(result: CanonicalControlResult, sys: (text: string) =>
tools: state.info?.tools ?? {}
}
}))
- sys(t('session.main.modelSwitched', result.model))
+ // `/model reset` on a session already on the configured default: the owner's note, nothing changed.
+ sys(typeof result.note === 'string' ? result.note : t('session.main.modelSwitched', result.model))
if (typeof result.effort === 'string') {
// The level committed in the same selection (a deferred result carries none yet).