Skip to content

The agent that grows with you

fix(bot-chat): mint a fresh Bot Chat after the auto-created one is renamed or deleted

Teknium470ae55d6d93
diff --git a/gateway/session_bot.py b/gateway/session_bot.py
index 8b26a44c621..995540a06ea 100644
--- a/gateway/session_bot.py
+++ b/gateway/session_bot.py
@@ -112,11 +112,30 @@ def _create_bot_chat(authority, actor):
from gateway.session_local import create_local_session
from gateway.session_local_title import title_new_session
ref = create_local_session(authority, actor, {
- 'request_id': 'bot-chat:' + authority.profile_id, 'source': 'cli', 'cwd': str(Path.home())})
+ 'request_id': _bot_chat_creation_id(authority, actor), 'source': 'cli', 'cwd': str(Path.home())})
title_new_session(authority, ref, 'Bot Chat')
return ref
+def _bot_chat_creation_id(authority, actor):
+ """The first creation identity whose session is not spent. Generation 0 keeps the historical
+ ``bot-chat:<profile>`` id; a generation is spent once its session was deleted (retired: a retry
+ must never resurrect it) or renamed (titled, but not "Bot Chat" — or the lookup had found it),
+ and a replacement takes the next one. Derived from durable rows only, so a restart and two
+ concurrent deliveries (this runs on the owner loop with no await) pick the same identity. An
+ existing UNtitled session is the same creation interrupted before its title: it is reused."""
+ from gateway.session_local_recovery import local_identity
+ from hermes_state_mutation_retirement import retired_session
+ base, generation = 'bot-chat:' + authority.profile_id, 0
+ while True:
+ request_id = base if generation == 0 else f'{base}:{generation}'
+ sid = local_identity(authority.profile_id, actor.subject, request_id)
+ row = authority.db.get_session(sid)
+ if not retired_session(authority.db, sid) and (row is None or not row.get('title')):
+ return request_id
+ generation += 1
+
+
def _admission_outcome(authority, admission_id, fallback=None):
"""``(status, reply)`` of one admission, read from its committed result, never transcript recency."""
row = get_session_admission(authority.db, admission_id=admission_id)
diff --git a/tests/gateway/test_session_bot_target_lifecycle.py b/tests/gateway/test_session_bot_target_lifecycle.py
new file mode 100644
index 00000000000..5b4606dadde
--- /dev/null
+++ b/tests/gateway/test_session_bot_target_lifecycle.py
@@ -0,0 +1,64 @@
+"""The auto-created Bot Chat target can be replaced: rename and delete spend its creation identity.
+
+``gateway.session_bot._create_bot_chat`` mints the profile's Bot Chat when none is titled so. The
+creation identity of an earlier target is immutable (a retry of it must converge, and a deleted one
+must never be resurrected), so a rename or canonical delete must lead to a FRESH creation instead of
+replaying the old one: retitling the renamed session back, or refusing on the retired id.
+"""
+from types import SimpleNamespace
+
+import pytest
+import pytest_asyncio
+
+from gateway.session_contract import Principal
+
+
+@pytest_asyncio.fixture
+async def bot(tmp_path, monkeypatch):
+ from gateway import run
+ from gateway.config import GatewayConfig
+ from gateway.session import SessionStore
+ from gateway.session_authority import initialize_session_authority
+ from hermes_state import SessionDB
+
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ monkeypatch.setattr(run, '_load_gateway_config',
+ lambda: {'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,
+ _evict_cached_agent=lambda route: None)
+ runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)
+ authority = await initialize_session_authority(runner, profile_id='default', instance_id='fixture')
+ owner = Principal('uid:1000', 'default', frozenset({'session:create', 'session:read', 'session:submit'}), 'native')
+ try:
+ yield SimpleNamespace(authority=authority, owner=owner, home=tmp_path)
+ finally:
+ store._db.close()
+
+
+def _target_id(bot):
+ from gateway.session_bot import _target
+ ref, _live, _entry = _target(bot.authority, bot.owner)
+ return ref.session_id
+
+
+async def test_renamed_or_deleted_bot_chat_gets_a_fresh_replacement(bot):
+ db = bot.authority.db
+ first = _target_id(bot)
+ assert _target_id(bot) == first # converges: resolved by title, never re-created
+
+ db.set_session_title(first, 'Planning notes')
+ second = _target_id(bot)
+ assert second != first
+ assert db.get_session(first)['title'] == 'Planning notes' # the rename stands
+ assert db.get_session(second)['title'] == 'Bot Chat'
+
+ assert db.delete_session(second, sessions_dir=bot.home / 'sessions')
+ bot.authority.sessions.pop(second, None)
+ third = _target_id(bot)
+ assert third not in (first, second) # a replacement, not the retired id
+ assert db.get_session(second) is None
+ assert db.get_session(third)['title'] == 'Bot Chat'
+ assert _target_id(bot) == third