The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a paused messaging session tells the platform user once and never parks the adapter
teknium1baece0035fbb
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 688c722ab2c..7853f83369a 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -31,6 +31,10 @@ class LiveSession:subscribers: dict = field(default_factory=dict)event_stream: SessionEvents = field(default_factory=SessionEvents)controls: PendingControls = field(init=False)+ # Why the FIFO is not advancing (unknown head, preflight refusal) or None. The+ # messaging ingress tells the platform user once per pause episode, not per message.+ paused: str | None = None+ pause_notified: bool = Falsedef __post_init__(self):self.controls = PendingControls(self.event_stream)@@ -204,6 +208,22 @@ class SessionAuthority:live.task = asyncio.create_task(self._drain(ref))live.task.add_done_callback(_log_drain_failure)+ def _pause(self, ref, reason):+ """The FIFO stopped without claiming its head. Committed rows stay queued for a later+ drain; only the process-local messaging delivery waiters on this session are released,+ with the reason instead of a reply, so an adapter loop is never parked on a turn that+ will not run. The ingress turns that refusal into one user-facing notice per episode."""+ live = self.sessions[ref.session_id]+ live.paused = reason+ for row in list_session_admissions(self.db, session_id=ref.session_id):+ admission_id = row['admission_id']+ if admission_id not in self.native_waiters:+ continue+ self.native_waiters.discard(admission_id)+ waiter = self.waiters.pop(admission_id, None)+ if waiter is not None and not waiter.done():+ waiter.set_exception(RuntimeStoreError(reason))+async def admit_automation(self, adapter, event, identity):from gateway.session_automation import admit_automationreturn await admit_automation(self, adapter, event, identity)@@ -416,6 +436,7 @@ class SessionAuthority:try:pending = list_session_admissions(self.db, session_id=ref.session_id)if any(row['status'] == 'unknown' for row in pending):+ self._pause(ref, 'unknown_execution')returnfirst = next((row for row in pending if row['status'] == 'queued'), None)from gateway.config import Platform@@ -457,7 +478,11 @@ class SessionAuthority:except RuntimeStoreError as exc:import logginglogging.getLogger(__name__).warning('Session %s paused: %s', ref.session_id, exc.reason)+ self._pause(ref, exc.reason)return+ # The FIFO is moving again (or empty): the next pause is a new episode.+ live.paused = None+ live.pause_notified = Falseif row is None:returnadmission_id = row['admission_id']diff --git a/gateway/session_ingress.py b/gateway/session_ingress.pyindex 4ace58dc6e7..47cf7adef73 100644--- a/gateway/session_ingress.py+++ b/gateway/session_ingress.py@@ -6,6 +6,7 @@ from dataclasses import replacefrom gateway.platforms.event import MessageEventfrom gateway.session_envelope import restore_native+from hermes_state_runtime import RuntimeStoreErroradmission_author = ContextVar('admission_author', default=None)executing_admission = ContextVar('executing_admission', default=False)@@ -18,7 +19,26 @@ async def admit_message(authority, event):# Only the delivery waiter is process-local; execution reads the committed snapshot.authority.native_waiters.add(receipt.admission_id)waiter = authority.waiters.setdefault(receipt.admission_id, asyncio.get_running_loop().create_future())- return await asyncio.shield(waiter)+ try:+ return await asyncio.shield(waiter)+ except RuntimeStoreError as exc:+ return pause_notice(authority, receipt.ref, exc.reason)+++def pause_notice(authority, ref, reason):+ """The committed input stays queued behind a paused FIFO (a turn lost across an owner+ restart, or a head the preflight refused). Tell the platform user once per pause episode+ through the ordinary reply path; later messages onto the same pause are admitted silently."""+ live = authority.sessions[ref.session_id]+ if live.pause_notified:+ return None+ live.pause_notified = True+ if reason == 'unknown_execution':+ cause = 'a previous turn did not finish when Hermes restarted, so nothing queued after it will run'+ else:+ cause = f'a queued message could not be re-authorized ({reason})'+ return (f'⏸️ This conversation is paused: {cause}. Your message is saved but will not be answered here. '+ 'Send /reset to start a fresh conversation, or ask the operator to resume this one.')def row_turn_author(policy, row):diff --git a/tests/cron/test_cron_bot_chat_create_if_missing.py b/tests/cron/test_cron_bot_chat_create_if_missing.pynew file mode 100644index 00000000000..e6246027a6e--- /dev/null+++ b/tests/cron/test_cron_bot_chat_create_if_missing.py@@ -0,0 +1,50 @@+"""Cron Bot Chat delivery creates the profile's canonical Bot Chat when it does not exist yet.++Main's lane was ``hermes chat -c "Bot Chat" --create-if-missing``; the canonical authority+door must keep that semantics, or a fresh profile's very first ``deliver: bot-chat`` job is+recorded as failed with nowhere to land.+"""+from contextlib import closing+import json+from pathlib import Path+import sqlite3++import pytest++from tests.gateway.fixtures.local_recovery_probe import child_env, daemon+from tests.gateway.test_normal_runtime_boot import model_peer++[email protected]_only+def test_cron_bot_chat_delivery_creates_the_missing_bot_chat_and_admits(tmp_path, monkeypatch):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ with model_peer() as (url, peer):+ (home / 'config.yaml').write_text(json.dumps({+ 'gateway': {'multiplex_profiles': False},+ 'model': {'provider': 'custom', 'default': 'local-wire-stub', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False}}, 'terminal': {'cwd': str(home)}}))+ env = child_env()+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url, PYTHONUNBUFFERED='1')+ monkeypatch.setenv('HERMES_HOME', str(home))+ monkeypatch.setattr(Path, 'home', lambda: user)+ with daemon(root, home, env, barrier=False):+ from cron.scheduler_delivery import _deliver_to_bot_chat+ job = {'id': 'digest', 'name': 'Digest', 'execution_id': 'run-1'}+ first = _deliver_to_bot_chat(job, 'FIRST_PAYLOAD', '')+ receipt = job['_bot_chat_delivery_receipts']['bot-chat:(own)']+ assert receipt['status'] in ('queued', 'claimed', 'settled'), (first, receipt)+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ titled = db.execute("SELECT id FROM sessions WHERE title='Bot Chat'").fetchall()+ assert len(titled) == 1, titled+ admitted = db.execute('SELECT target_session_id, payload_json FROM session_admissions').fetchall()+ assert len(admitted) == 1 and 'FIRST_PAYLOAD' in admitted[0][1], admitted+ # The next run lands in the SAME Bot Chat: created once, then resolved by name.+ second = _deliver_to_bot_chat({**job, 'execution_id': 'run-2'}, 'SECOND_PAYLOAD', '')+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ assert db.execute("SELECT count(*) FROM sessions WHERE title='Bot Chat'").fetchone()[0] == 1+ targets = {row[0] for row in db.execute('SELECT target_session_id FROM session_admissions')}+ assert len(targets) == 1, (first, second, targets)diff --git a/tests/gateway/test_native_pause_notice.py b/tests/gateway/test_native_pause_notice.pynew file mode 100644index 00000000000..7c1d64857c3--- /dev/null+++ b/tests/gateway/test_native_pause_notice.py@@ -0,0 +1,161 @@+"""A messaging user whose session FIFO is paused is told once, and can /reset out of it.++An owner crash mid-turn leaves the started admission ``unknown`` and the session paused+(fail-closed, never weakened here). Before this fix the next Telegram message was admitted,+``admit_message`` awaited it forever and the platform user saw nothing at all.+"""+import asyncio+from contextlib import closing+from http.server import ThreadingHTTPServer+import json+from pathlib import Path+import queue+import sqlite3+import threading+import time++import pytest++from tests.gateway.fixtures.local_recovery_probe import Model, child_env, daemon+from tests.gateway.test_native_telegram_startup_recovery import BotAPI, wait_for++PAUSE_MARKER = 'This conversation is paused'+++async def test_paused_fifo_releases_the_messaging_waiter_with_one_notice_per_episode(tmp_path, monkeypatch):+ """No daemon: the authority alone. A refused head pauses the FIFO; every messaging waiter+ parked on that session returns (never hangs), the first gets the notice, the rest None,+ and once the FIFO moves again the next pause is a fresh episode with its own notice."""+ from gateway.platforms.event import MessageEvent+ from gateway.session_authority import SessionAuthority+ from gateway.session_contract import Principal, Submission+ from gateway.session_controls import AuthorityConnection+ from gateway.session_ingress import admit_message+ from tests.gateway.test_authority_unknown_resolution import Peer, _restarted_owner_with_unknown_head++ executed = []+ store, authority, ref, unknown, follower = await _restarted_owner_with_unknown_head(tmp_path, monkeypatch, executed)+ try:+ actor = Principal('human', 'p', frozenset({'session:submit'}), 'fixture')++ async def admit_native(event):+ return await authority.submit(actor, Submission(event.text, ref, {'text': event.text}, 'queue'))+ monkeypatch.setattr(authority, 'admit_native', admit_native)+ authority._schedule = lambda ref: SessionAuthority._schedule(authority, ref)+ source = authority.sessions['s'].source+ first = asyncio.create_task(admit_message(authority, MessageEvent(text='one', source=source)))+ second = asyncio.create_task(admit_message(authority, MessageEvent(text='two', source=source)))+ replies = await asyncio.wait_for(asyncio.gather(first, second), 5)+ assert sum(r is not None and PAUSE_MARKER in r for r in replies) == 1, replies+ assert executed == []+ # The operator resumes the FIFO; the saved followers run, no new notice was owed.+ viewer = AuthorityConnection(authority, Peer(), {'user_id': 'human'})+ await viewer.dispatch({'id': 1, 'method': 'prompt.resolve_unknown', 'params': {+ 'session_id': 's', 'admission_id': unknown['admission_id'], 'execution_generation': unknown['generation']}})+ await asyncio.wait_for(authority.sessions['s'].task, 5)+ assert executed == ['FOLLOWER', 'one', 'two']+ assert authority.sessions['s'].paused is None and not authority.sessions['s'].pause_notified+ await viewer.close()+ finally:+ store.close_all_db_handles()++[email protected]_only+def test_crash_mid_turn_then_platform_message_gets_one_pause_notice_and_reset_unpauses(tmp_path):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ model = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ model.requests = []+ model.blocked, model.release = threading.Event(), threading.Event()+ bot = ThreadingHTTPServer(('127.0.0.1', 0), BotAPI)+ bot.calls, bot.sent, bot.updates = [], [], queue.Queue()+ for peer in (model, bot):+ threading.Thread(target=peer.serve_forever, daemon=True).start()+ base = f'http://127.0.0.1:{model.server_port}/v1'+ cfg = {'model': {'provider': 'custom', 'default': 'local-wire-stub', 'base_url': base},+ 'gateway': {'multiplex_profiles': False},+ 'platforms': {'telegram': {'enabled': True, 'extra': {+ 'base_url': f'http://127.0.0.1:{bot.server_port}/bot', 'dm_policy': 'allowlist'}}},+ 'auxiliary': {'title_generation': {'enabled': False}},+ 'platform_toolsets': {'telegram': []}, 'terminal': {'cwd': str(home)}}+ (home / 'config.yaml').write_text(json.dumps(cfg))+ env = child_env()+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=base, PYTHONUNBUFFERED='1',+ TELEGRAM_BOT_TOKEN='987654321:owned-loopback-fixture', TELEGRAM_ALLOWED_USERS='202')++ def rows():+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ return {json.loads(payload)['text']: {'session': sid, 'status': status}+ for sid, status, payload in db.execute(+ 'SELECT target_session_id,status,payload_json FROM session_admissions')}++ def sent_texts():+ # Telegram MarkdownV2 escapes underscores; compare on the unescaped text.+ return [m.get('text', '').replace('\\', '') for m in bot.sent]++ def notices():+ return [t for t in sent_texts() if PAUSE_MARKER in t]++ def diagnostic():+ return repr(rows()) + '\n' + repr(sent_texts()) + '\n' + '\n'.join(+ p.read_text() for p in (home / 'logs').glob('*.log'))++ update_id = 0++ def push(text):+ nonlocal update_id+ update_id += 1+ bot.updates.put({'update_id': update_id, 'message': {+ 'message_id': update_id, 'date': int(time.time()),+ 'chat': {'id': 202, 'type': 'private', 'first_name': 'Owned'},+ 'from': {'id': 202, 'is_bot': False, 'first_name': 'Owned'}, 'text': text}})++ def send(text, status):+ push(text)+ wait_for(lambda: rows().get(text, {}).get('status') == status, diagnostic)++ try:+ with daemon(root, home, env, barrier=False) as (proc, desc):+ send('WARM_HISTORY', 'terminal')+ send('BLOCK_STARTED', 'started')+ assert model.blocked.wait(20), diagnostic()+ proc.kill()+ assert proc.wait(timeout=10) == -9+ model.release.set()+ with daemon(root, home, env, barrier=False) as (proc, desc):+ wait_for(lambda: rows()['BLOCK_STARTED']['status'] == 'unknown', diagnostic)+ paused_session = rows()['BLOCK_STARTED']['session']+ # First message onto the paused FIFO: admitted (durable), the user is told once,+ # and the adapter loop keeps going (the second message is admitted too).+ send('AFTER_CRASH_ONE', 'queued')+ wait_for(lambda: len(notices()) == 1, diagnostic)+ assert '/reset' in notices()[0], notices()+ send('AFTER_CRASH_TWO', 'queued')+ assert rows()['AFTER_CRASH_TWO']['session'] == paused_session+ # The named escape works from the platform: /reset (confirmed) moves the chat to+ # a fresh session and the next message runs and is answered.+ push('/reset')+ wait_for(lambda: any('Confirm /new' in t for t in sent_texts()), diagnostic)+ push('/approve')+ wait_for(lambda: any('Session reset' in t or 'New session' in t for t in sent_texts()), diagnostic)+ send('AFTER_RESET', 'terminal')+ wait_for(lambda: any('RECOVERY_ACK_AFTER_RESET' in t for t in sent_texts()), diagnostic)+ after = rows()+ assert after['AFTER_RESET']['session'] != paused_session+ # Exactly one notice for the whole pause episode, and the pause itself is intact:+ # the lost turn stays unknown and its followers never ran on their own.+ assert len(notices()) == 1, notices()+ assert after['BLOCK_STARTED']['status'] == 'unknown'+ assert after['AFTER_CRASH_ONE']['status'] == after['AFTER_CRASH_TWO']['status'] == 'queued'+ texts = [next(m['content'] for m in reversed(r['messages']) if m['role'] == 'user') for r in model.requests]+ assert not any('AFTER_CRASH' in t for t in texts), texts+ print(json.dumps({'notice': notices()[0], 'final_rows': rows()}))+ finally:+ model.release.set()+ for peer in (model, bot):+ peer.shutdown()+ peer.server_close()