The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): make a Bot Chat follow its profile, whoever created it
David Dudok de Wit7dd3f98df3e1
diff --git a/gateway/session_bot.py b/gateway/session_bot.pyindex 662a86e0b8a..60a107290be 100644--- a/gateway/session_bot.py+++ b/gateway/session_bot.py@@ -207,7 +207,7 @@ async def _create_bot_chat(authority, actor):principal (owner recovery) still gets ``not_found``."""if 'session:create' not in actor.capabilities:raise RuntimeStoreError('not_found')- from gateway.session_local import stage_local_session+ from gateway.session_local import stage_local_session, staged_creation_followsfrom gateway.session_local_recovery import restore_local_sessionfrom gateway.session_local_title import title_new_sessionfrom gateway.session_runtime_workers import tracked_write@@ -218,8 +218,15 @@ async def _create_bot_chat(authority, actor):async with lock:if authority.db.get_session_by_title('Bot Chat') is not None:return None- ref = stage_local_session(authority, actor, {- 'request_id': _bot_chat_creation_id(authority, actor), 'source': 'cli', 'cwd': str(Path.home())})+ # The Bot Chat follows its profile whoever mints it (a Bot or cron delivery, a peer DM),+ # the same contract Desktop's create asks for. A later profile change reaches it.+ request_id = _bot_chat_creation_id(authority, actor)+ params = {'request_id': request_id, 'source': 'cli', 'cwd': str(Path.home()),+ 'follow_profile_config': True}+ # A creation staged by an older build, before this flag, resumes as it was staged.+ if not staged_creation_follows(authority, actor, request_id):+ params.pop('follow_profile_config')+ ref = stage_local_session(authority, actor, params)if isinstance(ref, dict):await tracked_write(authority, partial(commit_local_session, authority.db, epoch=authority.epoch, receipt=ref))ref = restore_local_session(authority, ref['session_id'])diff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex 1e01a6ee901..8d2cc01a1f9 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -417,9 +417,10 @@ class AuthorityConnection:return await self._create(params, title)async def _create(self, params, title):- from gateway.session_local import stage_local_session+ from gateway.session_local import stage_local_session, staged_creation_followsfrom gateway.session_local_recovery import restore_local_sessionfrom gateway.session_local_title import resolve_titled_session, title_new_session+ from gateway.session_policy import BYPASS_FIELDSfrom gateway.session_runtime_workers import tracked_writefrom hermes_state_local import commit_local_session# Bot Mode's forever-chat mint: born hidden from the sidebar. `follow_profile_config` stays in@@ -428,6 +429,13 @@ class AuthorityConnection:if type(hidden) is not bool:raise RuntimeStoreError('invalid_params', field='hidden', detail='must be a boolean')ref = title and resolve_titled_session(self.authority, self.actor, title, missing_ok=True)+ if (not ref and title == 'Bot Chat'+ and not any(params.get(name) is True for name in BYPASS_FIELDS)+ and staged_creation_follows(self.authority, self.actor, params.get('request_id'))):+ # ``chat -c "Bot Chat" --create-if-missing`` and any other titled create. A safe-mode+ # or ignore-user-config launch never reads the profile, so it stays frozen. An exact+ # retry of a creation staged without the flag keeps that frozen request.+ params.setdefault('follow_profile_config', True)if not ref:skills_prompt = Noneif 'skills' in params:@@ -594,11 +602,12 @@ class AuthorityConnection:# reopens it (``reopen_local_session`` in the drain), so opening a finished chat# never re-lights DB-derived liveness with no new activity.self.authority.authorize(self.actor, ref, 'session:read')- if 'session:control' in self.actor.capabilities and ref.session_id not in self.subscriptions:+ if 'session:control' in self.actor.capabilities:# A client attaching (main's `hermes -c` was a new process) re-reads the config-derived settings- # (CFG-2); a snapshot poll on this attachment does not.+ # (CFG-2); a snapshot poll on this attachment does not. Any open still adopts a frozen Bot Chat+ # whose earlier open found it busy (Desktop's warm `session.activate` resumes on one connection).from gateway.session_policy_refresh import refresh_resumed_policy- await refresh_resumed_policy(self.authority, ref)+ await refresh_resumed_policy(self.authority, ref, attached=ref.session_id in self.subscriptions)snapshot = await self.authority.attach(self.actor, ref)self.subscriptions[ref.session_id] = snapshot.subscription_idself._spawn_notice(ref)diff --git a/gateway/session_local.py b/gateway/session_local.pyindex c7e3bdac1ab..f3745456d14 100644--- a/gateway/session_local.py+++ b/gateway/session_local.py@@ -4,6 +4,7 @@ Source and supported launch settings are frozen per route, never process env."""from __future__ import annotations+import jsonimport loggingimport uuidfrom contextlib import contextmanager@@ -212,6 +213,28 @@ def create_local_session(authority, actor, params, *, trusted_policy=None, trustreturn staged+def staged_creation_follows(authority, actor, request_id):+ """Whether a retry of *request_id* may ask to follow the profile.++ True when nothing is staged under that identity, or the staged request already follows.+ False only when an older build committed the session without ``follow_profile_config`` and+ stopped before its title. The next attempt reuses the identity, and a different request is+ refused for good. The retry then carries the frozen request.+ """+ if not isinstance(request_id, str) or not request_id:+ return True+ from gateway.session_local_recovery import local_identity+ from hermes_state_local import local_receipt+ sid = local_identity(authority.profile_id, actor.subject, request_id)+ if authority.db.get_session(sid) is None:+ return True+ try:+ request = json.loads(local_receipt(authority.db, sid)['policy']['request_json'])+ except (KeyError, TypeError, ValueError, RuntimeStoreError):+ return True+ return isinstance(request, dict) and request.get('follow_profile_config') is True++def stage_local_session(authority, actor, params, *, trusted_policy=None, trusted_secrets=None, skills_prompt=None,client_local=False):"""Everything before the creation commit: the existing session's ref on an exact retry, else thediff --git a/gateway/session_local_migration.py b/gateway/session_local_migration.pyindex b1491f027f1..e97e515b161 100644--- a/gateway/session_local_migration.py+++ b/gateway/session_local_migration.py@@ -111,6 +111,78 @@ def legacy_launch_params(row):return params, route.get('api_mode')+def bot_chat_row(row):+ """Main's Bot Chat rule for a stored row: the ``follow_profile_config`` marker, or, for a row+ written before the marker existed, the exact title ``Bot Chat``."""+ from hermes_state_sessions import _parse_model_config+ saved = _parse_model_config(row.get('model_config'))+ return saved.get('follow_profile_config') is True or str(row.get('title') or '').strip() == 'Bot Chat'+++def composer_pick_holds(row, config):+ """Whether *row*'s composer pick still holds: the profile (*config*) targets what it diverged from."""+ from gateway.session_policy import profile_target+ from hermes_state_sessions import _parse_model_config+ composer = _parse_model_config(row.get('model_config')).get('composer_override_profile')+ return isinstance(composer, dict) and (+ str(composer.get('model') or '').strip(), str(composer.get('provider') or '').strip(),+ ) == profile_target(config)+++def legacy_bot_chat_launch(row, params, api_mode, config):+ """``(params, api_mode)`` for adoption. A Bot Chat (``bot_chat_row``) follows its profile.++ A composer pick is kept only while the profile still targets what the pick diverged from, and+ is adopted the way a create records one: held until the next profile edit. Otherwise only the+ workspace and source carry over, so the route last run is not frozen and its wire mode is not+ either. Any other row is unchanged.+ """+ if not bot_chat_row(row):+ return params, api_mode+ if not ('model' in params and composer_pick_holds(row, config)):+ params = {key: params[key] for key in ('cwd', 'source') if key in params}+ api_mode = None+ return {**params, 'follow_profile_config': True}, api_mode+++def follow_bot_chat(authority, session_id, policy, live, picked=()):+ """*policy* following its profile when the session is a Bot Chat an earlier build committed+ frozen (its delivery door, a CLI titled create, an adoption), else *policy* itself.++ The caller is a client opening the chat (``session.resume``), which adopts it on the same rule+ and composer pick as adoption above; *live* is the profile's config the open read. A request+ that names ``follow_profile_config`` (``false`` included) is the client's own choice, and a+ bypass launch never reads the profile. The request is not rewritten. A committed ``/reasoning``+ (*picked*, the session's policy edits) stays the session's level, recorded as its session pin.+ The caller re-binds the private values without the followed sections, so a frozen key never+ reaches the profile's route.+ """+ from gateway.session_policy import FOLLOW_ADOPTED, SESSION_PINS, present_sections, profile_target+ if (policy.follows_profile or policy.ignore_user_config+ or 'follow_profile_config' in json.loads(policy.request_json)):+ return policy+ db = authority.db+ owner = db.get_session(session_id) or {}+ if not bot_chat_row(owner):+ # Compression can carry the canonical title to a later segment of the same conversation.+ titled = db.get_session_by_title('Bot Chat')+ if titled is None:+ return policy+ from hermes_state_local import local_conversation_ids+ with db._read_ctx() as conn:+ if titled['id'] not in local_conversation_ids(conn, session_id):+ return policy+ live = present_sections(live)+ config = json.loads(policy.config_json)+ if composer_pick_holds(owner, live):+ # Recorded the way a create records a pick: it holds until the profile's model or provider moves.+ config.setdefault('model', {})['selection_profile'] = list(profile_target(live))+ pins = config.get(SESSION_PINS) if isinstance(config.get(SESSION_PINS), dict) else {}+ if 'reasoning' in picked and not isinstance(pins.get('reasoning'), bool):+ config[SESSION_PINS] = {**pins, 'reasoning': True}+ return replace(policy, config_json=json.dumps({**config, FOLLOW_ADOPTED: True}))++def _route_is_usage_stamp(row):"""True when the row's only route record is the ``billing_provider='custom'`` + ``billing_base_url``usage stamp: no ``gateway_runtime`` and no top-level ``provider``/``base_url`` in ``model_config``.@@ -175,6 +247,7 @@ def adopt_legacy_session(authority, actor, row):params['source'] = LEGACY_CREATION_SOURCES.get(row['source'], row['source'])private = {}config = _load_gateway_config()+ params, api_mode = legacy_bot_chat_launch(row, params, api_mode, config)model_cfg = config.get('model')if isinstance(model_cfg, dict) and ('provider' in params or 'base_url' in params):from gateway.session_route_identity import ROUTE_BOUND_KEYS, resolved_route, same_route@@ -208,8 +281,18 @@ def adopt_legacy_session(authority, actor, row):config = json.loads(policy.config_json)config.setdefault('model', {})['api_mode'] = api_modepolicy = replace(policy, config_json=json.dumps(config))- if policy.model is None:- policy = replace(policy, model=_resolve_gateway_model(policy.config()))+ # restore_policy rejects a blank model, and the commit below is what the next open reads.+ # A following Bot Chat drops the saved name out of the request, so a profile with no+ # default would store ''. Put a name on the receipt only: the profile's resolved model,+ # else the row's. The request is unchanged, so a later profile default still wins.+ named = str(policy.model or '').strip() or (_resolve_gateway_model(policy.config()) or '').strip()+ if not named:+ named = str(row.get('model') or '').strip()+ if not named:+ raise RuntimeStoreError('invalid_params', field='model',+ detail='the profile names no model and the saved session has none')+ if policy.model != named:+ policy = replace(policy, model=named)policy = bind_launch_key(authority, sid, policy, None, config_secrets=private)from gateway.session_local_recovery import local_sourcesource = local_source(authority, sid, actor.subject)diff --git a/gateway/session_policy.py b/gateway/session_policy.pyindex bdd170b5403..81f51972748 100644--- a/gateway/session_policy.py+++ b/gateway/session_policy.py@@ -20,6 +20,23 @@ CREATE_FIELDS = frozenset({'request_id', 'source', 'cwd', 'model', 'toolsets',# turn (main's Bot Chat row), credentials included: a frozen key never crosses a profile route change.FOLLOW_SECTIONS = ('model', 'providers', 'custom_providers', 'fallback_providers', 'fallback_model', 'model_aliases','platform_toolsets')+# A Bot Chat an earlier build committed frozen follows its profile once a client opens it (``follow_bot_chat``).+# The marker sits in the policy's own config, so no other receipt changes shape (an older owner restores+# them all, and reads this chat as frozen), and the creation request, the exact-retry identity, stays as sent.+FOLLOW_ADOPTED = 'follow_adopted'+# A launch field's state as a committed session edit left it, in the policy's own config: ``True`` the+# session chose it (``/reasoning <level>``, a model pick carrying one), ``False`` a reset gave it back to+# the profile. Either wins over the creation request (the launch identity, never rewritten) and the older+# pick receipts.+SESSION_PINS = 'session_pins'+++def session_pinned(config, field, launched):+ """Whether *field* is the session's own choice: its last committed session edit, else *launched*."""+ pins = config.get(SESSION_PINS)+ return pins[field] if isinstance(pins, dict) and isinstance(pins.get(field), bool) else launched++def pin_reasoning_effort(config, effort):"""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."""@@ -120,9 +137,10 @@ class LocalSessionPolicy:if live:frozen, request = config.get('model') or {}, json.loads(self.request_json)pick = frozen.get('selection_profile')- held = pick is not None and pick == list(profile_target(live))+ held = pick is not None and pick == list(profile_target(live)) and entry_serves(frozen, live)pinned = {'platform_toolsets', 'disabled_toolsets'} if 'toolsets' in request else set()- pinned |= {'reasoning_effort', 'reasoning_overrides'} if 'reasoning' in request else set()+ chosen = session_pinned(config, 'reasoning', 'reasoning' in request)+ pinned |= {'reasoning_effort', 'reasoning_overrides'} if chosen else set()pinned |= {'service_tier'} if 'service_tier' in request else set()for key in FOLLOW_SECTIONS:if key in pinned:@@ -155,7 +173,8 @@ class LocalSessionPolicy:@propertydef follows_profile(self):- return json.loads(self.request_json).get('follow_profile_config') is True+ return (json.loads(self.request_json).get('follow_profile_config') is True+ or json.loads(self.config_json).get(FOLLOW_ADOPTED) is True)def read_profile(self, authority):"""The owning profile's current config for a following session, else None; inside this policy's@@ -289,6 +308,29 @@ def bound_route_holds(bound, bound_config, block, config):return same_route({**bound, 'base_url': url} if url else bound, block, config)+def entry_serves(block, config):+ """False when *block* pins a ``base_url`` that the config entry its credential comes from no longer+ serves in *config*: its named provider (``providers:`` / ``custom_providers:``), or the alias its+ ``api_key_from`` points into. That entry's key (inline, ``key_env``, ``key_cmd``) authenticates the+ entry's own endpoint, so a pick held on the old one ends rather than carry the new key there."""+ from hermes_cli.route_identity import normalize_route_base_url+ block = block if isinstance(block, dict) else {}+ url = normalize_route_base_url(block.get('base_url'))+ if not url:+ return True+ from gateway.session_route_identity import _named_entry+ provider = str(block.get('provider') or '').strip()+ entries = [_named_entry(provider, config)] if provider else []+ source = block.get('api_key_from')+ if isinstance(source, list) and len(source) > 1:+ alias = config+ for part in source[:-1]:+ alias = alias.get(part) if isinstance(alias, dict) else None+ entries.append(alias)+ return all(normalize_route_base_url(entry.get('base_url')) == url for entry in entries+ if isinstance(entry, dict) and str(entry.get('base_url') or '').strip())++def _held_pick(frozen, live):"""A pick that still holds keeps its selection; on the profile's own endpoint the rest of the``model:`` block (a rotated key included) is the profile's. Another endpoint never gets it."""@@ -344,9 +386,11 @@ def build_policy(params, config, *, private_secrets=None, profile_terminal=True,validate_editor(source, params.get('editor'))launch_skills(params)config = present_sections(json.loads(json.dumps(config)))- if params.get('follow_profile_config') is True and 'model' in params:- # The pick's provenance, recorded before the launch route folds in: it holds while the profile- # still targets this, and a later profile edit supersedes it.+ picked_route = {'model', 'provider', 'base_url'} & set(_without_auto_pick(params))+ if params.get('follow_profile_config') is True and picked_route:+ # Any explicit route pick (a model, a provider, an endpoint) records its provenance before the+ # launch route folds in: it holds while the profile still targets this, and a later profile edit+ # supersedes it. Without it the first turn's followed route replaces the pick.config.setdefault('model', {})['selection_profile'] = list(profile_target(config))_apply_launch_overrides(params, config)# The posture is opt-in (``session.create`` only) and needs a folder the client named: the daemon's owndiff --git a/gateway/session_policy_refresh.py b/gateway/session_policy_refresh.pyindex d13f58ca24c..58105d8f0ce 100644--- a/gateway/session_policy_refresh.py+++ b/gateway/session_policy_refresh.py@@ -5,7 +5,8 @@ and the reasoning default came from the config it started with, while the storedThe owner keeps that line on ``session.resume``: it re-derives exactly those fields from the session profile'scurrent config and commits them as a new policy generation. ``reload.mcp`` commits the MCP part alone for thecalling session. The creation flags (request_json), the model route and a committed ``/reasoning`` or workspace-pick stay; a session with a turn running or queued keeps the policy that turn was admitted under.+pick stay; a session with a turn running or queued keeps the policy that turn was admitted under. A Bot Chat an+earlier build committed frozen follows its profile from the open on (``follow_bot_chat``)."""import asyncioimport json@@ -131,9 +132,10 @@ def _server_name(servers, name):return name[4:] if name.startswith('mcp-') and name not in servers else name-def _prepare(authority, session_id, mcp_only=False):+def _prepare(authority, session_id, mcp_only=False, adopt_only=False):"""Off the owner loop: the stored policy, its refresh from this profile home's files, and the generation- it was derived at. None when the session takes no refresh or nothing moved."""+ it was derived at. None when the session takes no refresh or nothing moved. *adopt_only*: the adoption+ of a frozen Bot Chat alone, without the config-derived settings (a later open on the same attachment)."""from gateway.run import _load_gateway_configfrom gateway.session_policy import SURFACES, restore_policyfrom hermes_state_local import local_receipt@@ -146,24 +148,41 @@ def _prepare(authority, session_id, mcp_only=False):if old.ignore_user_config or old.source not in SURFACES:return Nonehome = Path(authority.db.db_path).resolve().parent- terminal = {} if mcp_only else build_profile_terminal_scope(home)- policy, secrets, replaced = refreshed_policy(old, _load_gateway_config(home / 'config.yaml'), terminal,- picked=policy_picks(authority.db, session_id), mcp_only=mcp_only)+ terminal = {} if mcp_only or adopt_only else build_profile_terminal_scope(home)+ live, picked = _load_gateway_config(home / 'config.yaml'), policy_picks(authority.db, session_id)+ base = old+ if not mcp_only:+ # Opening a Bot Chat an earlier build froze adopts it: it follows its profile from now on.+ from gateway.session_local_migration import follow_bot_chat+ base = follow_bot_chat(authority, session_id, old, live, picked)+ if adopt_only:+ return None if base is old else (stored, old, base, {}, set(), generation)+ policy, secrets, replaced = refreshed_policy(base, live, terminal, picked=picked, mcp_only=mcp_only)return None if policy is old else (stored, old, policy, secrets, replaced, generation)def _rebind(authority, session_id, old, policy, fresh, replaced):"""Re-bind the private values like a policy mutation: policy identity covers config and terminal, and therefreshed sections' private values are the profile's current ones (the stored ones there are neither- re-read nor checked: a rotated key is what the refresh picks up, not a revoked credential)."""+ re-read nor checked: a rotated key is what the refresh picks up, not a revoked credential). A policy+ that follows its profile from this open on keeps none of its followed sections' frozen values."""from gateway.session_policy import FOLLOW_SECTIONS, bind_launch_key, launch_keyfrom gateway.session_policy_credentials import recover_config_secrets- skip = (*(FOLLOW_SECTIONS if old.follows_profile else ()), *replaced)+ skip = (*(FOLLOW_SECTIONS if policy.follows_profile else ()), *replaced)secrets = recover_config_secrets(authority, old, skip) if old.config_secret_ref else {}secrets.update(fresh)return bind_launch_key(authority, session_id, policy, launch_key(authority, old), config_secrets=secrets)+def _pending_adoptions(authority):+ """Frozen Bot Chats an open found to adopt but could not commit (a turn running or queued, a concurrent+ edit): the next open retries, whether or not that client is already attached."""+ found = getattr(authority, '_pending_adoptions', None)+ if found is None:+ found = authority._pending_adoptions = set()+ return found++def _in_flight(authority):found = getattr(authority, '_policy_refreshes', None)if found is None:@@ -181,7 +200,7 @@ async def refresh_settled(authority, session_id):await asyncio.wait({running}) # its outcome is its caller's; a cancelled waiter leaves it running-async def commit_refresh(authority, ref, *, mcp_only=False):+async def commit_refresh(authority, ref, *, mcp_only=False, adopt_only=False):"""Commit an idle local session's refresh as its next policy generation: True when one was committed,False when nothing moved. Raises the store's refusal (``session_busy`` while a turn runs or waits).One refresh per session at a time, run to its publication even when the caller is cancelled: a second@@ -189,19 +208,23 @@ async def commit_refresh(authority, ref, *, mcp_only=False):from gateway.session_runtime_workers import track_mutationawait refresh_settled(authority, ref.session_id)refreshes = _in_flight(authority)- task = refreshes[ref.session_id] = track_mutation(authority, _commit_refresh(authority, ref, mcp_only))+ task = refreshes[ref.session_id] = track_mutation(authority, _commit_refresh(authority, ref, mcp_only, adopt_only))task.add_done_callback(lambda done: refreshes.pop(ref.session_id, None) if refreshes.get(ref.session_id)is done else None)return await asyncio.shield(task)-async def _commit_refresh(authority, ref, mcp_only):+async def _commit_refresh(authority, ref, mcp_only, adopt_only=False):from gateway.session_runtime_workers import tracked_writefrom hermes_state_mutation_prepared import commit_refreshed_policy- prepared = await asyncio.to_thread(_prepare, authority, ref.session_id, mcp_only)+ prepared = await asyncio.to_thread(_prepare, authority, ref.session_id, mcp_only, adopt_only)+ pending = _pending_adoptions(authority)if prepared is None:+ pending.discard(ref.session_id)return Falsestored, old, policy, secrets, replaced, generation = prepared+ if policy.follows_profile and not old.follows_profile:+ pending.add(ref.session_id) # until this commit landsmoved = json.loads(policy.terminal_json) != json.loads(old.terminal_json)policy = _rebind(authority, ref.session_id, old, policy, secrets, replaced)# Compare-and-swap against the receipt as stored (JSON lists), not its restored tuple form. The@@ -211,15 +234,21 @@ async def _commit_refresh(authority, ref, mcp_only):session_id=ref.session_id, old=stored, new=asdict(policy),generation=generation),then=lambda _generation: _publish(authority, ref, moved))+ pending.discard(ref.session_id)return True-async def refresh_resumed_policy(authority, ref):+async def refresh_resumed_policy(authority, ref, *, attached=False):"""Commit the config refresh of an idle local session before it is attached. Never fails the resume:a busy session, a revoked launch credential or an unreadable profile keeps the stored policy. Only a turn- running or queued (or admitted during the commit) is expected; anything else is a WARNING."""+ running or queued (or admitted during the commit) is expected; anything else is a WARNING.++ *attached*: this client already holds the session (Desktop's warm reopen). The settings refresh is once+ per attachment, but a frozen Bot Chat whose adoption a busy open refused is adopted on any later open."""+ if attached and ref.session_id not in _pending_adoptions(authority):+ returntry:- await commit_refresh(authority, ref)+ await (commit_refresh(authority, ref, adopt_only=True) if attached else commit_refresh(authority, ref))except Exception as exc: # health: allow BLE001 -- a refresh is best-effort; the resume itself must proceedreason = getattr(exc, 'reason', None) or type(exc).__name__busy = reason in {'session_busy', 'unknown_execution', 'revision_conflict'}diff --git a/tests/gateway/test_bot_chat_follows_profile.py b/tests/gateway/test_bot_chat_follows_profile.pynew file mode 100644index 00000000000..5c812cb3689--- /dev/null+++ b/tests/gateway/test_bot_chat_follows_profile.py@@ -0,0 +1,577 @@+"""A Bot Chat follows its profile's current route, whoever creates it.++Desktop's create asks for ``follow_profile_config``. The Bot/cron delivery door, a peer DM+create, a CLI ``chat -c "Bot Chat" --create-if-missing`` and the adoption of a pre-upgrade+Bot Chat used to freeze the route of that moment. Desktop later reuses the chat by title, so+a profile change never reached it, and retiring the old key broke it. A session that is not+a Bot Chat keeps the route it was created or saved with. A safe-mode Bot Chat stays frozen:+that launch never reads the profile. A Bot Chat an earlier build already froze follows from+the first time a client opens it; its creation request is not rewritten.++Real: SessionStore/SessionAuthority/AuthorityConnection, ``session_bot._target`` (the delivery+door), ``resolve_local_target`` -> ``adopt_legacy_session``, ``session.resume`` (the policy+refresh on open), a real config.yaml and ``GatewayTurnPrepareMixin._resolve_session_agent_runtime``.+Seam: a SimpleNamespace runner. No endpoint is contacted.+"""+import json+from pathlib import Path++import pytest++from tests.gateway.test_follow_profile_followups import _create_bot_chat, _profile+from tests.gateway.test_session_follow_profile_config import _owner, _route+++def home(monkeypatch):+ """The profile home the follow-profile tests write ``config.yaml`` into."""+ from gateway import run+ from hermes_constants import get_hermes_home+ profile = get_hermes_home()+ profile.mkdir(parents=True, exist_ok=True)+ monkeypatch.setattr(run, '_hermes_home', profile)+ return profile+++def _follows(runner, live):+ from gateway.session_policy import policy_for_source+ return policy_for_source(runner, live.source).follows_profile+++def _key(runner, authority, live):+ """The api_key the session's next turn sends, from its policy's one effective read.++ ``_route`` reports ``no-key-required`` for an adopted session, so a key check goes+ through ``effective``."""+ from gateway.session_policy import policy_for_source+ model = policy_for_source(runner, live.source).effective(authority)[0].get('model') or {}+ return model.get('api_key')++[email protected]('first', ['delivery', 'desktop', 'cli'])+async def test_bot_chat_follows_profile_whoever_creates_it(home, first):+ from gateway.session_bot import _target+ _profile(home, 'old-model', 1, 'old-key')+ store, runner, authority, owner = _owner(home)+ runner._peek_session_state = lambda key: None+ try:+ if first == 'delivery':+ _ref, live, _entry = await _target(authority, owner.actor)+ elif first == 'desktop':+ live = await _create_bot_chat(owner, authority, home, 'gui-first', title='Bot Chat', hidden=True)+ else:+ response = await owner.dispatch({'id': 'cli', 'method': 'session.create', 'params': dict(+ request_id='cli-first', source='cli', cwd=str(home), title='Bot Chat')})+ assert 'result' in response, response+ live = authority.sessions[response['result']['session_id']]+ # Desktop opening Bot Chat later is a titled create: it lands on the same session.+ reopened = await _create_bot_chat(owner, authority, home, 'gui-open', title='Bot Chat', hidden=True)+ assert reopened is live+ assert _route(runner, live) == ('old-model', 'http://127.0.0.1:1/v1', 'old-key')+ _profile(home, 'new-model', 2, 'new-key')+ assert _route(runner, live) == ('new-model', 'http://127.0.0.1:2/v1', 'new-key')+ assert _key(runner, authority, live) == 'new-key'+ finally:+ await owner.close()+ store.close_all_db_handles()++[email protected]('extra', [+ {'title': 'Notes'},+ {'title': 'Bot Chat', 'safe_mode': True, 'provider': 'custom', 'base_url': 'http://127.0.0.1:1/v1'},+ {'title': 'Bot Chat', 'ignore_user_config': True, 'provider': 'custom',+ 'base_url': 'http://127.0.0.1:1/v1'},+])+async def test_other_titles_and_bypass_launches_stay_frozen(home, extra):+ _profile(home, 'old-model', 1, 'old-key')+ store, runner, authority, owner = _owner(home)+ runner._peek_session_state = lambda key: None+ try:+ response = await owner.dispatch({'id': 'create', 'method': 'session.create', 'params': dict(+ request_id='create', source='cli', cwd=str(home), model='old-model', **extra)})+ assert 'result' in response, response+ live = authority.sessions[response['result']['session_id']]+ assert not _follows(runner, live)+ _profile(home, 'new-model', 2, 'new-key')+ assert not _follows(runner, live)+ assert _route(runner, live)[0] == 'old-model'+ finally:+ await owner.close()+ store.close_all_db_handles()+++async def test_delivery_resumes_a_creation_staged_without_the_follow_flag(home):+ """An older build staged the delivery's Bot Chat and stopped before its title. The next+ delivery reuses that creation identity and must not be refused for a new flag."""+ from gateway.session_bot import _bot_chat_creation_id, _target+ from gateway.session_local import stage_local_session+ from gateway.session_local_recovery import restore_local_session+ from hermes_state_local import commit_local_session+ _profile(home, 'old-model', 1, 'old-key')+ store, runner, authority, owner = _owner(home)+ runner._peek_session_state = lambda key: None+ try:+ request_id = _bot_chat_creation_id(authority, owner.actor)+ receipt = stage_local_session(authority, owner.actor, {+ 'request_id': request_id, 'source': 'cli', 'cwd': str(Path.home())})+ commit_local_session(authority.db, epoch=authority.epoch, receipt=receipt)+ staged = restore_local_session(authority, receipt['session_id'])+ ref, live, _entry = await _target(authority, owner.actor)+ assert ref.session_id == staged.session_id+ assert authority.db.get_session_by_title('Bot Chat')['id'] == staged.session_id+ assert not _follows(runner, live)+ finally:+ await owner.close()+ store.close_all_db_handles()+++async def test_cli_retries_a_titled_create_staged_without_the_follow_flag(home):+ """Same trap on ``session.create``: an exact retry of a request staged before the flag+ resumes that request instead of being refused. The CLI then opens its titled Bot Chat, which+ follows the profile; the request it was created with stays as staged."""+ from gateway.session_local import stage_local_session+ from hermes_state_local import commit_local_session, local_receipt+ _profile(home, 'old-model', 1, 'old-key')+ store, runner, authority, owner = _owner(home)+ runner._peek_session_state = lambda key: None+ try:+ receipt = stage_local_session(authority, owner.actor, {+ 'request_id': 'cli-retry', 'source': 'cli', 'cwd': str(home)})+ commit_local_session(authority.db, epoch=authority.epoch, receipt=receipt)+ response = await owner.dispatch({'id': 'retry', 'method': 'session.create', 'params': dict(+ request_id='cli-retry', source='cli', cwd=str(home), title='Bot Chat')})+ assert 'result' in response, response+ assert response['result']['session_id'] == receipt['session_id']+ live = authority.sessions[receipt['session_id']]+ assert authority.db.get_session_by_title('Bot Chat')['id'] == receipt['session_id']+ stored = local_receipt(authority.db, receipt['session_id'])['policy']+ assert stored['request_json'] == receipt['policy']['request_json']+ assert _follows(runner, live)+ finally:+ await owner.close()+ store.close_all_db_handles()+++def _legacy(db, profile, sid, **row):+ title = row.pop('title', None)+ db.create_session(sid, cwd=str(profile), **row)+ if title:+ db.set_session_title(sid, title)+ db.end_session(sid, 'tui_close')++[email protected]('marker', ['title', 'follow-marker'])+async def test_adopted_legacy_bot_chat_keeps_following(home, marker):+ from gateway.session_local_migration import resolve_local_target+ from gateway.session_policy import policy_for_source+ _profile(home, 'profile-model', 2, 'k2', agent={'reasoning_effort': 'low'})+ store, runner, authority, owner = _owner(home)+ runner._peek_session_state = lambda key: None+ db = authority.db+ _legacy(db, home, 'old-tui', source='tui', model='saved-model', model_config={+ 'provider': 'custom', 'base_url': 'http://127.0.0.1:1/v1', 'api_mode': 'chat_completions',+ 'reasoning_config': {'enabled': True, 'effort': 'high'}})+ bot_config = {'provider': 'custom', 'base_url': 'http://127.0.0.1:1/v1', 'api_mode': 'codex_responses'}+ if marker == 'follow-marker':+ bot_config['follow_profile_config'] = True+ _legacy(db, home, 'old-bot', source='gui', model='old-bot-model', model_config=bot_config,+ title='Bot Chat' if marker == 'title' else 'Renamed later')+ authority._native_legacy_transports = {owner.actor.transport_id: owner.actor}+ try:+ tui = authority.sessions[resolve_local_target(authority, owner.actor, 'old-tui').session_id]+ bot = authority.sessions[resolve_local_target(authority, owner.actor, 'old-bot').session_id]+ route = _route(runner, tui)+ reasoning = policy_for_source(runner, tui.source).current_reasoning_config(runner)+ assert (route[:2], reasoning.get('effort')) == (('saved-model', 'http://127.0.0.1:1/v1'), 'high')+ assert _key(runner, authority, tui) not in ('k2', 'k3')+ assert _follows(runner, bot)+ assert _route(runner, bot)[:2] == ('profile-model', 'http://127.0.0.1:2/v1')+ assert _key(runner, authority, bot) == 'k2'+ frozen = json.loads(policy_for_source(runner, bot.source).config_json).get('model') or {}+ assert frozen.get('api_mode') != 'codex_responses'+ _profile(home, 'moved-model', 3, 'k3', agent={'reasoning_effort': 'low'})+ assert _route(runner, bot)[:2] == ('moved-model', 'http://127.0.0.1:3/v1')+ assert _key(runner, authority, bot) == 'k3'+ assert _key(runner, authority, tui) not in ('k2', 'k3')+ assert _route(runner, tui)[:2] == ('saved-model', 'http://127.0.0.1:1/v1')+ finally:+ await owner.close()+ store.close_all_db_handles()+++async def test_adopted_desktop_chat_keeps_its_saved_route(home):+ from gateway.session_local_migration import resolve_local_target+ from gateway.session_policy import policy_for_source+ _profile(home, 'profile-model', 2, 'k2', agent={'reasoning_effort': 'low'})+ store, runner, authority, owner = _owner(home)+ runner._peek_session_state = lambda key: None+ db = authority.db+ _legacy(db, home, 'old-desktop', source='desktop', model='saved-model', model_config={+ 'provider': 'custom', 'base_url': 'http://127.0.0.1:1/v1', 'api_mode': 'chat_completions',+ 'reasoning_config': {'enabled': True, 'effort': 'high'}})+ authority._native_legacy_transports = {owner.actor.transport_id: owner.actor}+ try:+ live = authority.sessions[resolve_local_target(authority, owner.actor, 'old-desktop').session_id]+ reasoning = policy_for_source(runner, live.source).current_reasoning_config(runner)+ route = _route(runner, live)+ assert not _follows(runner, live)+ assert (route[:2], reasoning.get('effort')) == (('saved-model', 'http://127.0.0.1:1/v1'), 'high')+ assert _key(runner, authority, live) not in ('k2', 'k3')+ finally:+ await owner.close()+ store.close_all_db_handles()++[email protected]('shape', ['empty', 'provider-only'])+async def test_adopting_a_bot_chat_with_no_profile_model_stays_openable(home, shape):+ """A profile that names no model must not leave a Bot Chat receipt that restore rejects.++ ``{}``, and a provider plus key with no ``model.default``, both resolve to a blank model.+ Committing that blank name makes the first open ``storage_unavailable``, and every later+ open stays there after a model is added. The saved row's model is enough to open, and the+ chat follows once the profile has a default.+ """+ from gateway.session_local_migration import resolve_local_target+ from hermes_state_local import local_receipt+ if shape == 'empty':+ (home / 'config.yaml').write_text('{}\n')+ else:+ (home / 'config.yaml').write_text(json.dumps({'model': {+ 'provider': 'custom', 'base_url': 'http://127.0.0.1:1/v1', 'api_key': 'sk-provider-only'}}))+ store, runner, authority, owner = _owner(home)+ runner._peek_session_state = lambda key: None+ _legacy(authority.db, home, 'old-bot', source='gui', model='saved-model', title='Bot Chat',+ model_config={'provider': 'custom', 'base_url': 'http://127.0.0.1:9/v1'})+ authority._native_legacy_transports = {owner.actor.transport_id: owner.actor}+ try:+ opened = resolve_local_target(authority, owner.actor, 'old-bot')+ stored = local_receipt(authority.db, opened.session_id)['policy']['model']+ assert isinstance(stored, str) and stored.strip()+ _profile(home, 'added-model', 2, 'sk-added')+ authority.sessions.pop(opened.session_id, None)+ again = resolve_local_target(authority, owner.actor, 'old-bot')+ live = authority.sessions[again.session_id]+ assert _follows(runner, live)+ assert _route(runner, live)[:2] == ('added-model', 'http://127.0.0.1:2/v1')+ assert _key(runner, authority, live) == 'sk-added'+ finally:+ await owner.close()+ store.close_all_db_handles()+++async def test_adopted_bot_chat_keeps_a_composer_pick_until_the_profile_moves(home):+ from gateway.session_local_migration import resolve_local_target+ _profile(home, 'profile-model', 2, 'k2')+ store, runner, authority, owner = _owner(home)+ runner._peek_session_state = lambda key: None+ _legacy(authority.db, home, 'old-bot', source='gui', model='picked-model', title='Bot Chat', model_config={+ 'composer_override_profile': {'model': 'profile-model', 'provider': 'custom'}})+ authority._native_legacy_transports = {owner.actor.transport_id: owner.actor}+ try:+ bot = authority.sessions[resolve_local_target(authority, owner.actor, 'old-bot').session_id]+ assert _follows(runner, bot)+ assert _route(runner, bot)[:2] == ('picked-model', 'http://127.0.0.1:2/v1')+ assert _key(runner, authority, bot) == 'k2'+ _profile(home, 'moved-model', 3, 'k3')+ assert _route(runner, bot)[:2] == ('moved-model', 'http://127.0.0.1:3/v1')+ assert _key(runner, authority, bot) == 'k3'+ finally:+ await owner.close()+ store.close_all_db_handles()+++def _frozen_bot_chat(authority, actor, home, title='Bot Chat', **extra):+ """A chat an earlier build committed without the flag (its delivery door, a CLI titled create)."""+ from gateway.session_local import stage_local_session+ from gateway.session_local_recovery import restore_local_session+ from gateway.session_local_title import title_new_session+ from hermes_state_local import commit_local_session+ params = {'request_id': 'earlier-build', 'source': 'cli', 'cwd': str(home), **extra}+ receipt = stage_local_session(authority, actor, dict(params))+ commit_local_session(authority.db, epoch=authority.epoch, receipt=receipt)+ ref = restore_local_session(authority, receipt['session_id'])+ title_new_session(authority, ref, title)+ return ref, params+++async def _open(authority, ref):+ """Desktop opening a stored Bot Chat: ``session.resume`` by id on its own connection."""+ from gateway.session_controls import AuthorityConnection+ desktop = AuthorityConnection(authority, object(), {'user_id': 'human'})+ try:+ response = await desktop.dispatch({'id': 'open', 'method': 'session.resume',+ 'params': {'session_id': ref.session_id}})+ assert 'result' in response, response+ finally:+ await desktop.close()++[email protected]('moved', ['before-open', 'after-open'])+async def test_opening_a_frozen_bot_chat_makes_it_follow(home, moved):+ """A Bot Chat an earlier build froze kept its old route after any open. The open now adopts+ it once, durably, and the creation request stays the exact-retry identity."""+ from gateway.session_local import stage_local_session+ from hermes_state_local import local_receipt+ _profile(home, 'old-model', 1, 'old-key')+ store, runner, authority, owner = _owner(home)+ runner._peek_session_state = lambda key: None+ try:+ ref, params = _frozen_bot_chat(authority, owner.actor, home)+ live = authority.sessions[ref.session_id]+ request = local_receipt(authority.db, ref.session_id)['policy']['request_json']+ if moved == 'before-open':+ _profile(home, 'new-model', 2, 'new-key')+ await _open(authority, ref)+ if moved == 'after-open':+ _profile(home, 'new-model', 2, 'new-key')+ assert _route(runner, live) == ('new-model', 'http://127.0.0.1:2/v1', 'new-key')+ stored = local_receipt(authority.db, ref.session_id)['policy']+ assert stored['request_json'] == request and 'follow_adopted' not in stored+ assert json.loads(stored['config_json'])['follow_adopted'] is True+ generation = authority.db.get_session(ref.session_id)['runtime_generation']+ await _open(authority, ref)+ assert authority.db.get_session(ref.session_id)['runtime_generation'] == generation+ assert stage_local_session(authority, owner.actor, params).session_id == ref.session_id+ finally:+ await owner.close()+ store.close_all_db_handles()++[email protected]('extra', [{}, {'api_key': 'sk-launch-for-one'}], ids=['profile-key', 'launch-key'])+async def test_a_flipped_bot_chat_never_sends_its_frozen_key_to_the_profiles_new_endpoint(home, extra):+ """A frozen key (the profile's, or a CLI ``--api-key``) belongs to the old endpoint. After the+ open, the profile's new endpoint gets no key until the profile names one, and the private-value+ reference is re-derived: a fresh owner recovers the chat's other secrets, no frozen model key."""+ from gateway.session_policy import policy_for_source+ from hermes_state_local import local_receipt+ aux = {'auxiliary': {'vision': {'provider': 'custom', 'api_key': 'aux-key'}}}+ _profile(home, 'old-model', 1, 'old-key', **aux)+ store, runner, authority, owner = _owner(home)+ runner._peek_session_state = lambda key: None+ try:+ ref, _params = _frozen_bot_chat(authority, owner.actor, home, **extra)+ live = authority.sessions[ref.session_id]+ (home / 'config.yaml').write_text(json.dumps({'model': {+ 'provider': 'custom', 'base_url': 'http://127.0.0.1:2/v1', 'default': 'new-model'}, **aux}))+ await _open(authority, ref)+ authority._local_config_secrets = {} # a fresh owner reads the reference against config.yaml+ model, url, key = _route(runner, live)+ assert (model, url) == ('new-model', 'http://127.0.0.1:2/v1') and key not in ('old-key', 'sk-launch-for-one')+ assert _key(runner, authority, live) is None+ ref_json = local_receipt(authority.db, ref.session_id)['policy']['config_secret_ref']+ entries = [path for path, _ in json.loads(ref_json.split(':', 1)[1])['entries']]+ assert entries == [['auxiliary', 'vision', 'api_key']]+ config = policy_for_source(runner, live.source).config(authority)+ assert config['auxiliary']['vision']['api_key'] == 'aux-key'+ _profile(home, 'new-model', 2, 'new-key', **aux)+ assert _route(runner, live) == ('new-model', 'http://127.0.0.1:2/v1', 'new-key')+ finally:+ await owner.close()+ store.close_all_db_handles()++[email protected]('kind', ['other-title', 'chose-frozen', 'safe-mode'])+async def test_opening_leaves_other_chats_and_deliberate_freezes_frozen(home, kind):+ from hermes_state_local import local_receipt+ extra = {'other-title': {'title': 'Notes'}, 'chose-frozen': {'follow_profile_config': False},+ 'safe-mode': {'safe_mode': True, 'model': 'old-model', 'provider': 'custom',+ 'base_url': 'http://127.0.0.1:1/v1'}}[kind]+ _profile(home, 'old-model', 1, 'old-key')+ store, runner, authority, owner = _owner(home)+ runner._peek_session_state = lambda key: None+ try:+ ref, _params = _frozen_bot_chat(authority, owner.actor, home, **extra)+ live = authority.sessions[ref.session_id]+ _profile(home, 'new-model', 2, 'new-key')+ await _open(authority, ref)+ assert not _follows(runner, live)+ assert _route(runner, live)[:2] == ('old-model', 'http://127.0.0.1:1/v1')+ # An older owner restores this receipt: it gains no field.+ assert 'follow_adopted' not in local_receipt(authority.db, ref.session_id)['policy']+ finally:+ await owner.close()+ store.close_all_db_handles()+++async def test_opening_a_frozen_adopted_bot_chat_holds_its_composer_pick_until_the_profile_moves(home, monkeypatch):+ """An earlier build adopted this pre-upgrade Bot Chat frozen. The open applies adoption's rule."""+ from gateway import session_local_migration+ from gateway.session_local_migration import resolve_local_target+ _profile(home, 'profile-model', 2, 'k2')+ store, runner, authority, owner = _owner(home)+ runner._peek_session_state = lambda key: None+ _legacy(authority.db, home, 'old-bot', source='gui', model='picked-model', title='Bot Chat', model_config={+ 'composer_override_profile': {'model': 'profile-model', 'provider': 'custom'}})+ authority._native_legacy_transports = {owner.actor.transport_id: owner.actor}+ try:+ with monkeypatch.context() as earlier:+ earlier.setattr(session_local_migration, 'legacy_bot_chat_launch',+ lambda row, params, mode, config: (params, mode))+ ref = resolve_local_target(authority, owner.actor, 'old-bot')+ bot = authority.sessions[ref.session_id]+ assert not _follows(runner, bot)+ await _open(authority, ref)+ assert _follows(runner, bot)+ assert _route(runner, bot)[:2] == ('picked-model', 'http://127.0.0.1:2/v1')+ assert _key(runner, authority, bot) == 'k2'+ _profile(home, 'moved-model', 3, 'k3')+ assert _route(runner, bot)[:2] == ('moved-model', 'http://127.0.0.1:3/v1')+ assert _key(runner, authority, bot) == 'k3'+ finally:+ await owner.close()+ store.close_all_db_handles()+++def _named_profile(home, monkeypatch, section, credential, url, secret):+ """The profile runs ``custom:primary``; a second named entry ``picked`` serves *url* with *secret*+ held inline, through ``key_env`` or through ``key_cmd``."""+ entry = {'base_url': url}+ if credential == 'inline':+ entry['api_key'] = secret+ elif credential == 'env':+ monkeypatch.setenv('PICKED_ENTRY_KEY', secret)+ entry['key_env'] = 'PICKED_ENTRY_KEY'+ else:+ entry['key_cmd'] = f'echo {secret}'+ primary = {'base_url': 'http://127.0.0.1:2/v1', 'api_key': 'primary-key-long'}+ config = {'model': {'provider': 'custom:primary', 'default': 'profile-model'}}+ if section == 'providers':+ config['providers'] = {'primary': primary, 'picked': entry}+ else:+ config['custom_providers'] = [{'name': 'primary', **primary}, {'name': 'picked', **entry}]+ (home / 'config.yaml').write_text(json.dumps(config))++[email protected]('section, credential, path', [+ ('providers', 'inline', 'adoption'), ('providers', 'env', 'open'),+ ('custom_providers', 'inline', 'open'), ('custom_providers', 'command', 'adoption')])+async def test_a_held_pick_never_sends_its_named_entrys_new_key_to_the_old_endpoint(+ home, monkeypatch, section, credential, path):+ """A held composer pick on the named entry ``picked`` keeps the endpoint it was made on. Once that+ entry moves to another endpoint and key, its credential belongs there: the hold ends."""+ from gateway import session_local_migration+ from gateway.session_local_migration import resolve_local_target+ _named_profile(home, monkeypatch, section, credential, 'http://127.0.0.1:5/v1', 'picked-key-one')+ store, runner, authority, owner = _owner(home)+ runner._peek_session_state = lambda key: None+ _legacy(authority.db, home, 'old-bot', source='gui', model='picked-model', title='Bot Chat', model_config={+ 'provider': 'custom:picked', 'base_url': 'http://127.0.0.1:5/v1',+ 'composer_override_profile': {'model': 'profile-model', 'provider': 'custom:primary'}})+ authority._native_legacy_transports = {owner.actor.transport_id: owner.actor}+ try:+ with monkeypatch.context() as earlier:+ if path == 'open':+ earlier.setattr(session_local_migration, 'legacy_bot_chat_launch',+ lambda row, params, mode, config: (params, mode))+ ref = resolve_local_target(authority, owner.actor, 'old-bot')+ if path == 'open':+ await _open(authority, ref)+ bot = authority.sessions[ref.session_id]+ assert _route(runner, bot)[:2] == ('picked-model', 'http://127.0.0.1:5/v1')+ _named_profile(home, monkeypatch, section, credential, 'http://127.0.0.1:6/v1', 'picked-key-two')+ assert _route(runner, bot) == ('profile-model', 'http://127.0.0.1:2/v1', 'primary-key-long')+ finally:+ await owner.close()+ store.close_all_db_handles()++[email protected]('pick', [{'provider': 'custom:other'}, {'base_url': 'http://127.0.0.1:7/v1'}],+ ids=['provider-only', 'endpoint-only'])+async def test_a_route_pick_without_a_model_holds_on_a_following_create(home, pick):+ """``chat -c "Bot Chat" --create-if-missing --provider X`` follows the profile, and its pick holds+ like a ``-m`` pick until the profile's model or provider changes."""+ (home / 'config.yaml').write_text(json.dumps({+ 'model': {'provider': 'custom', 'base_url': 'http://127.0.0.1:1/v1', 'default': 'shared-model',+ 'api_key': 'profile-key-one'},+ 'providers': {'other': {'base_url': 'http://127.0.0.1:7/v1', 'api_key': 'other-key-long'}}}))+ store, runner, authority, owner = _owner(home)+ runner._peek_session_state = lambda key: None+ try:+ response = await owner.dispatch({'id': 'cli', 'method': 'session.create', 'params': dict(+ request_id='cli-pick', source='cli', cwd=str(home), title='Bot Chat', **pick)})+ assert 'result' in response, response+ live = authority.sessions[response['result']['session_id']]+ assert _follows(runner, live)+ model, url, key = _route(runner, live)+ assert (model, url) == ('shared-model', 'http://127.0.0.1:7/v1') and key != 'profile-key-one'+ _profile(home, 'moved-model', 3, 'moved-key-long')+ assert _route(runner, live) == ('moved-model', 'http://127.0.0.1:3/v1', 'moved-key-long')+ finally:+ await owner.close()+ store.close_all_db_handles()++[email protected]('by', ['session_id', 'title'])+async def test_a_busy_first_open_leaves_adoption_to_the_next_open_on_that_connection(home, monkeypatch, by):+ """Desktop keeps its connection: a warm reopen (``session.activate`` is ``session.resume``) must still+ adopt a chat whose first open found a turn running."""+ import hermes_state_mutation_guards as guards+ from gateway.session_controls import AuthorityConnection+ from hermes_state_runtime import RuntimeStoreError+ _profile(home, 'old-model', 1, 'old-key')+ store, runner, authority, owner = _owner(home)+ runner._peek_session_state = lambda key: None+ real, refused = guards.require_idle, []++ def busy_once(db, conn, ids):+ if not refused:+ refused.append(ids)+ raise RuntimeStoreError('session_busy')+ return real(db, conn, ids)+ monkeypatch.setattr(guards, 'require_idle', busy_once)+ desktop = AuthorityConnection(authority, object(), {'user_id': 'human'})+ try:+ ref, _params = _frozen_bot_chat(authority, owner.actor, home)+ live = authority.sessions[ref.session_id]+ _profile(home, 'new-model', 2, 'new-key')+ params = {'session_id': ref.session_id} if by == 'session_id' else {'title': 'Bot Chat'}+ for attempt in ('busy', 'idle'):+ response = await desktop.dispatch({'id': attempt, 'method': 'session.resume', 'params': dict(params)})+ assert 'result' in response, response+ assert _follows(runner, live) is (attempt == 'idle')+ assert refused and _route(runner, live) == ('new-model', 'http://127.0.0.1:2/v1', 'new-key')+ finally:+ await desktop.close()+ await owner.close()+ store.close_all_db_handles()+++async def test_opening_a_frozen_bot_chat_keeps_its_committed_reasoning_choice(home):+ """A ``/reasoning high`` committed on the frozen chat is the session's choice: the open adopts the+ profile's route, not the profile's ``low``."""+ from gateway.session_policy import policy_for_source+ _profile(home, 'old-model', 1, 'old-key', agent={'reasoning_effort': 'low'})+ store, runner, authority, owner = _owner(home)+ runner._peek_session_state = lambda key: None+ runner._set_session_reasoning_override = lambda route, value: None+ try:+ ref, _params = _frozen_bot_chat(authority, owner.actor, home)+ live = authority.sessions[ref.session_id]+ snap = authority.db.get_session(ref.session_id)+ response = await owner.dispatch({'id': 'pick', 'method': 'session.mutate', 'params': dict(+ session_id=ref.session_id, request_id='high', operation='reasoning', payload={'effort': 'high'},+ expected_revision=snap['runtime_revision'], expected_generation=snap['runtime_generation'])})+ assert 'result' in response, response+ _profile(home, 'new-model', 2, 'new-key', agent={'reasoning_effort': 'low'})+ await _open(authority, ref)+ assert _route(runner, live) == ('new-model', 'http://127.0.0.1:2/v1', 'new-key')+ assert policy_for_source(runner, live.source).current_reasoning_config(runner).get('effort') == 'high'+ finally:+ await owner.close()+ store.close_all_db_handles()diff --git a/tests/gateway/test_peer_dm_bot_chat_headless.py b/tests/gateway/test_peer_dm_bot_chat_headless.pyindex 37164f4bcba..0f5bb62302b 100644--- a/tests/gateway/test_peer_dm_bot_chat_headless.py+++ b/tests/gateway/test_peer_dm_bot_chat_headless.py@@ -27,8 +27,9 @@ async def headless(tmp_path, monkeypatch):from gateway.session_authority import initialize_session_authoritymonkeypatch.setenv('HERMES_HOME', str(tmp_path))+ # A following Bot Chat reads the profile config by path.monkeypatch.setattr(run, '_load_gateway_config',- lambda: {'platform_toolsets': {'cli': []}, 'model': {'default': 'fixture'}})+ lambda *_path: {'platform_toolsets': {'cli': []}, 'model': {'default': 'fixture'}})from hermes_state import SessionDBstore = SessionStore(tmp_path / 'sessions', GatewayConfig())store._db = SessionDB(db_path=tmp_path / 'state.db')diff --git a/tests/gateway/test_session_bot_target_lifecycle.py b/tests/gateway/test_session_bot_target_lifecycle.pyindex 8d5ae5fb0c8..03b3392207f 100644--- a/tests/gateway/test_session_bot_target_lifecycle.py+++ b/tests/gateway/test_session_bot_target_lifecycle.py@@ -22,8 +22,9 @@ async def bot(tmp_path, monkeypatch):from hermes_state import SessionDBmonkeypatch.setenv('HERMES_HOME', str(tmp_path))+ # A following Bot Chat reads the profile config by path.monkeypatch.setattr(run, '_load_gateway_config',- lambda: {'platform_toolsets': {'cli': []}, 'model': {'default': 'fixture'}})+ lambda *_path: {'platform_toolsets': {'cli': []}, 'model': {'default': 'fixture'}})store = SessionStore(tmp_path / 'sessions', GatewayConfig())store._db = SessionDB(db_path=tmp_path / 'state.db')runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False,