The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): exit and /new end a session's delegations; unviewed completions become notes
unsupportedpastelsd04e580956b9
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.pyindex 8a67168982c..d62859f1062 100644--- a/gateway/run_notifications.py+++ b/gateway/run_notifications.py@@ -984,7 +984,11 @@ class GatewayNotificationsMixin(GatewayUpdateNotificationsMixin, GatewayNotificaparent_session_id, entry.session_id if entry else "",)target_session_id = parent_session_id- if verdict == "deliver" and parent is not None and parent.get("ended_at"):+ # A local conversation a viewer closed keeps its own work as a note on its closed tip (#134889 LC-7).+ closed_tip = await self._closed_local_target(session_db, entry, parent_session_id, parent)+ if closed_tip:+ verdict, target_session_id = "deliver", closed_tip+ elif verdict == "deliver" and parent is not None and parent.get("ended_at"):end_reason = str(parent.get("end_reason") or "")if end_reason != "compression":# Only a USER-closed session (/new, user_exit, session_switch) is unreachable; idle/timeoutdiff --git a/gateway/run_notifications_ownership.py b/gateway/run_notifications_ownership.pyindex d73e0f18f29..583f6be374e 100644--- a/gateway/run_notifications_ownership.py+++ b/gateway/run_notifications_ownership.py@@ -63,6 +63,31 @@ class GatewayNotificationOwnershipMixin:)return "terminal", None+ async def _closed_local_target(+ self, session_db: Any, entry: Optional[SessionEntry], pinned_session_id: str, pinned_row: Optional[dict],+ ) -> str:+ """The closed (/new, exit) physical session of a local conversation a completion is noted on+ (#134889 LC-7, ``session_completion_notes``), else ``""``. The pinned session, or the compression+ tip it rotated to, must be the one the conversation's route still names: a local /new opens a new+ route, so the replacement never matches, and messaging routes never qualify. Only a close ends a+ local tip (``session.detach {end_reason}`` stamps the client's own reason: ``cli_close``,+ ``tui_close``, ``tui_shutdown``...), so any end but compression is one."""+ from gateway.config import Platform+ if entry is None or entry.platform != Platform.LOCAL or pinned_row is None:+ return ""+ target, row = pinned_session_id, pinned_row+ if row.get("end_reason") == "compression":+ try:+ target = await session_db.get_compression_tip(pinned_session_id)+ row = await session_db.get_session(target) if target == entry.session_id else None+ except Exception:+ logger.debug("Closed local tip lookup failed for %s", pinned_session_id, exc_info=True)+ return "" # the compression path below defers it+ if (target != entry.session_id or row is None or not row.get("ended_at")+ or row.get("end_reason") == "compression"):+ return ""+ return target+async def _lookup_completion_owner(self, session_id: str, current_session_id: str = ""):"""Nonmutating delegation proof shared by preflight and route resolution.diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex dc062223ebc..c9d18673222 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -232,6 +232,8 @@ class SessionAuthority:if member == actor), None) or uuid.uuid4().hexlive.subscribers[subscription] = actorself.pending_closes.pop(ref.session_id, None)+ from tools.async_delegation import allow_for_session+ allow_for_session((self.profile_id, ref.session_id)) # a closed session's work may start againtransport = self.events.get(actor.transport_id)if transport is not None:live.event_stream.fanout.attach(transport)@@ -844,7 +846,9 @@ class SessionAuthority:# tracked so retirement and the shutdown close gate count it.from gateway.session_local_recovery import reopen_local_sessionfrom gateway.session_runtime_workers import tracked_write- await tracked_write(self, partial(reopen_local_session, self, ref))+ from gateway.session_completion_notes import noted_completion+ if not noted_completion(first): # a note leaves a closed row closed (session_completion_notes)+ await tracked_write(self, partial(reopen_local_session, self, ref))if first is not None and 'native_text_v1' in first['payload']:from gateway.session_envelope import check_native_routeawait check_native_route(self.runner, first['payload'], self.physical_target(ref), live.source,diff --git a/gateway/session_completion_notes.py b/gateway/session_completion_notes.pynew file mode 100644index 00000000000..bcb60876dee--- /dev/null+++ b/gateway/session_completion_notes.py@@ -0,0 +1,61 @@+"""A completion for a local session no viewer is watching is written into it as a note (#134889 LC-7).++Main's CLI and TUI hosted async delegations and background processes in their own process, so once+the user left nothing started a turn for them. Under the gateway the owner outlives its viewers. The+completion is admitted like any producer input. Producers still coalesce a batch into one admission+under its primary identity, the siblings' identities in its descriptor: a lookup by any of them finds+it (``completion_admission``), results already admitted are left out of a new batch, and the one+outcome, note or turn, covers the whole batch. When that admission comes up for execution with no+viewer attached (the authority's own subscriber records) the executor records it in the session's+history, where the next turn sees it, and settles the admission without a model call. Queue order, restart survival and+exactly-once are the admission contract's. With a viewer attached it runs as the turn it always was;+messaging, cron, Kanban, ``/loop`` and heartbeat wakes never reach here.+"""+import json+from functools import partial++# ``_completion_delivery_identity`` kinds: an async delegation's result, a background process's exit+# and its watch-pattern notices.+_NOTED_PRODUCERS = frozenset({'async_delegation', 'completion', 'watch_match', 'watch_disabled'})+++def _producer(identity):+ try:+ return json.loads(identity)[0]+ except (ValueError, TypeError, IndexError, KeyError):+ return None+++def noted_completion(row):+ """*row* is a local completion admission: a note when it runs with no viewer attached."""+ descriptor = (row or {}).get('payload', {}).get('local_automation_v1')+ return descriptor is not None and _producer(descriptor['identity']) in _NOTED_PRODUCERS+++async def note_if_unviewed(authority, ref, row):+ """The claimed *row*'s response when it was written as a note instead of running, else None.+ It is the FIFO head, so the note lands after every input committed before it and before every+ input committed after; the viewer check and the decision share one loop step."""+ if not noted_completion(row):+ return None+ from gateway.session_runtime_workers import tracked_write+ live = authority.sessions.get(ref.session_id)+ if live is None or live.subscribers:+ # The claim left a closed row closed for a note; the turn reopens it as any first turn does.+ from gateway.session_local_recovery import reopen_local_session+ await tracked_write(authority, partial(reopen_local_session, authority, ref))+ return None+ from gateway.session_viewer_close import _physical_target+ descriptor = row['payload']['local_automation_v1']+ metadata = {'completion_note': sorted(set(descriptor.get('identities') or ()) | {descriptor['identity']})}+ metadata.update({key: descriptor[key] for key in ('display_text', 'notification_category') if key in descriptor})+ target = _physical_target(authority, ref.session_id)+ # Keyed by its admission: a claim is never replayed, and this keeps a write retry exact.+ await tracked_write(authority, partial(+ authority.db.append_completion_note, target, row['admission_id'], row['payload']['text'],+ descriptor.get('display_kind', 'internal_notification'), metadata))+ refresh = getattr(authority.runner, '_refresh_agent_cache_message_count', None)+ if refresh is not None: # the owner's own row: a cached agent stays, as after a turn's writes+ await refresh(live.route, target)+ authority.pending_results[row['admission_id']] = {'result': {'final_response': '', 'messages': []}, 'usage': {}}+ return ''diff --git a/gateway/session_ingress.py b/gateway/session_ingress.pyindex b2efffe1dfd..e51a2c31ab7 100644--- a/gateway/session_ingress.py+++ b/gateway/session_ingress.py@@ -199,6 +199,10 @@ def row_turn_author(policy, row):async def execute_admission(authority, ref, row):+ from gateway.session_completion_notes import note_if_unviewed+ noted = await note_if_unviewed(authority, ref, row) # #134889 LC-7: no viewer, no turn+ if noted is not None:+ return notedfrom gateway.session_policy import policy_for_sourcepolicy = policy_for_source(authority.runner, authority.sessions[ref.session_id].source)if policy is not None and policy.source == 'cron':diff --git a/gateway/session_viewer_close.py b/gateway/session_viewer_close.pyindex c60dbdb1e6b..dd09a92ccd8 100644--- a/gateway/session_viewer_close.py+++ b/gateway/session_viewer_close.py@@ -47,7 +47,19 @@ class _PendingClose:async def close_viewer_session(authority, session_id, reason):- """``session.detach {end_reason}`` left *session_id* without viewers: close it now, or once idle."""+ """``session.detach {end_reason}`` left *session_id* without viewers: close it now, or once idle.+ Its own async delegations end now, mid-turn too, as main's CLI exit and TUI close ended them+ (#134889 LC-7); each returns as an interrupted completion, and ones its still-running turn starts+ later are refused until a viewer attaches again. Other sessions' work is untouched."""+ live = authority.sessions[session_id]+ if live.subscribers:+ return # a viewer attached while the detach was off the loop: nothing closes or ends+ from tools.async_delegation import interrupt_for_session, refuse_for_session+ route = live.route+ parents = tuple(dict.fromkeys((session_id, _physical_target(authority, session_id))))+ refuse_for_session((authority.profile_id, session_id), session_key=route, parent_session_ids=parents)+ for parent in parents:+ interrupt_for_session(session_key=route, parent_session_id=parent, reason=f'viewer_close:{reason}')authority.pending_closes[session_id] = _PendingClose(reason)await settle_viewer_close(authority, session_id)diff --git a/hermes_state_messages.py b/hermes_state_messages.pyindex 639dc3e19af..12b8ef5af92 100644--- a/hermes_state_messages.py+++ b/hermes_state_messages.py@@ -35,6 +35,13 @@ _INSERT_MESSAGE_SQL = """INSERT INTO messages (session_id, role, content, tool_cdisplay_metadata, display_identity, message_uid, absorbed_message_uids, tool_call_uids,tool_call_uid)VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"""+# Rows of a session and of the parents it was compressed from; a detached result's match condition follows.+_LINEAGE_MATCH_SQL = """WITH RECURSIVE lineage(id) AS (SELECT ? UNION+ SELECT s.parent_session_id FROM sessions s JOIN lineage l ON s.id = l.id+ JOIN sessions p ON p.id = s.parent_session_id WHERE p.end_reason = 'compression'+) SELECT m.id FROM messages m JOIN lineage l ON m.session_id = l.id WHERE """+_DELEGATION_DELIVERY_MATCH = ("m.display_kind IN ('async_delegation_complete', 'hidden') AND json_extract(m.display_metadata, "+ "'$.delegation_id') = ? AND coalesce(json_extract(m.display_metadata, '$.delivery_notice'), '') = ?")# Every column this module knows how to read: the ones it writes plus the three SQLite/compaction# owns. `_row_to_message_dict` drops raw bytes ONLY outside this set — a schema column keeps its# key (and its typed decoder) even when a row holds a BLOB, so no reader ever loses msg["content"].@@ -421,35 +428,36 @@ class SessionMessagesMixin:return self._execute_write(_do, patience_s=self._TRANSCRIPT_WRITE_PATIENCE_S)def append_delegation_delivery(self, session_id: str, content: str, metadata: dict[str, Any]) -> int:- """Record a detached API result once, between client turns, including replay after rotation.-- The event's unit id, not its text or active flag, is the identity. Check and insert- share the writer transaction, so independent gateway processes cannot duplicate it.- """+ """Record a detached API result once, keyed by the event's unit id (not its text or active flag)."""delegation_id = metadata.get("delegation_id")if not delegation_id:raise ValueError("Delegation delivery requires a stable delegation_id")- msg = {"content": content,- "display_kind": "hidden" if metadata.get("presentation_suppressed") else "async_delegation_complete",- "display_metadata": metadata}+ kind = "hidden" if metadata.get("presentation_suppressed") else "async_delegation_complete"+ return self._append_detached_result(session_id, content, kind, metadata, _DELEGATION_DELIVERY_MATCH,+ (delegation_id, metadata.get("delivery_notice", "")))++ def append_completion_note(self, session_id: str, admission_id: str, content: str, display_kind: str,+ metadata: dict[str, Any]) -> int:+ """Record an unviewed completion's note once, keyed by its admission (stored as ``completion_admission``)."""+ return self._append_detached_result(+ session_id, content, display_kind, {**metadata, "completion_admission": admission_id},+ "json_extract(m.display_metadata, '$.completion_admission') = ?", (admission_id,))++ def _append_detached_result(self, session_id: str, content: str, display_kind: str, metadata: dict[str, Any],+ match_sql: str, params: tuple) -> int:+ """Record a result that arrived between turns as a user row once, including replay after rotation: a row+ ``match_sql`` (a condition on ``m``) finds in the compression lineage is returned instead. Check and insert+ share the writer transaction, so independent gateway processes cannot duplicate it; a live turn refuses it."""+ msg = {"content": content, "display_kind": display_kind, "display_metadata": metadata}stamp_message_uid(msg) # a fresh occurrence: mint its durable id- params = self._message_row_params(session_id, "user", msg, None, time.time(), keep_reasoning=True)+ row = self._message_row_params(session_id, "user", msg, None, time.time(), keep_reasoning=True)def _do(conn):- existing = conn.execute(- """WITH RECURSIVE lineage(id) AS (- SELECT ? UNION- SELECT s.parent_session_id FROM sessions s JOIN lineage l ON s.id = l.id- JOIN sessions p ON p.id = s.parent_session_id WHERE p.end_reason = 'compression'- ) SELECT m.id FROM messages m JOIN lineage l ON m.session_id = l.id- WHERE m.display_kind IN ('async_delegation_complete', 'hidden')- AND json_extract(m.display_metadata, '$.delegation_id') = ?- AND coalesce(json_extract(m.display_metadata, '$.delivery_notice'), '') = ? LIMIT 1""",- (session_id, delegation_id, metadata.get("delivery_notice", ""))).fetchone()+ existing = conn.execute(_LINEAGE_MATCH_SQL + match_sql + " LIMIT 1", (session_id, *params)).fetchone()if existing is not None:return existing[0]self._check_transcript_write_guards(conn, session_id, None, reject_active_turn_lease=True)- msg_id = conn.execute(_INSERT_MESSAGE_SQL, params).lastrowid+ msg_id = conn.execute(_INSERT_MESSAGE_SQL, row).lastrowidself._bump_session_counters(conn, session_id, 1, 0, unit=True)return msg_iddiff --git a/tests/gateway/fixtures/local_automation_peer.py b/tests/gateway/fixtures/local_automation_peer.pyindex 0c8d81e0456..50cc973a144 100644--- a/tests/gateway/fixtures/local_automation_peer.py+++ b/tests/gateway/fixtures/local_automation_peer.py@@ -44,6 +44,50 @@ def probe(base, source):async def wait(predicate):await async_wait_until(predicate, timeout=30)+ def notes():+ with sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True) as db:+ return db.execute("SELECT display_kind, json_extract(display_metadata, '$.display_text') FROM messages"+ " WHERE role='user' AND content LIKE ?", ('%REAL_TERMINAL_COMPLETION%',)).fetchall()++ def completion_turns():+ # Model calls whose newest user input is the completion: an automation turn for it.+ return [r for r in model.requests if r.get('messages') and 'REAL_TERMINAL_COMPLETION' in str(next(+ (m.get('content', '') for m in reversed(r['messages']) if m['role'] == 'user'), ''))]++ async def unviewed(desc, sid):+ # No viewer is left (#134889 LC-7): the completion is committed behind the running turn and the+ # human follower, in FIFO order, and when it reaches the head it is written into the session as a+ # note (no model call) instead of an automation turn; the next turn sees it.+ await wait(lambda: any(r['principal_id'].startswith('automation:') for r in rows()))+ automatic = [r for r in rows() if r['principal_id'].startswith('automation:')]+ assert len(automatic) == 1 and automatic[0]['status'] == 'queued', automatic+ assert json.loads(automatic[0]['request_id'])[0] == ('watch_match' if watch else 'completion'), automatic+ assert automatic[0]['seq'] > next(r for r in rows() if r['request_id'] == 'follower')['seq']+ assert not notes()+ model.release.set()+ await wait(lambda: all(r['status'] == 'terminal' for r in rows()))+ await async_wait_until(notes, timeout=120)+ await asyncio.sleep(8) # health: allow HX013 -- proves no automation turn or second note arrives+ assert completion_turns() == [], 'an unviewed completion started a model turn'+ assert all(r['outcome'] == 'completed' for r in rows()), rows()+ found = notes()+ if watch: # a watch match is a notice, not the async-result card+ assert len(found) == 1 and found[0][0] == 'internal_notification', found+ else:+ assert len(found) == 1 and found[0][0] == 'process_complete', found+ assert str(found[0][1]).startswith('Background Process Finished: '), found+ async with websocket(home, desc) as ws:+ assert 'result' in await rpc(ws, 'session.resume', session_id=sid)+ assert 'result' in await rpc(ws, 'prompt.submit', session_id=sid, input_id='after', text='AFTER_NOTE')+ await wait(lambda: next((r['status'] for r in rows() if r['request_id'] == 'after'), '') == 'terminal')+ users = [str(m.get('content')) for m in model.requests[-1]['messages'] if m['role'] == 'user']+ assert 'AFTER_NOTE' in users[-1] and any('REAL_TERMINAL_COMPLETION' in u for u in users), users+ assert 'HUMAN_FIFO_FOLLOWER' in str(users), users+ prefixes = {json.dumps([m for m in r['messages'] if m['role'] in ('system', 'developer')], sort_keys=True)+ for r in model.requests if r.get('messages')}+ assert len(prefixes) == 1, 'the note changed the cached system prefix'+ return {'source': source, 'ledger': rows(), 'note': found, 'observer_closed_before_completion': True}+async def run(desc):async with websocket(home, desc) as ws:result = await rpc(ws, 'session.create', request_id='automation', source=source,@@ -66,43 +110,7 @@ def probe(base, source):await submit('follower', 'HUMAN_FIFO_FOLLOWER')# Last observer closes while owner remains in a model call.model.gate.touch()- await wait(lambda: any(r['principal_id'].startswith('automation:') for r in rows()))- # The completion is in; a duplicate admission would land within this window (none may).- await asyncio.sleep(8) # health: allow HX013 -- proves no second automation row arrives- ledger = rows()- automatic = [r for r in ledger if r['principal_id'].startswith('automation:')]- assert automatic, {'missing_automation': ledger}- assert len(automatic) == 1 and automatic[0]['status'] == 'queued', automatic- if watch:- assert json.loads(automatic[0]['request_id'])[0] == 'watch_match', automatic- assert next(r for r in ledger if r['request_id'] == 'held')['status'] == 'started'- assert automatic[0]['seq'] > next(r for r in ledger if r['request_id'] == 'follower')['seq']- model.release.set()- await wait(lambda: all(r['status'] == 'terminal' for r in rows()))- assert all(r['outcome'] == 'completed' for r in rows()), rows()- texts = [next((m.get('content', '') for m in reversed(r['messages']) if m['role'] == 'user'), '')- for r in model.requests if r.get('messages')]- assert 'REAL_TERMINAL_COMPLETION' in str(texts[-1]), texts- assert sum('REAL_TERMINAL_COMPLETION' in str(text) for text in texts) == 1, texts- with sqlite3.connect(home / 'state.db') as db:- notices = db.execute("SELECT display_kind, json_extract(display_metadata, '$.display_text') FROM messages"- " WHERE role='user' AND content LIKE ?", ('%REAL_TERMINAL_COMPLETION%',)).fetchall()- # A completion is the same async-result card the in-process TUI persisted; a watch match is not one.- assert len(notices) == 1, notices- if watch:- assert notices[0][0] == 'internal_notification', notices- else:- assert notices[0][0] == 'process_complete', notices- assert str(notices[0][1]).startswith('Background Process Finished: '), notices- prefixes = [json.dumps([m for m in r['messages'] if m['role'] in ('system', 'developer')], sort_keys=True)- for r in model.requests if r.get('messages')]- assert len(set(prefixes)) == 1, 'automation changed the cached system prefix'- assert 'HUMAN_FIFO_FOLLOWER' in str(texts[-2]), texts- async with websocket(home, desc) as ws:- resumed = await rpc(ws, 'session.resume', session_id=sid)- assert 'result' in resumed, resumed- return {'source': source, 'ledger': rows(), 'model_inputs': texts,- 'observer_closed_before_completion': True}+ return await unviewed(desc, sid)try:with daemon(root, home, env, barrier=restart, fixture='local_automation_daemon.py') as (proc, desc):@@ -132,8 +140,9 @@ def probe(base, source):asyncio.run(recovered(desc))texts = [next((m.get('content', '') for m in reversed(r['messages']) if m['role'] == 'user'), '')for r in model.requests if r.get('messages')]- completion_inputs = [t for t in texts if 'REAL_TERMINAL_COMPLETION' in str(t)]- assert len(completion_inputs) == 1, texts+ # The committed completion outlived two owners; with no viewer it ran once, as one note.+ assert completion_turns() == [], texts+ assert len(notes()) == 1, notes()assert len(set(pids)) == 3 and epochs == sorted(set(epochs))print(json.dumps({'pids': pids, 'epochs': epochs, 'ledger': rows(),'model_inputs': texts, 'lost_producer_ack': True}))diff --git a/tests/gateway/test_local_automation.py b/tests/gateway/test_local_automation.pyindex 78c85162e8c..aa1ed2b1699 100644--- a/tests/gateway/test_local_automation.py+++ b/tests/gateway/test_local_automation.py@@ -18,9 +18,13 @@ def _probe(tmp_path, source):print(result.stdout)[email protected]('source', ['cli', 'tui', 'gui', 'watch'])-def test_local_completion_joins_fifo_without_an_observer(tmp_path, source):- _probe(tmp_path, source)[email protected]('source', ['cli', 'tui', 'gui'])+def test_local_completion_without_an_observer_is_a_note_the_next_turn_sees(tmp_path, source):+ _probe(tmp_path, source) # #134889 LC-7: no unattended turn+++def test_local_watch_match_without_an_observer_is_a_note(tmp_path):+ _probe(tmp_path, 'watch')def test_local_completion_survives_owner_kill_without_duplicate(tmp_path):diff --git a/tests/gateway/test_session_end_delegations.py b/tests/gateway/test_session_end_delegations.pynew file mode 100644index 00000000000..5ae70169a7f--- /dev/null+++ b/tests/gateway/test_session_end_delegations.py@@ -0,0 +1,336 @@+"""``exit`` and ``/new`` end that session's own async delegations in the gateway; a completion for a+local session no viewer is watching is written into it as a note, not an unattended turn.++Regression for #134889 LC-7. Main's classic CLI interrupted its async delegations at exit and main's+TUI ended a session's own delegations when it closed it; under the gateway the client is a viewer, so+the delegations kept running after it left and their completions (and background-process notices)+started turns nobody watched.+"""+import json+from types import MethodType, SimpleNamespace++import pytest++from tools import async_delegation as delegation++[email protected](autouse=True)+def _no_delegations():+ delegation._reset_for_tests()+ yield+ delegation._reset_for_tests()+++async def _owner(tmp_path, monkeypatch):+ from gateway import run+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.run_shutdown_session_end import GatewaySessionEndMixin+ from gateway.session_authority import initialize_session_authority++ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'platform_toolsets': {'cli': []}})+ monkeypatch.setattr('hermes_cli.lifecycle.invoke_hook', lambda name, **kwargs: None)+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())++ async def finalize(**kwargs):+ return []++ async def housekeeping(func, *args):+ return func(*args)++ runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False,+ _cached_agent_for=lambda route: None,+ _evict_cached_agent_at_boundary=lambda key: None,+ _finalize_session_off_loop=finalize, _FINALIZE_TIMEOUT_S=10.0,+ _run_housekeeping_in_executor=housekeeping,+ _run_release_in_profile_scope=lambda target, args, key: target(*args))+ runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)+ runner._reset_session_off_loop = MethodType(GatewaySessionEndMixin._reset_session_off_loop, runner)+ authority = await initialize_session_authority(runner, profile_id=str(tmp_path), instance_id='owner')+ return store._db, authority+++async def _call(conn, method, **params):+ reply = await conn.dispatch({'id': 1, 'method': method, 'params': params})+ assert 'result' in reply, reply+ return reply['result']+++async def _open(db, authority, tmp_path, session_id):+ from gateway.session_controls import AuthorityConnection+ db.create_session(session_id, source='cli', model='fake-model', cwd=str(tmp_path))+ db.append_message(session_id, 'user', 'q')+ viewer = AuthorityConnection(authority, SimpleNamespace(write=lambda frame: None), {+ 'provider': 'local', 'user_id': 'native', 'profile_id': str(tmp_path), 'instance_id': 'owner'})+ resumed = await _call(viewer, 'session.resume', session_id=session_id)+ db.reopen_session(session_id)+ return viewer, resumed['subscription_id']+++def _running(stopped, delegation_id, *, parent='', route=''):+ """A live async delegation as ``dispatch_async_delegation`` registers it."""+ delegation._records[delegation_id] = {+ 'delegation_id': delegation_id, 'status': 'running', 'parent_session_id': parent,+ 'session_key': route, 'interrupt_fn': lambda: stopped.append(delegation_id)}+++# Classic CLI exit and /new; Ink /new (or a resume switch) and exit.[email protected]('reason', ['cli_close', 'new_session', 'tui_close', 'tui_shutdown'])+async def test_exit_and_new_cancel_only_that_sessions_delegations(tmp_path, monkeypatch, reason):+ db, authority = await _owner(tmp_path, monkeypatch)+ viewer, subscription = await _open(db, authority, tmp_path, 'chat')+ await _open(db, authority, tmp_path, 'other')+ stopped = []+ _running(stopped, 'deleg_parent', parent='chat')+ _running(stopped, 'deleg_route', route=authority.sessions['chat'].route)+ _running(stopped, 'deleg_other', parent='other', route=authority.sessions['other'].route)++ await _call(viewer, 'session.detach', session_id='chat', subscription_id=subscription, end_reason=reason)++ assert sorted(stopped) == ['deleg_parent', 'deleg_route']+++async def test_leaving_without_closing_cancels_nothing(tmp_path, monkeypatch):+ """Desktop closing or a dropped connection detaches without an end reason; another viewer still+ watching keeps the session's work alive even when one viewer exits."""+ db, authority = await _owner(tmp_path, monkeypatch)+ viewer, subscription = await _open(db, authority, tmp_path, 'chat')+ stopped = []+ _running(stopped, 'deleg_parent', parent='chat')++ await _call(viewer, 'session.detach', session_id='chat', subscription_id=subscription)+ assert stopped == []++ first = await _call(viewer, 'session.resume', session_id='chat')+ second, _ = await _open(db, authority, tmp_path, 'unrelated')+ await _call(second, 'session.resume', session_id='chat')+ await _call(viewer, 'session.detach', session_id='chat', subscription_id=first['subscription_id'],+ end_reason='cli_close')+ assert stopped == []+++async def test_viewer_reattaching_during_detach_cleanup_keeps_delegations(tmp_path, monkeypatch):+ """The last viewer's detach awaits the editor-MCP release off the loop; a viewer that attaches+ meanwhile keeps the session's work: the viewer check sits right before the interruption."""+ import asyncio+ import threading+ from gateway import session_local_mcp+ db, authority = await _owner(tmp_path, monkeypatch)+ viewer, subscription = await _open(db, authority, tmp_path, 'chat')+ stopped = []+ _running(stopped, 'deleg_parent', parent='chat')+ entered, release = threading.Event(), threading.Event()++ def suspended(_authority, _session_ids):+ entered.set()+ assert release.wait(10)+ monkeypatch.setattr(session_local_mcp, 'release_editor_mcp', suspended)+ detach = asyncio.ensure_future(_call(viewer, 'session.detach', session_id='chat', subscription_id=subscription,+ end_reason='cli_close'))+ assert await asyncio.to_thread(entered.wait, 10)+ other, _ = await _open(db, authority, tmp_path, 'unrelated')+ await _call(other, 'session.resume', session_id='chat')+ release.set()+ await detach++ assert stopped == []+ assert 'chat' not in authority.pending_closes+ assert db.get_session('chat')['ended_at'] is None+++def _dispatch(route, parent):+ return delegation.dispatch_async_delegation(goal='late', context=None, toolsets=None, role='leaf', model=None,+ session_key=route, parent_session_id=parent,+ runner=lambda: {'status': 'completed'})+++async def test_delegation_started_after_the_close_is_refused_until_a_viewer_returns(tmp_path, monkeypatch):+ """The close interrupts what is registered; the parent turn can still dispatch more (the close+ waits for an idle FIFO, and a fan-out may be mid-build). Those are refused for that session only,+ until a viewer attaches again."""+ db, authority = await _owner(tmp_path, monkeypatch)+ viewer, subscription = await _open(db, authority, tmp_path, 'chat')+ await _open(db, authority, tmp_path, 'other')+ route = authority.sessions['chat'].route++ await _call(viewer, 'session.detach', session_id='chat', subscription_id=subscription, end_reason='cli_close')++ assert _dispatch(route, 'chat')['status'] == 'rejected'+ assert _dispatch('', 'chat')['status'] == 'rejected', 'matched by the parent session too'+ assert _dispatch(authority.sessions['other'].route, 'other')['status'] == 'dispatched'+ await _call(viewer, 'session.resume', session_id='chat')+ assert _dispatch(route, 'chat')['status'] == 'dispatched', 'a viewer that came back keeps its work'+++# --- completions for a local session with no viewer --------------------------------------------++async def _local(tmp_path, monkeypatch):+ from gateway.config import GatewayConfig+ from gateway.run import GatewayRunner+ from gateway.session_authority import SessionAuthority, initialize_session_authority+ from gateway.session_contract import Principal+ from gateway.session_local import create_local_session+ from hermes_state import AsyncSessionDB, SessionDB++ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ monkeypatch.setattr(SessionAuthority, '_schedule', lambda self, ref: None) # admitted rows stay queued+ runner = GatewayRunner(GatewayConfig(sessions_dir=tmp_path / 'sessions'))+ db = SessionDB(tmp_path / 'state.db')+ runner.session_store._db = db+ runner._session_db = AsyncSessionDB(db)+ authority = await initialize_session_authority(runner, profile_id='default', instance_id='lc7', db=db)+ actor = Principal('test-owner', 'default', frozenset({'session:create', 'session:submit', 'session:read'}),+ 'fixture')+ ref = create_local_session(authority, actor, dict(request_id='lc7', source='cli', model='fixture', toolsets=[]))+ return runner, authority, ref, actor+++_PROCESS = ('completion', 'proc_lc7', 1700000000.0)+_DELEGATION = ('async_delegation', 'deleg_lc7', '')+_CARDS = {'completion': 'process_complete', 'async_delegation': 'async_delegation_complete'}+++async def _deliver(runner, authority, ref, producer):+ """What ``_inject_watch_notification`` admits for a finished background process or delegation."""+ from gateway.platforms.event import MessageEvent+ identity = json.dumps(producer, separators=(',', ':'))+ live = authority.sessions[ref.session_id]+ entry = runner.session_store.lookup_by_session_key(live.route)+ event = MessageEvent(text=f'[finished] RESULT_{producer[1]}', source=live.source, internal=True, metadata={+ 'gateway_session_key': live.route, 'gateway_session_id': entry.session_id,+ 'display_kind': _CARDS[producer[0]], 'display_text': f'Finished: {producer[1]}'})+ await authority.admit_automation(runner._adapter_for_source(live.source), event, identity)+ return entry.session_id+++def _admissions(authority, ref):+ from hermes_state_runtime import list_session_admissions+ return [r for r in list_session_admissions(authority.db, session_id=ref.session_id, pending_only=False)+ if r['principal_id'].startswith('automation:')]+++def _notes(authority, target):+ return [m for m in authority.db.get_messages(target) if 'RESULT_' in str(m.get('content'))]+++def _record_turns(runner):+ """The turns the drain actually executes, by their input text (no model call)."""+ seen = []++ async def handle(event):+ seen.append(event.text)+ return 'ok'+ runner._handle_message = handle+ return seen++[email protected]('producer', [_PROCESS, _DELEGATION], ids=['process', 'delegation'])+async def test_unviewed_local_completion_is_a_note_not_a_turn(tmp_path, monkeypatch, producer):+ runner, authority, ref, _actor = await _local(tmp_path, monkeypatch)+ try:+ async def no_turn(event):+ raise AssertionError('no viewer: the completion must not start a turn')+ runner._handle_message = no_turn+ target = await _deliver(runner, authority, ref, producer)+ await authority._drain(ref)+ notes = _notes(authority, target)+ assert len(notes) == 1, notes+ assert notes[0]['role'] == 'user' and notes[0]['display_kind'] == _CARDS[producer[0]]+ assert notes[0]['display_metadata']['display_text'] == f'Finished: {producer[1]}'+ assert [r['outcome'] for r in _admissions(authority, ref)] == ['completed']++ # A producer retry (lost ACK) is the same settled admission, even once a viewer is back:+ # a completion is a note or a turn, never both.+ await _deliver(runner, authority, ref, producer)+ authority.sessions[ref.session_id].subscribers['back'] = _actor+ await _deliver(runner, authority, ref, producer)+ await authority._drain(ref)+ assert len(_notes(authority, target)) == 1 and len(_admissions(authority, ref)) == 1+ finally:+ authority.db.close()+++async def test_viewed_local_completion_still_starts_its_turn(tmp_path, monkeypatch):+ runner, authority, ref, actor = await _local(tmp_path, monkeypatch)+ try:+ authority.sessions[ref.session_id].subscribers['watching'] = actor+ target = await _deliver(runner, authority, ref, _PROCESS)+ assert [r['status'] for r in _admissions(authority, ref)] == ['queued']+ seen = _record_turns(runner)+ await authority._drain(ref)+ assert seen == [f'[finished] RESULT_{_PROCESS[1]}'], 'a watched completion runs as its turn'+ assert [r['outcome'] for r in _admissions(authority, ref)] == ['completed']+ assert _notes(authority, target) == []+ # Its retry after the viewer left is the same settled admission: no second turn, no note.+ authority.sessions[ref.session_id].subscribers.clear()+ await _deliver(runner, authority, ref, _PROCESS)+ await authority._drain(ref)+ assert len(seen) == 1 and len(_admissions(authority, ref)) == 1 and _notes(authority, target) == []+ finally:+ authority.db.close()+++async def test_messaging_completion_still_starts_its_turn(tmp_path, monkeypatch):+ """A messaging chat has no viewers at all: its completion keeps admitting a turn, as on main."""+ from gateway.config import GatewayConfig, Platform, PlatformConfig+ from gateway.platforms.event import MessageEvent+ from gateway.run import GatewayRunner+ from gateway.session_authority import SessionAuthority, initialize_session_authority+ from gateway.session_ingress_context import native_callback+ from hermes_constants import get_hermes_home+ from hermes_state_runtime import list_session_admissions+ from plugins.platforms.discord.adapter import DiscordAdapter+ from tests.gateway.test_completion_admission import pending++ monkeypatch.setattr(SessionAuthority, '_schedule', lambda self, ref: None)+ monkeypatch.setenv('DISCORD_ALLOWED_USERS', '42')+ runner = GatewayRunner(GatewayConfig())+ adapter = DiscordAdapter(PlatformConfig(enabled=True, token='fixture-token', typing_indicator=False))+ runner.adapters = {Platform.DISCORD: adapter}+ authority = await initialize_session_authority(runner, profile_id='default', instance_id='lc7-messaging')+ runner._wire_adapter_handlers(adapter)+ source = adapter.build_source(chat_id='42', chat_type='dm', user_id='42')+ human = MessageEvent(text='human', source=source, message_id='human')+ with native_callback(runner, human, get_hermes_home()):+ await authority.admit_native(human)+ key = runner.session_store._generate_session_key(source)+ sid = runner.session_store.peek_session_id(key)+ assert await runner._deliver_async_delegation_group([dict(pending(key, 'deleg_chat'), parent_session_id=sid)])+ rows = list_session_admissions(authority.db, session_id=sid, pending_only=False)+ assert [r['principal_id'].startswith('automation:') for r in rows] == [False, True], rows+ seen = _record_turns(runner)+ from gateway.session_contract import SessionRef+ await authority._drain(SessionRef(authority.profile_id, sid))+ assert seen[0] == 'human' and len(seen) == 2 and 'deleg_chat' in seen[1], 'the completion ran as a turn'+ rows = list_session_admissions(authority.db, session_id=sid, pending_only=False)+ assert [r['outcome'] for r in rows] == ['completed', 'completed']+ assert not [m for m in authority.db.get_messages(sid) if 'deleg_chat' in str(m.get('content'))]+++async def test_other_local_automation_is_unchanged(tmp_path, monkeypatch):+ """Only completions become notes: a /loop tick or Kanban wake keeps its turn with no viewer."""+ from gateway.session_automation import admit_route_wake+ runner, authority, ref, _actor = await _local(tmp_path, monkeypatch)+ try:+ live = authority.sessions[ref.session_id]+ assert await admit_route_wake(runner, runner._adapter_for_source(live.source), live.source,+ 'TICK', 'loop-tick')+ assert [r['status'] for r in _admissions(authority, ref)] == ['queued']+ assert not live.subscribers+ seen = _record_turns(runner)+ await authority._drain(ref)+ assert seen == ['TICK'], 'no viewer, and the wake still runs as its turn'+ assert [r['outcome'] for r in _admissions(authority, ref)] == ['completed']+ target = runner.session_store.lookup_by_session_key(live.route).session_id+ assert not [m for m in authority.db.get_messages(target) if 'TICK' in str(m.get('content'))]+ finally:+ authority.db.close()diff --git a/tests/gateway/test_unviewed_completion_notes.py b/tests/gateway/test_unviewed_completion_notes.pynew file mode 100644index 00000000000..fe7c06d65c9--- /dev/null+++ b/tests/gateway/test_unviewed_completion_notes.py@@ -0,0 +1,376 @@+"""An unviewed local completion becomes a note through the gateway FIFO, never a lost or early one.++Regression for the #134889 LC-7 review. The completion is admitted durably like any producer input (a+coalesced batch is one admission, found by any of its identities); when that admission comes up for+execution with no viewer attached, the executor writes the note (no model call) and settles the+admission. Busy sessions, queue order, owner restarts and lost acknowledgements are the admission+contract's, not a retry budget's.+"""+import pytest++from tests.gateway.test_completion_admission import pending+from tests.gateway.test_session_end_delegations import _PROCESS, _admissions, _deliver, _local, _notes+from tools import async_delegation as delegation++[email protected](autouse=True)+def _no_delegations():+ delegation._reset_for_tests()+ yield+ delegation._reset_for_tests()+++def _human(authority, ref, request_id, text):+ from hermes_state_runtime import admit_session_input+ return admit_session_input(authority.db, epoch=authority.epoch, principal_id='test-owner',+ session_id=ref.session_id, request_id=request_id, payload={'text': text})+++def _turns(runner, authority, target, marker='RESULT_'):+ """Record every turn the drain runs, with the notes the transcript held when it started."""+ seen = []++ async def handle(event):+ seen.append((event.text, len(_texts(authority, target, marker))))+ return 'ok'+ runner._handle_message = handle+ return seen+++def _texts(authority, target, marker):+ return [m for m in authority.db.get_messages(target) if marker in str(m.get('content'))]+++def _target(runner, authority, ref):+ return runner.session_store.lookup_by_session_key(authority.sessions[ref.session_id].route).session_id+++def _process_event(authority, ref, target, name='proc_busy'):+ """What the process watcher hands ``_deliver_completion_notification`` for a pinned completion."""+ return {'type': 'completion', 'session_id': name, 'started_at': 1700000000.0, 'command': 'make',+ 'exit_code': 0, 'output': f'RESULT_{name}', 'session_key': authority.sessions[ref.session_id].route,+ 'parent_session_id': target}+++async def test_busy_session_keeps_the_completion_durably_until_its_turn(tmp_path, monkeypatch):+ """No ``session_busy`` refusal (so no delivery-failure budget): the completion is committed behind+ the running input and becomes a note when it reaches the head, with notifications off too."""+ runner, authority, ref, _actor = await _local(tmp_path, monkeypatch)+ try:+ target = _target(runner, authority, ref)+ _human(authority, ref, 'human', 'FIRST')+ await _deliver(runner, authority, ref, _PROCESS)+ evt = _process_event(authority, ref, target)+ assert await runner._deliver_completion_notification(f'[finished] RESULT_{evt["session_id"]}', evt) is True+ assert [r['status'] for r in _admissions(authority, ref)] == ['queued', 'queued']+ assert _notes(authority, target) == []++ seen = _turns(runner, authority, target)+ await authority._drain(ref)+ assert seen == [('FIRST', 0)], 'the human input runs first and sees no note yet'+ assert len(_notes(authority, target)) == 2+ assert [r['outcome'] for r in _admissions(authority, ref)] == ['completed', 'completed']+ finally:+ authority.db.close()+++async def test_input_admitted_after_the_completion_sees_its_note(tmp_path, monkeypatch):+ """The idle decision is the FIFO's: a human input committed after the completion runs after its note."""+ runner, authority, ref, _actor = await _local(tmp_path, monkeypatch)+ try:+ target = _target(runner, authority, ref)+ await _deliver(runner, authority, ref, _PROCESS)+ _human(authority, ref, 'human', 'AFTER')+ seen = _turns(runner, authority, target)+ await authority._drain(ref)+ assert seen == [('AFTER', 1)]+ assert len(_notes(authority, target)) == 1+ finally:+ authority.db.close()+++async def test_viewer_back_before_execution_gets_the_turn(tmp_path, monkeypatch):+ """Whether it is a note is decided when the admission runs, not when it was committed."""+ runner, authority, ref, actor = await _local(tmp_path, monkeypatch)+ try:+ target = _target(runner, authority, ref)+ await _deliver(runner, authority, ref, _PROCESS)+ authority.sessions[ref.session_id].subscribers['back'] = actor+ seen = _turns(runner, authority, target)+ await authority._drain(ref)+ assert [text for text, _ in seen] == [f'[finished] RESULT_{_PROCESS[1]}']+ assert [r['outcome'] for r in _admissions(authority, ref)] == ['completed']+ assert _notes(authority, target) == []+ assert not [m for m in authority.db.get_messages(target)+ if (m.get('display_metadata') or {}).get('completion_admission')]+ finally:+ authority.db.close()+++async def test_note_keeps_the_cached_agent(tmp_path, monkeypatch):+ """A plain disconnect keeps the cached agent; the owner's own note re-baselines its message count,+ so the next turn reuses it instead of reading the note as an outside write and rebuilding."""+ runner, authority, ref, _actor = await _local(tmp_path, monkeypatch)+ try:+ target, route = _target(runner, authority, ref), authority.sessions[ref.session_id].route+ agent, before = object(), authority.db.get_session(target)['message_count']+ runner._agent_cache[route] = (agent, 'sig', before, target)+ await _deliver(runner, authority, ref, _PROCESS)+ await authority._drain(ref)+ assert len(_notes(authority, target)) == 1+ after = authority.db.get_session(target)['message_count']+ assert after == before + 1+ assert runner._agent_cache[route] == (agent, 'sig', after, target), 'the next turn would rebuild the agent'+ finally:+ authority.db.close()+++async def test_watch_notice_without_a_viewer_is_a_note(tmp_path, monkeypatch):+ from gateway.platforms.event import MessageEvent+ runner, authority, ref, _actor = await _local(tmp_path, monkeypatch)+ try:+ target = _target(runner, authority, ref)+ live = authority.sessions[ref.session_id]+ for kind in ('watch_match', 'watch_disabled'):+ identity = f'["{kind}","proc_watch","evt-1"]'+ event = MessageEvent(text=f'[watch] RESULT_{kind}', source=live.source, internal=True, metadata={+ 'gateway_session_key': live.route, 'gateway_session_id': target})+ await authority.admit_automation(runner._adapter_for_source(live.source), event, identity)+ seen = _turns(runner, authority, target)+ await authority._drain(ref)+ assert seen == []+ assert [m['content'] for m in _notes(authority, target)] == ['[watch] RESULT_watch_match',+ '[watch] RESULT_watch_disabled']+ finally:+ authority.db.close()+++async def _restart(tmp_path, monkeypatch, old):+ """A real owner restart over the same state.db: new runner, new epoch, local sessions recovered."""+ from gateway.config import GatewayConfig+ from gateway.run import GatewayRunner+ from gateway.session_authority import initialize_session_authority+ from hermes_state import AsyncSessionDB, SessionDB+ path = old.db.db_path+ old.db.close()+ runner = GatewayRunner(GatewayConfig(sessions_dir=tmp_path / 'sessions'))+ db = SessionDB(path)+ runner.session_store._db = db+ runner._session_db = AsyncSessionDB(db)+ authority = await initialize_session_authority(runner, profile_id='default', instance_id='lc7-restarted', db=db)+ assert authority.epoch > old.epoch+ return runner, authority+++def _delegation_note(authority, target, name):+ return [m for m in authority.db.get_messages(target) if name in str(m.get('content'))]+++async def test_lost_ack_restart_and_regrouped_batch_note_each_result_once(tmp_path, monkeypatch):+ """A is noted but its producer claim is never acknowledged; after a real owner restart A is offered+ again grouped with a fresh B. A resolves to its committed admission, B is noted, each once."""+ runner, authority, ref, _actor = await _local(tmp_path, monkeypatch)+ route = authority.sessions[ref.session_id].route+ target = _target(runner, authority, ref)+ first = dict(pending(route, 'deleg_alpha'), parent_session_id=target)+ lost = []+ monkeypatch.setattr(type(runner), '_settle_durable_claim', staticmethod(lambda *args: lost.append(args)))+ assert await runner._deliver_async_delegation_group([first]) is True+ await authority._drain(ref)+ assert len(_delegation_note(authority, target, 'deleg_alpha')) == 1+ assert lost and lost[0][0] == 'complete', 'the acknowledgement was the step that got lost'+ monkeypatch.undo()++ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ monkeypatch.setattr(delegation, '_CLAIM_LEASE_S', -1.0) # the dead owner's claim is reclaimable+ runner, authority = await _restart(tmp_path, monkeypatch, authority)+ from gateway.session_authority import SessionAuthority+ monkeypatch.setattr(SessionAuthority, '_schedule', lambda self, ref: None)+ try:+ second = dict(pending(route, 'deleg_bravo'), parent_session_id=target)+ assert await runner._deliver_async_delegation_group([dict(first), second]) is True+ await authority._drain(ref)+ assert len(_delegation_note(authority, target, 'deleg_alpha')) == 1+ assert len(_delegation_note(authority, target, 'deleg_bravo')) == 1, 'a fresh sibling was dropped'+ assert [r['outcome'] for r in _admissions(authority, ref)] == ['completed', 'completed']+ finally:+ authority.db.close()++[email protected]('producer', ['delegation', 'process'])+async def test_executed_turn_stays_a_turn_after_lost_ack_detach_and_restart(tmp_path, monkeypatch, producer):+ """A watched completion ran as its turn, but the producer never saw the acknowledgement. The viewer+ leaves, the owner restarts, and the producer offers it again through its real path: it resolves to+ the executed admission, so there is no second turn and no note."""+ runner, authority, ref, actor = await _local(tmp_path, monkeypatch)+ route, target = authority.sessions[ref.session_id].route, _target(runner, authority, ref)+ name = f'{producer}_ran'+ evt = (dict(pending(route, name), parent_session_id=target) if producer == 'delegation'+ else _process_event(authority, ref, target, name))++ async def offer(runner):+ if producer == 'delegation':+ return await runner._deliver_async_delegation_group([dict(evt)])+ return await runner._deliver_completion_notification(f'[finished] RESULT_{name}', dict(evt))+ authority.sessions[ref.session_id].subscribers['watching'] = actor+ with monkeypatch.context() as lost_ack:+ settled = []+ lost_ack.setattr(type(runner), '_settle_durable_claim', staticmethod(lambda *args: settled.append(args)))+ assert await offer(runner) is True+ seen = _turns(runner, authority, target, name)+ await authority._drain(ref)+ assert [text for text, _ in seen] == [_admissions(authority, ref)[0]['payload']['text']]+ assert name in seen[0][0] and seen[0][1] == 0, 'the watched completion ran as a turn'+ assert [r['outcome'] for r in _admissions(authority, ref)] == ['completed']+ if producer == 'delegation':+ assert settled and settled[0][0] == 'complete', 'the acknowledgement was the step that got lost'+ monkeypatch.setattr(delegation, '_CLAIM_LEASE_S', -1.0) # the dead owner's claim is reclaimable++ authority.sessions[ref.session_id].subscribers.clear() # the viewer leaves+ runner, authority = await _restart(tmp_path, monkeypatch, authority)+ try:+ assert not authority.sessions[ref.session_id].subscribers+ seen = _turns(runner, authority, target, name)+ assert await offer(runner) is True, 'the retry resolves to the executed admission'+ await authority._drain(ref)+ assert seen == [], 'never a second turn'+ assert not [m for m in authority.db.get_messages(target)+ if (m.get('display_metadata') or {}).get('completion_admission')], 'never also a note'+ assert _texts(authority, target, name) == []+ assert [r['outcome'] for r in _admissions(authority, ref)] == ['completed']+ finally:+ authority.db.close()+++async def test_queued_completion_survives_owner_restart_as_one_note(tmp_path, monkeypatch):+ runner, authority, ref, _actor = await _local(tmp_path, monkeypatch)+ target = _target(runner, authority, ref)+ _human(authority, ref, 'human', 'FIRST')+ await _deliver(runner, authority, ref, _PROCESS)+ runner, authority = await _restart(tmp_path, monkeypatch, authority)+ try:+ seen = _turns(runner, authority, target)+ await authority._drain(ref)+ await authority._drain(ref)+ assert seen == [('FIRST', 0)]+ assert len(_notes(authority, target)) == 1+ finally:+ authority.db.close()+++# Every last-viewer close a local client sends (``session.detach {end_reason}``): the classic CLI's exit,+# /new, /resume and /branch; Ink's /new or resume switch and its exit.+_CLOSES = ['cli_close', 'new_session', 'resumed_other', 'branched', 'tui_close', 'tui_shutdown']++[email protected]('reason', _CLOSES)[email protected]('producer', ['delegation', 'process'])+async def test_completion_after_new_is_noted_on_the_closed_session(tmp_path, monkeypatch, producer, reason):+ """The viewer closed the session (exit, /new): work finishing afterwards is a note on that original+ session, never dropped and never delivered into the session opened next."""+ from gateway.session_local import create_local_session+ from hermes_state_local import end_idle_local_session+ runner, authority, ref, actor = await _local(tmp_path, monkeypatch)+ try:+ target = _target(runner, authority, ref)+ assert end_idle_local_session(authority.db, epoch=authority.epoch, session_id=ref.session_id,+ target_id=target, reason=reason)+ fresh = create_local_session(authority, actor, dict(request_id='lc7-next', source='cli', model='fixture',+ toolsets=[]))+ route = authority.sessions[ref.session_id].route+ if producer == 'delegation':+ evt = dict(pending(route, 'deleg_after_new'), parent_session_id=target)+ assert await runner._deliver_async_delegation_group([evt]) is True+ name = 'deleg_after_new'+ else:+ evt = _process_event(authority, ref, target, 'proc_after_new')+ assert await runner._deliver_completion_notification('[finished] RESULT_proc_after_new', evt) is True+ name = 'proc_after_new'+ await authority._drain(ref)+ assert len(_delegation_note(authority, target, name)) == 1+ row = authority.db.get_session(target)+ assert row['ended_at'] and row['end_reason'] == reason, 'the note must not reopen the closed session'+ fresh_target = _target(runner, authority, fresh)+ assert not _delegation_note(authority, fresh_target, name)+ assert _admissions(authority, fresh) == []+ finally:+ authority.db.close()+++def _compress(runner, authority, ref, parent, child):+ """A real compression rotation of the local conversation's physical transcript, route included."""+ db = authority.db+ assert db.try_acquire_compression_lock(parent, 'lc7')+ try:+ db.publish_compression_child(parent_session_id=parent, child_session_id=child, source='cli',+ messages=[{'role': 'user', 'content': 'SUMMARY'}], compression_lock_holder='lc7')+ finally:+ db.release_compression_lock(parent, 'lc7')+ assert runner.session_store.advance_compression_session(authority.sessions[ref.session_id].route, parent, child)++[email protected]('reason', _CLOSES)[email protected]('producer', ['delegation', 'process'])+async def test_compressed_then_closed_completion_is_noted_on_the_closed_tip(tmp_path, monkeypatch, producer, reason):+ """Work started before compression stays pinned to the ancestor; the user then closed the compressed+ continuation (exit, /new). The result is a note on that closed tip, not the ancestor, not the replacement."""+ from gateway.session_local import create_local_session+ from hermes_state_local import end_idle_local_session+ runner, authority, ref, actor = await _local(tmp_path, monkeypatch)+ try:+ ancestor = _target(runner, authority, ref)+ _compress(runner, authority, ref, ancestor, 'lc7-tip')+ assert _target(runner, authority, ref) == 'lc7-tip'+ assert end_idle_local_session(authority.db, epoch=authority.epoch, session_id=ref.session_id,+ target_id='lc7-tip', reason=reason)+ fresh = create_local_session(authority, actor, dict(request_id='lc7-next', source='cli', model='fixture',+ toolsets=[]))+ route, name = authority.sessions[ref.session_id].route, f'{producer}_compressed'+ if producer == 'delegation':+ evt = dict(pending(route, name), parent_session_id=ancestor)+ assert await runner._deliver_async_delegation_group([evt]) is True+ else:+ evt = _process_event(authority, ref, ancestor, name)+ assert await runner._deliver_completion_notification(f'[finished] RESULT_{name}', evt) is True+ seen = _turns(runner, authority, 'lc7-tip')+ await authority._drain(ref)+ assert seen == []+ assert len(_delegation_note(authority, 'lc7-tip', name)) == 1+ assert not _delegation_note(authority, ancestor, name)+ row = authority.db.get_session('lc7-tip')+ assert row['ended_at'] and row['end_reason'] == reason, 'the note must not reopen the closed tip'+ assert [r['outcome'] for r in _admissions(authority, ref)] == ['completed']+ assert not _delegation_note(authority, _target(runner, authority, fresh), name)+ assert _admissions(authority, fresh) == []+ finally:+ authority.db.close()+++async def test_closed_tip_note_needs_the_route_to_name_it(tmp_path, monkeypatch):+ """Only the conversation's own continuation qualifies: a local route that names another session is+ never retargeted onto the closed lineage."""+ from hermes_state_local import end_idle_local_session+ runner, authority, ref, _actor = await _local(tmp_path, monkeypatch)+ try:+ ancestor = _target(runner, authority, ref)+ _compress(runner, authority, ref, ancestor, 'lc7-tip')+ assert end_idle_local_session(authority.db, epoch=authority.epoch, session_id=ref.session_id,+ target_id='lc7-tip', reason='new_session')+ route = authority.sessions[ref.session_id].route+ assert await runner._classify_completion_owner(ancestor, route) == ('deliver', ancestor, 'lc7-tip')+ authority.db.create_session('lc7-other', source='cli')+ runner.session_store._entries[route].session_id = 'lc7-other'+ assert (await runner._classify_completion_owner(ancestor, route))[0] != 'deliver'+ finally:+ authority.db.close()diff --git a/tests/tools/test_completed_process_results.py b/tests/tools/test_completed_process_results.pyindex 400d3a863a3..a61d847832d 100644--- a/tests/tools/test_completed_process_results.py+++ b/tests/tools/test_completed_process_results.py@@ -15,6 +15,29 @@ import timeREPO_ROOT = Path(__file__).resolve().parents[2]+def _completion_notes(home):+ """Background-process completions the owner wrote into its sessions as notes."""+ import sqlite3+ if not (home / "state.db").exists():+ return []+ with sqlite3.connect(f"file:{home / 'state.db'}?mode=ro", uri=True) as db:+ return db.execute("SELECT content, display_kind FROM messages WHERE role = 'user' AND content LIKE ?",+ ("[IMPORTANT: Background process %",)).fetchall()+++def _process_receipts(home):+ return list((home / "logs" / "process-results").glob("*.json"))+++def _cli_closed(home):+ """The gateway processed the one-shot CLI's exit: its ``session.detach`` stamped the idle row."""+ import sqlite3+ if not (home / "state.db").exists():+ return False+ with sqlite3.connect(f"file:{home / 'state.db'}?mode=ro", uri=True) as db:+ return db.execute("SELECT 1 FROM sessions WHERE end_reason = 'cli_close'").fetchone() is not None++def _new_background_notifications(messages, seen_counts):"""Count new history occurrences, not positions shifted by request assembly."""counts = Counter(@@ -72,7 +95,7 @@ def test_headless_terminal_result_survives_cli_exit(tmp_path, request):child = tmp_path / "review.py"child.write_text(textwrap.dedent('''import pathlib, sys, time- deadline = time.monotonic() + 15+ deadline = time.monotonic() + 90while not pathlib.Path(sys.argv[1]).exists():if time.monotonic() > deadline:sys.exit(91)@@ -87,7 +110,6 @@ def test_headless_terminal_result_survives_cli_exit(tmp_path, request):seen_tool = set()seen_follow_up_counts = Counter()follow_ups = []- completed_during_provider_reply = threading.Event()class Provider(http.server.BaseHTTPRequestHandler):def do_GET(self):@@ -119,15 +141,6 @@ def test_headless_terminal_result_survives_cli_exit(tmp_path, request):if key not in seen_tool:seen_tool.add(key)observed.append(json.loads(m["content"]))- release.touch()- # Hold the tool-result response until the real child has exited: on a- # loaded runner completion can race this provider request.- deadline = time.monotonic() + 25- receipt = home / "logs" / "process-results" / f"{observed[0]['session_id']}.json"- while not receipt.is_file() and time.monotonic() < deadline:- time.sleep(0.01)- if receipt.is_file():- completed_during_provider_reply.set()response = {"id": "chatcmpl-local", "object": "chat.completion", "created": 1,"model": "test-model", "choices": [{@@ -177,10 +190,19 @@ def test_headless_terminal_result_survives_cli_exit(tmp_path, request):], cwd=tmp_path, env=env, stdin=subprocess.DEVNULL,capture_output=True, text=True, encoding="utf-8", timeout=60, check=False)# The canonical CLI is a finite client: it exits on its turn's terminal event while- # the daemon that owns the child keeps its watcher. The owned completion is admitted- # there as a follow-up turn, so the model must stay reachable until it arrives.+ # the daemon that owns the child keeps its watcher. The child finishes only once the+ # gateway has processed the CLI's exit (its detach stamps the idle row ``cli_close``),+ # so the completion arrives with no viewer: it is written into the session as a note,+ # never an unattended follow-up turn (#134889 LC-7). The model stays reachable so a+ # wrong turn would be seen.+ exited_before_completion = not _process_receipts(home)deadline = time.monotonic() + 30- while not follow_ups and time.monotonic() < deadline:+ while not _cli_closed(home) and time.monotonic() < deadline:+ time.sleep(0.05)+ detached = _cli_closed(home)+ release.touch()+ deadline = time.monotonic() + 60+ while not _completion_notes(home) and time.monotonic() < deadline:time.sleep(0.1)finally:release.touch()@@ -188,18 +210,19 @@ def test_headless_terminal_result_survives_cli_exit(tmp_path, request):server.server_close()thread.join(timeout=5)assert producer.returncode == 0, producer.stdout + producer.stderr- assert completed_during_provider_reply.is_set(), producer.stdout + producer.stderr+ assert exited_before_completion and detached, producer.stdout + producer.stderrassert "Coordinator finished." in producer.stdoutassert len(observed) == 1, (observed, producer.stdout, producer.stderr)process_id = observed[0]["session_id"]assert observed[0].get("notify_on_complete") is True, observed- # The owned notify_on_complete completion resumes as ONE follow-up turn on the owning- # daemon session, carrying the child's real output and exit code to the model. It is an- # [IMPORTANT: Background process ...] event, not an [ASYNC DELEGATION ...] event, and the- # same history entry can appear in several provider requests without being delivered twice.- assert len(follow_ups) == 1, follow_ups- assert follow_ups[0].startswith(f"[IMPORTANT: Background process {process_id} exited (exit code 7).")- assert "SYNTHETIC_REVIEW_COMPLETE" in follow_ups[0]+ # The owned notify_on_complete completion is ONE note on the owning daemon session, carrying+ # the child's real output and exit code for the next turn. It is an [IMPORTANT: Background+ # process ...] event, not an [ASYNC DELEGATION ...] event, and no turn ran for it.+ assert follow_ups == [], follow_ups+ notes = _completion_notes(home)+ assert len(notes) == 1, notes+ assert notes[0][0].startswith(f"[IMPORTANT: Background process {process_id} exited (exit code 7).")+ assert "SYNTHETIC_REVIEW_COMPLETE" in notes[0][0] and notes[0][1] == "process_complete"consumer = textwrap.dedent('''import json, sysdiff --git a/tools/async_delegation.py b/tools/async_delegation.pyindex 7852e07a43d..ccb6c285642 100644--- a/tools/async_delegation.py+++ b/tools/async_delegation.py@@ -38,6 +38,9 @@ _executor_max_workers: int = 0_records_lock = threading.Lock()# delegation_id -> record dict; kept for the run plus a short completed tail._records: dict[str, dict[str, Any]] = {}+# A closed session's token -> the (field, value) selectors a new dispatch is refused for (``refuse_for_session``).+_refused: dict[Any, frozenset] = {}+_FENCED_FIELDS = ("session_key", "parent_session_id")_DEFAULT_MAX_ASYNC_CHILDREN = 3# Completed records retained (in memory and in the ledger) for status queries.@@ -842,6 +845,8 @@ def _dispatch_admitted(# Stale-monitor bookkeeping (see _stale_monitor_loop)."_progress_token": None, "_progress_ts": dispatched_at, "_interrupted_at": None}with _records_lock:+ if any((field, record[field]) in fence for fence in _refused.values() for field in _FENCED_FIELDS):+ return {"status": "rejected", "error": "This session was closed (exit or /new): no new background work."}active_slots = {r.get("slot_key") or r["delegation_id"] for r in _records.values() if r.get("status") in _ACTIVE_STATES}if record["slot_key"] not in active_slots and len(active_slots) >= max_async_children:return {"status": "rejected", "error": capacity_error}@@ -1282,6 +1287,20 @@ def interrupt_for_session(targets, "interrupt_for_session", reason, "Interrupted %d async delegation(s) for ending session (%s)")+def refuse_for_session(token: Any, *, session_key: str = "", parent_session_ids=()) -> None:+ """Refuse new dispatches for ONE closing session (any selector matches) until ``allow_for_session``.+ Set before ``interrupt_for_session``: a dispatch registered first is interrupted, a later one refused."""+ fence = {("session_key", session_key)} if session_key else set()+ fence.update(("parent_session_id", parent) for parent in parent_session_ids if parent)+ with _records_lock:+ _refused[token] = frozenset(fence)+++def allow_for_session(token: Any) -> None:+ with _records_lock:+ _refused.pop(token, None)++def _reset_for_tests() -> None:"""Test-only: clear all state and tear down the executor + monitor."""global _executor, _executor_max_workers, _monitor_thread@@ -1297,6 +1316,7 @@ def _reset_for_tests() -> None:thread.join(timeout=2)with _records_lock:_records.clear()+ _refused.clear()with _orphan_lock:_offered.clear()_startup_replayed.clear()