The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): preserve owner Bot Chat history on first delivery
Gille1a08f050cccc
diff --git a/gateway/session_bot.py b/gateway/session_bot.pyindex a5e099129ff..7ddf1b4643b 100644--- a/gateway/session_bot.py+++ b/gateway/session_bot.py@@ -276,23 +276,23 @@ def release_superseded_bot_chat_at_boot(db, store):def _kept_local_history(db, row):"""Whether an unbound row is local history the Bot Chat door must leave in place: a CLI, TUI- or Desktop row a native open adopts (unstamped, or stamped with a subject a native ticket- carries: the host's own OS identity, or a structured login subject a same-user peer forwards),+ or Desktop row a native open adopts (unstamped, or stamped with the host owner's OS identity,+ an owner login label, or a structured login subject),or a Desktop row a served login stamped with its label (kept as on main, even with a routecolumn or another profile's name). Any other local-source row no open can ever adopt (a route- column left by a crash or reconnect, another profile's stamp, or outside Desktop any other- stamp, such as a login label ``basic:alice``) is not: it held the title and refused every- delivery for good (#141243, #143715)."""+ column left by a crash or reconnect, another profile's stamp, or outside Desktop a foreign+ stamp) is not: it held the title and refused every delivery for good (#141243, #143715)."""from gateway.session_identity import parse_authenticated_subject+ from gateway.owner_identity import same_ownerfrom gateway.session_worker_reservation import owner_worker_subjectfrom hermes_state_local_migration import LEGACY_LOCAL_SOURCES, legacy_account_label, validate_legacy_rowif row.get('source') not in LEGACY_LOCAL_SOURCES:return Falseuser_id = row.get('user_id')- if (user_id and not legacy_account_label(row) and user_id != owner_worker_subject()+ if (user_id and not legacy_account_label(row) and not same_owner(user_id, owner_worker_subject())and parse_authenticated_subject(user_id) is None):- # A Desktop row a login stamped stays where it is, as on main (#140183). On any other local- # source such a stamp names no subject a native ticket carries, so nobody adopts it (#143715).+ # Keep the Desktop foreign-login exception (#140183). Owner login labels must instead+ # reach validation: delivery and native open must agree before this door displaces history.return row.get('source') == 'desktop'try:validate_legacy_row(db, row, subject=user_id)diff --git a/tests/gateway/test_bot_chat_owner_adoption.py b/tests/gateway/test_bot_chat_owner_adoption.pynew file mode 100644index 00000000000..4062b1ced4f--- /dev/null+++ b/tests/gateway/test_bot_chat_owner_adoption.py@@ -0,0 +1,98 @@+"""Owner login history survives either delivery-first or open-first Bot Chat adoption."""++import pytest++from tests.gateway import test_peer_dm_bot_chat_headless as peer+from tests.gateway.test_bot_chat_unadoptable_local_title import _deliver+from tests.waiting import async_wait_until++headless = peer.headless++[email protected]("open_first", [False, True])+ "stamp", ["basic:alice", "self-hosted:alice", 'auth:v1:["basic","","alice"]']+)+async def test_owner_chat_retains_identity_history_and_replies_in_both_orders(+ headless, monkeypatch, stamp, open_first+):+ import gateway.session_worker_reservation as reservation++ monkeypatch.setattr(reservation, "owner_worker_subject", lambda: "uid:1000")+ db = headless.authority.db+ sid = "existing-bot-chat"+ db.create_session(sid, source="tui", user_id=stamp)+ db.set_session_title(sid, "Bot Chat")+ db.append_message(sid, "user", "existing project context")+ db.append_message(sid, "assistant", "existing answer")+ history = db.get_messages_as_conversation(sid)+ owner = peer._local_owner(headless.authority)+ try:+ if open_first:+ await peer._rpc(owner, "session.resume", session_id=sid)+ first = await _deliver(headless.authority, "a")+ assert first["session_id"] == sid+ await async_wait_until(+ lambda: len(headless.executed) == 1, timeout=10, interval=0.05+ )+ await peer._rpc(owner, "session.resume", session_id=sid)+ response = await headless.cli.post(+ f"/api/sessions/{sid}/chat",+ json={"message": "follow-up from peer", "author": peer.AUTHOR},+ )+ body = await response.json()+ assert response.status == 200, body+ assert body["message"]["content"] == "pong"+ assert [entry[0] for entry in headless.executed] == [sid, sid]+ assert db.get_session_by_title("Bot Chat")["id"] == sid+ assert db.get_messages_as_conversation(sid)[: len(history)] == history+ assert [row[0] for row in db._read_all("SELECT id FROM sessions")] == [sid]+ finally:+ await owner.close()+++async def test_owner_login_chat_is_not_replaced_while_its_legacy_writer_is_live(+ headless, monkeypatch+):+ from pathlib import Path++ import gateway.session_worker_reservation as reservation+ from hermes_cli.active_sessions import (+ release_active_session,+ try_acquire_active_session,+ )+ from hermes_state_runtime import RuntimeStoreError++ monkeypatch.setattr(reservation, "owner_worker_subject", lambda: "uid:1000")+ db = headless.authority.db+ sid = "busy-existing-bot-chat"+ db.create_session(sid, source="tui", user_id="basic:alice")+ db.set_session_title(sid, "Bot Chat")+ db.append_message(sid, "assistant", "existing project context")+ lease, refusal = try_acquire_active_session(+ session_id=sid,+ surface="desktop",+ registry_home=Path(db.db_path).parent,+ config={},+ )+ assert lease is not None, refusal+ try:+ with pytest.raises(RuntimeStoreError) as refused:+ await _deliver(headless.authority, "b")+ assert refused.value.reason == "runtime_coordination_required"+ assert db.get_session_by_title("Bot Chat")["id"] == sid+ assert not headless.executed+ assert not db.get_session(sid)["chat_id"]+ assert [row[0] for row in db._read_all("SELECT id FROM sessions")] == [sid]+ finally:+ release_active_session(lease)+ delivered = await _deliver(headless.authority, "c")+ assert delivered["session_id"] == sid+ await async_wait_until(+ lambda: len(headless.executed) == 1, timeout=10, interval=0.05+ )+ assert (+ db.get_messages_as_conversation(sid)[0]["content"] == "existing project context"+ )diff --git a/tests/gateway/test_bot_chat_unadoptable_local_title.py b/tests/gateway/test_bot_chat_unadoptable_local_title.pyindex bd115ee7916..41a5a55486c 100644--- a/tests/gateway/test_bot_chat_unadoptable_local_title.py+++ b/tests/gateway/test_bot_chat_unadoptable_local_title.py@@ -65,7 +65,7 @@ async def test_an_unadoptable_local_bot_chat_is_moved_aside_and_the_delivery_lan@pytest.mark.parametrize('source, stamp, route', [('tui', 'github:alice', None),('tui', 'nous:[email protected]', None),- ('cli', 'basic:alice', None),+ ('cli', 'basic:alice', 'agent:main:tui:dm:stale'), # owner login, but a stale route prevents adoption('tui', 'github:alice', 'agent:main:tui:dm:stale'), # a crash's route column, never bound('tui', 'uid:1001', None), # another OS user, not this host's identity('desktop', 'auth:v1:["basic","","alice"]', 'agent:main:tui:dm:stale'), # a subject, but routed@@ -73,9 +73,9 @@ async def test_an_unadoptable_local_bot_chat_is_moved_aside_and_the_delivery_lan@pytest.mark.asyncioasync def test_a_bot_chat_another_login_stamped_is_moved_aside_and_the_delivery_lands(headless, monkeypatch, source, stamp, route):- # Outside Desktop, a stamp that is neither this host's identity nor a login subject names no- # subject a native ticket carries; a crash's route column makes a subject-stamped row (Desktop- # too) unadoptable. No caller can adopt such a row, so it held the title and refused every+ # Foreign stamps and stale routes remain unadoptable. An owner's login label alone no longer+ # makes a row foreign, but a crash's route column still prevents adoption (Desktop too).+ # No caller can adopt these rows, so they held the title and refused every# delivery for good (#143715). Moving it keeps its id, stamp and messages.from tests.waiting import async_wait_untilimport gateway.session_worker_reservation as reservation