The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): the restart/shutdown reason survives a viewer reconnect
Tekniumb6123b8f70ca
diff --git a/gateway/session_results.py b/gateway/session_results.pyindex 13b8ab653ab..3df19a58fed 100644--- a/gateway/session_results.py+++ b/gateway/session_results.py@@ -84,8 +84,16 @@ def finish_result(db, *, epoch, row, response, outcome, result=None, prepared=Noresult = load_result(saved[0])return dict(current), result['result'].get('final_response') or ''outcome, stored = prepared or prepare_result(row, response, outcome, result)+ # A turn the owner's restart/stop interrupted: its reason commits as a Hermes transcript notice+ # in this same write, so a viewer that reconnects after the restart reads why (#134889 GW-21);+ # the live ``message.complete.warning`` carries the same copy. A retry that finds the row+ # terminal returns above, so the notice is written once.+ from gateway.session_settlement_recovery import owner_stop_notice+ notice = owner_stop_notice(result, outcome, row)+ write = None if notice is None else (lambda conn, _current: close_discarded_turn(db, conn, row, notice))settled = settle_session_input(db, epoch=epoch, admission_id=row['admission_id'],- generation=row['generation'], outcome=outcome, result=stored, _transfers=transfers)+ generation=row['generation'], outcome=outcome, result=stored, _transfers=transfers,+ _terminal_write=write)return settled, responsediff --git a/hermes_state_runtime.py b/hermes_state_runtime.pyindex c55311acb54..d8584482166 100644--- a/hermes_state_runtime.py+++ b/hermes_state_runtime.py@@ -232,7 +232,10 @@ def claim_session_input(db, *, epoch: int, session_id: str, _guard=None, head=_Adef settle_session_input(db, *, epoch: int, admission_id: str, generation: int, outcome: str,- result: dict | None = None, _transfers=None) -> dict:+ result: dict | None = None, _transfers=None, _terminal_write=None) -> dict:+ """``_terminal_write(conn, row)`` is the owner's same-transaction effect (a transcript notice,+ ``gateway.session_results.finish_result``); like ``resolve_unknown_session_input``'s it must+ not commit, may run again on SQLite retry, and raising rolls the settlement back."""if outcome not in ('completed', 'interrupted', 'rejected', 'failed'):raise RuntimeStoreError('invalid_params')from hermes_state_terminal import compact_result, encode_result@@ -245,6 +248,8 @@ def settle_session_input(db, *, epoch: int, admission_id: str, generation: int,or session['runtime_generation'] != generation):raise RuntimeStoreError('stale_generation')_retire_admission_workers(conn, row, epoch)+ if _terminal_write is not None:+ _terminal_write(conn, row)if result is not None:from hermes_state_terminal import RESULT_PREFIXencoded = _json(encode_result(compact_result(result, user_message=json.loads(row['payload_json']).get('text'))))diff --git a/tests/gateway/test_restart_interrupt_notice.py b/tests/gateway/test_restart_interrupt_notice.pyindex ab0219aa716..33894928ab4 100644--- a/tests/gateway/test_restart_interrupt_notice.py+++ b/tests/gateway/test_restart_interrupt_notice.py@@ -224,8 +224,10 @@ def test_managed_worker_turn_settles_with_the_cause_of_the_stop_that_reached_it(assert complete['status'] == 'interrupted'if user_stopped_first:assert 'warning' not in complete, complete+ assert _notices(db) == []else:assert complete['warning'] == RESTART_INTERRUPT_NOTICE+ assert _notices(db) == [RESTART_INTERRUPT_NOTICE] # GW-21: a reconnecting viewer reads it too@pytest.mark.parametrize('user_stopped_first', [False, True])@@ -322,3 +324,74 @@ def test_automation_turn_the_owner_stop_interrupted_is_never_asked_to_resend(cau(frame,) = stream.framesassert frame['warning'] == AUTOMATION_INTERRUPTED_NOTICEassert 'again' not in frame['warning'].replace('not run again', '')+++def _settle_on_real_store(tmp_path, cause, principal='person', payload=None):+ """One claimed admission on a real SessionDB settled through commit_and_publish (the owner's+ worker-thread settlement) with *cause* recorded. Returns (db, row, frames, settlement)."""+ from gateway.session_authority import LiveSession, SessionAuthority+ from gateway.session_contract import SessionRef+ from gateway.session_settlement_recovery import commit_and_publish+ from hermes_state import SessionDB+ from hermes_state_runtime import admit_session_input, begin_runtime_epoch, claim_session_input++ runner = SimpleNamespace(_draining=False, _running=True, _restart_requested=True)+ db = SessionDB(db_path=tmp_path / 'state.db')+ db.create_session('s', source='test')+ epoch = begin_runtime_epoch(db, instance_id='owner')+ authority = SessionAuthority(runner, profile_id='owned', instance_id='owner', db=db, epoch=epoch)+ live = authority.sessions['s'] = LiveSession(None, 'route')+ ref = SessionRef('owned', 's')+ admit_session_input(db, epoch=epoch, principal_id=principal, session_id='s', request_id='r',+ payload=payload or {'text': 'please work'})+ row = claim_session_input(db, epoch=epoch, session_id='s')+ authority._stamp_claim(ref, live, row)+ db.append_message('s', 'user', 'please work') # the turn's own rows, as the agent wrote them+ db.append_message('s', 'assistant', 'partial reply')+ frames = []+ live.event_stream.observers.add(frames.append)+ result = {'final_response': 'partial reply', 'messages': [], 'interrupted': True, 'completed': False}+ if cause:+ result['interrupt_message'] = cause+ settlement = {}+ commit_and_publish(authority, live, ref, row, 'partial reply', 'interrupted', {'result': result}, settlement)+ return db, authority, row, frames, settlement+++def _notices(db):+ from agent.turn_failure_copy import FAILED_TURN_DISPLAY_KIND+ return [m['content'] for m in db.get_messages('s') if m.get('display_kind') == FAILED_TURN_DISPLAY_KIND]++[email protected](('cause', 'notice'), [('Gateway restarting', RESTART_INTERRUPT_NOTICE),+ ('Gateway shutting down', SHUTDOWN_INTERRUPT_NOTICE)])+def test_owner_stop_reason_is_in_the_transcript_for_a_viewer_that_reconnects(tmp_path, cause, notice):+ """#134889 GW-21: a viewer that reconnects after the restart reads the transcript, not the live+ frame. The reason commits as a Hermes notice in the settlement's own write, once; the live+ ``message.complete.warning`` stays."""+ from gateway.session_results import finish_result+ db, authority, row, frames, settlement = _settle_on_real_store(tmp_path, cause)+ with db:+ assert settlement['settled']['outcome'] == 'interrupted'+ assert _notices(db) == [notice]+ (complete,) = [f['params']['payload'] for f in frames if f['params']['type'] == 'message.complete']+ assert complete['warning'] == notice+ # A settlement retry that reads the committed row back never writes the notice again.+ finish_result(db, epoch=authority.epoch, row=row, response='partial reply', outcome='interrupted',+ result={'result': {'final_response': 'partial reply', 'messages': [], 'interrupted': True,+ 'interrupt_message': cause}})+ assert _notices(db) == [notice]++[email protected]('cause', [None, 'User requested stop'])+def test_a_user_stop_writes_no_transcript_notice(tmp_path, cause):+ db, *_ = _settle_on_real_store(tmp_path, cause)+ with db:+ assert _notices(db) == []+++def test_automation_turn_transcript_notice_is_the_neutral_copy(tmp_path):+ from agent.turn_failure_copy import AUTOMATION_INTERRUPTED_NOTICE+ db, *_ = _settle_on_real_store(tmp_path, 'Gateway restarting', principal='cron-owner')+ with db:+ assert _notices(db) == [AUTOMATION_INTERRUPTED_NOTICE]