The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a cold /refine review is the session's, so a turn cancels it
Teknium1fdf37e3d154
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 938a696ac67..6ce6bc9a6e0 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -11,6 +11,7 @@ from contextvars import ContextVarfrom dataclasses import asdict, dataclass, fieldfrom functools import partialimport sqlite3+from types import SimpleNamespaceimport uuidfrom gateway.session_contract import (@@ -79,6 +80,9 @@ class LiveSession:# Mounted by that cold path (not published by its lane): the lane publishing ANOTHER conversation# on the same route later supersedes it too.history_mount: bool = False+ # The background-review guard of a cold ``/refine`` (gateway/session_refine.py): its side agent is+ # per call, so the run token lives here; a second /refine joins it and the next turn cancels it.+ review: SimpleNamespace = field(default_factory=SimpleNamespace)def __post_init__(self):self.controls = PendingControls(self.event_stream)@@ -1113,6 +1117,12 @@ class SessionAuthority:execution returns; a lost managed worker pauses the FIFO and re-raises ManagedExecutionUnknown."""from gateway.session_finite import execute_finite_admissionfrom gateway.session_managed_worker import ManagedExecutionUnknown+ review = getattr(live.review, '_background_review_run', None)+ if review is not None and not review.request_done.is_set():+ # A cold /refine's review shares the session id, as the resident agent's does: cancel it+ # before the turn (its bounded wait runs off-loop).+ from agent.background_review import cancel_background_review_for_live_turn+ await asyncio.to_thread(cancel_background_review_for_live_turn, live.review)try:try:return await execute_finite_admission(self, ref, row), 'completed'diff --git a/gateway/session_refine.py b/gateway/session_refine.pyindex df2ffc3f7df..e2957e067ae 100644--- a/gateway/session_refine.py+++ b/gateway/session_refine.py@@ -42,7 +42,14 @@ async def refine_local_session(runner, source, focus):target, history = await asyncio.to_thread(load)if not history:return t('gateway.refine.nothing_yet')+ from agent.background_review import finish_background_review_run, prepare_background_review_runfrom gateway.session_tui_side import _side_agent, _side_scope, _spawn+ # The guard is the session's (its side agent is per call): a /refine while one runs joins it, as+ # the resident agent's does, and the session's next turn cancels it (``_execute_claimed``).+ run = prepare_background_review_run(live.review)+ tail = t('gateway.refine.focus_suffix', focus=focus) if focus else ''+ if run is None:+ return t('gateway.refine.started', focus_suffix=tail)task_id = f'refine_{uuid.uuid4().hex[:6]}'holder = [None]@@ -52,9 +59,14 @@ async def refine_local_session(runner, source, focus):current.event_stream.publish(ref.session_id, {'text': str(message)}, event_type='review.summary')def body():- from agent.background_review import (- finish_background_review_run, prepare_background_review_run, spawn_background_review_thread,- )+ try:+ review_body()+ finally: # whatever raised first, the session's guard is released+ finish_background_review_run(live.review, run)+ return '' # the summary (if any) was published above; an empty review.summary draws nothing++ def review_body():+ from agent.background_review import spawn_background_review_threadfrom agent.turn_finalizer import _clone_background_review_messageswith _side_scope(authority, policy, task_id):# The session's own id: the review's usage is recorded against it, and the agent never@@ -67,7 +79,6 @@ async def refine_local_session(runner, source, focus):agent._end_session_on_close = Falseagent.background_review_callback = publishagent._print_fn = lambda *_a, **_k: None- run = prepare_background_review_run(agent)try:review, _prompt = spawn_background_review_thread(agent, _clone_background_review_messages(history), review_memory=True,@@ -75,14 +86,12 @@ async def refine_local_session(runner, source, focus):focus=focus or None, review_run=run, explicit=True)review()finally:- finish_background_review_run(agent, run)with contextlib.suppress(Exception):agent.release_clients()- return '' # the summary (if any) was published above; an empty review.summary draws nothingtry:_spawn(authority, ref, task_id, 'review.summary', body, holder=holder)except RuntimeError as exc: # the review thread could not start+ finish_background_review_run(live.review, run)return t('gateway.refine.start_failed', error=exc)- tail = t('gateway.refine.focus_suffix', focus=focus) if focus else ''return t('gateway.refine.started', focus_suffix=tail)diff --git a/tests/gateway/test_local_refine_keeps_session_resources.py b/tests/gateway/test_local_refine_keeps_session_resources.pyindex f422c024f16..ed1a972708b 100644--- a/tests/gateway/test_local_refine_keeps_session_resources.py+++ b/tests/gateway/test_local_refine_keeps_session_resources.py@@ -36,7 +36,7 @@ async def test_cold_refine_keeps_the_sessions_terminal(tmp_path, monkeypatch):assert key == sid, keyterminal_tool._active_environments[key] = envsource = SimpleNamespace(chat_id=sid)- live = SimpleNamespace(source=source)+ live = SimpleNamespace(source=source, review=SimpleNamespace())authority = SimpleNamespace(profile_id=str(tmp_path), sessions={sid: live},db=SimpleNamespace(get_messages_as_conversation=lambda *a, **k: [{'role': 'user', 'content': 'history'}]))policy = object()diff --git a/tests/gateway/test_local_refine_review_guard.py b/tests/gateway/test_local_refine_review_guard.pynew file mode 100644index 00000000000..9c2a7eaeb19--- /dev/null+++ b/tests/gateway/test_local_refine_review_guard.py@@ -0,0 +1,107 @@+"""A cold ``/refine`` review belongs to the session, not to its throwaway side agent (T7).++The resident agent's review is fenced by one per-agent guard: a second ``/refine`` is refused while+it runs, and the session's next turn cancels it. The cold path builds a fresh side agent per call,+so its guard must live on the session (``LiveSession.review``) for both to hold. The real refine body,+review-run handshake, canceller and ``SessionAuthority._execute_claimed`` run; agent construction,+review inference and the admitted turn are stubbed.+"""+import threading+from contextlib import nullcontext+from types import SimpleNamespace++import pytest++from tests.waiting import wait_until+++def _stub_refine(monkeypatch, refine, live, sid, review):+ from gateway import session_tui_side, session_policy, session_local_recovery+ from agent import background_review+ from run_agent import AIAgent+ authority = SimpleNamespace(profile_id='p', sessions={sid: live},+ db=SimpleNamespace(get_messages_as_conversation=lambda *a, **k: [{'role': 'user', 'content': 'h'}]))+ monkeypatch.setattr(refine, '_local_session', lambda r, s: (authority, live))+ monkeypatch.setattr(session_policy, 'policy_for_source', lambda r, s: object())+ monkeypatch.setattr(session_local_recovery, 'transcript_target', lambda a, r: sid)+ monkeypatch.setattr(session_tui_side, '_side_scope', lambda *a: nullcontext())++ def side_agent(*args, **kwargs):+ agent = object.__new__(AIAgent)+ agent.session_id = kwargs.get('session_id')+ agent.valid_tool_names = set()+ return agent+ monkeypatch.setattr(session_tui_side, '_side_agent', side_agent)+ monkeypatch.setattr(background_review, 'spawn_background_review_thread',+ lambda agent, *a, review_run=None, **k: (lambda: review(agent, review_run), ''))+ monkeypatch.setattr(background_review, '_interrupt_background_review', lambda *a, **k: None)+ threads = []++ def spawn(a, r, t, e, body, **kw):+ thread = threading.Thread(target=body, daemon=True)+ threads.append(thread)+ thread.start()+ monkeypatch.setattr(session_tui_side, '_spawn', spawn)+ return threads+++async def test_second_cold_refine_while_one_runs_is_refused(monkeypatch):+ refine = pytest.importorskip('gateway.session_refine')+ from agent.background_review import finish_background_review_run+ from gateway.session_authority import LiveSession+ sid = 'refine-guard-dup'+ live = LiveSession(SimpleNamespace(chat_id=sid), 'route')+ release, started = threading.Event(), []++ def review(agent, run):+ started.append(run)+ release.wait(10)+ finish_background_review_run(agent, run)+ threads = _stub_refine(monkeypatch, refine, live, sid, review)+ try:+ first = await refine.refine_local_session(object(), live.source, None)+ wait_until(lambda: started, what='the first review started')+ second = await refine.refine_local_session(object(), live.source, None)+ finally:+ release.set()+ for thread in threads:+ thread.join(10)+ assert 'Reviewing this conversation' in first, first+ # Deduped, as the resident agent's guard does (``_spawn_background_review`` returns early).+ assert len(started) == 1, ('a second /refine started another review', second)+++async def test_new_turn_cancels_the_cold_refine_review(monkeypatch):+ refine = pytest.importorskip('gateway.session_refine')+ from agent.background_review import finish_background_review_run+ from gateway import session_finite+ from gateway.session_authority import LiveSession, SessionAuthority+ from gateway.session_contract import SessionRef+ sid = 'refine-guard-turn'+ live = LiveSession(SimpleNamespace(chat_id=sid), 'route')+ started, outcome = [], {}++ def review(agent, run):+ assert run.begin_request(agent)+ started.append(run)+ outcome['cancelled'] = run.cancel_requested.wait(5)+ finish_background_review_run(agent, run)+ threads = _stub_refine(monkeypatch, refine, live, sid, review)++ async def turn(authority, ref, row):+ outcome['turn_saw_review_done'] = started[0].request_done.is_set()+ return 'ok'+ monkeypatch.setattr(session_finite, 'execute_finite_admission', turn)+ try:+ await refine.refine_local_session(object(), live.source, None)+ wait_until(lambda: started, what='the review started')+ owner = SimpleNamespace(executing={})+ result = await SessionAuthority._execute_claimed(owner, SessionRef('p', sid), live, {'admission_id': 'a'})+ finally:+ for thread in threads:+ thread.join(10)+ assert result == ('ok', 'completed'), result+ assert outcome.get('cancelled') is True, 'the new turn left the cold /refine review running'+ assert outcome['turn_saw_review_done'], 'the turn started before the review acknowledged'diff --git a/tests/gateway/test_local_refine_skips_memory_provider.py b/tests/gateway/test_local_refine_skips_memory_provider.pyindex 4dfc06f20be..5e8a700f820 100644--- a/tests/gateway/test_local_refine_skips_memory_provider.py+++ b/tests/gateway/test_local_refine_skips_memory_provider.py@@ -36,7 +36,7 @@ async def test_cold_refine_builds_no_memory_provider(tmp_path, monkeypatch):monkeypatch.setattr(agent_init, 'is_core_memory_provider', lambda name: False)sid = 'refine-memory-parent'source = SimpleNamespace(chat_id=sid)- live = SimpleNamespace(source=source)+ live = SimpleNamespace(source=source, review=SimpleNamespace())authority = SimpleNamespace(profile_id=str(tmp_path), sessions={sid: live},db=SimpleNamespace(get_messages_as_conversation=lambda *a, **k: [{'role': 'user', 'content': 'h'}]))policy = SimpleNamespace(ignore_rules=False)