The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(sessions): surface wait status for cross-process turn leases
fangliquan3b0945601955
diff --git a/hermes_state.py b/hermes_state.pyindex 8b33c6cdd06..f8a5ce79bcd 100644--- a/hermes_state.py+++ b/hermes_state.py@@ -5819,17 +5819,44 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)ttl_seconds: float = 300.0,wait_seconds: float = 1800.0,poll_interval_seconds: float = 0.1,+ on_wait=None,+ wait_notice_interval_seconds: float = 15.0,) -> bool:- """Wait for a cross-process turn lease without holding a SQLite lock."""+ """Wait for a cross-process turn lease without holding a SQLite lock.++ ``on_wait(elapsed_seconds)`` is best-effort: invoked when the first+ attempt fails (elapsed ~0) and again about every+ ``wait_notice_interval_seconds`` while still waiting, so UIs can show+ that another process holds the conversation.+ """deadline = time.monotonic() + max(0.0, float(wait_seconds))+ wait_started = None+ last_notice_at = None+ notice_every = max(0.0, float(wait_notice_interval_seconds))while True:if self.try_acquire_session_turn_lease(session_id, holder, ttl_seconds=ttl_seconds):return True- remaining = deadline - time.monotonic()+ now = time.monotonic()+ remaining = deadline - nowif remaining <= 0:return False+ if wait_started is None:+ wait_started = now+ if on_wait is not None and (+ last_notice_at is None+ or notice_every == 0.0+ or (now - last_notice_at) >= notice_every+ ):+ try:+ on_wait(max(0.0, now - wait_started))+ except Exception:+ logger.debug(+ "session turn lease on_wait callback failed",+ exc_info=True,+ )+ last_notice_at = nowtime.sleep(min(max(0.01, float(poll_interval_seconds)), remaining))def refresh_session_turn_lease(diff --git a/run_agent.py b/run_agent.pyindex 46bf45f3bf3..7b84b50f65d 100644--- a/run_agent.py+++ b/run_agent.py@@ -8111,19 +8111,69 @@ class AIAgent:# prologue. We just proved this row exists, so suppress the# redundant create attempt after acquiring it.self._session_db_created = True- durable_turn_lease = (+ _durable_holder = (f"pid={os.getpid()}:turn={relay_turn_id}:platform="f"{task_context['platform'] or 'unknown'}")_lease_ttl = 300.0+ _lease_waited = False++ def _on_session_turn_lease_wait(elapsed: float) -> None:+ nonlocal _lease_waited+ _lease_waited = True+ if elapsed < 1.0:+ self._emit_status(+ "⏳ Another Hermes process is using this session; "+ "waiting for it to finish before starting your turn..."+ )+ else:+ self._emit_status(+ "⏳ Still waiting for the other Hermes process on "+ f"this session ({int(elapsed)}s)..."+ )+if not _turn_db.acquire_session_turn_lease(session_id,- durable_turn_lease,+ _durable_holder,ttl_seconds=_lease_ttl,wait_seconds=1800.0,+ on_wait=_on_session_turn_lease_wait,):- raise TimeoutError(- f"session turn lease wait timed out for {session_id}"+ # Fail closed like gateway TurnLeaseTimeoutError: do not+ # enter load/run/flush, and surface a resend notice instead+ # of a bare TimeoutError that looks like a hang.+ timeout_msg = (+ "⏳ Another Hermes process kept this session busy too "+ "long. Your message was not processed - wait for the "+ "other process to finish, then send it again."+ )+ logger.error(+ "session turn lease wait timed out for %s",+ session_id,+ )+ try:+ self._emit_warning(timeout_msg)+ except Exception:+ logger.debug(+ "Failed to emit session turn lease timeout warning",+ exc_info=True,+ )+ relay_outcome = "timed_out"+ return {+ "final_response": timeout_msg,+ "messages": list(conversation_history or []),+ "api_calls": 0,+ "completed": False,+ "failed": True,+ "error": f"session_turn_lease_timeout:{session_id}",+ }++ # Assign only after admission so finally release cannot target a+ # holder string that never owned the row.+ durable_turn_lease = _durable_holder+ if _lease_waited:+ self._emit_status(+ "Session is free; loading the latest transcript...")# The holder may have compressed and rotated the session whilediff --git a/tests/run_agent/test_cross_process_turn_lease.py b/tests/run_agent/test_cross_process_turn_lease.pyindex 1296f6d2a18..ce92c7d3883 100644--- a/tests/run_agent/test_cross_process_turn_lease.py+++ b/tests/run_agent/test_cross_process_turn_lease.py@@ -6,16 +6,20 @@ from run_agent import AIAgentclass _DB:- def __init__(self, session_exists=True):+ def __init__(self, session_exists=True, acquire_result=True):self.events = []self.session_exists = session_exists+ self.acquire_result = acquire_resultdef get_session(self, session_id):return {"id": session_id} if self.session_exists else Nonedef acquire_session_turn_lease(self, session_id, holder, **kwargs):self.events.append(("acquire", session_id, holder))- return True+ on_wait = kwargs.get("on_wait")+ if on_wait is not None and self.acquire_result is False:+ on_wait(0.0)+ return self.acquire_resultdef resolve_resume_session_id(self, session_id):self.events.append(("resolve", session_id))@@ -32,11 +36,10 @@ class _DB:self.events.append(("release", session_id, holder))-def test_run_conversation_acquires_then_reloads_latest_tip(monkeypatch):- db = _DB()+def _agent_with_db(db, *, session_id="stale-parent", platform="desktop"):agent = AIAgent.__new__(AIAgent)- agent.session_id = "stale-parent"- agent.platform = "desktop"+ agent.session_id = session_id+ agent.platform = platformagent.model = "test-model"agent._session_db = dbagent._session_db_created = True@@ -44,7 +47,20 @@ def test_run_conversation_acquires_then_reloads_latest_tip(monkeypatch):agent._parent_session_id = Noneagent._relay_pending_turn_id = Noneagent._reset_activity_labels_after_turn = lambda: None- agent._conversation_root_id = lambda: "stale-parent"+ agent._conversation_root_id = lambda: session_id+ agent.log_prefix = ""+ agent._vprint = lambda *a, **k: None+ agent.status_callback = None+ return agent+++def test_run_conversation_acquires_then_reloads_latest_tip(monkeypatch):+ db = _DB()+ agent = _agent_with_db(db)+ status_events = []+ agent.status_callback = lambda kind, text=None: status_events.append(+ (kind, text)+ )observed = {}@@ -53,6 +69,16 @@ def test_run_conversation_acquires_then_reloads_latest_tip(monkeypatch):observed["session_id"] = _agent.session_idreturn {"final_response": "ok", "messages": history, "failed": False}+ # Simulate a contended wait so the resume status path is covered.+ def acquire_with_wait(session_id, holder, **kwargs):+ db.events.append(("acquire", session_id, holder))+ on_wait = kwargs.get("on_wait")+ if on_wait is not None:+ on_wait(0.0)+ return True++ db.acquire_session_turn_lease = acquire_with_wait+monkeypatch.setattr("agent.conversation_loop.run_conversation", fake_run)result = AIAgent.run_conversation(agent,@@ -71,20 +97,25 @@ def test_run_conversation_acquires_then_reloads_latest_tip(monkeypatch):"reload","release",]+ assert any(+ kind == "lifecycle"+ and text+ and "waiting for it to finish" in text+ for kind, text in status_events+ )+ assert any(+ kind == "lifecycle"+ and text+ and "loading the latest transcript" in text+ for kind, text in status_events+ )def test_fresh_session_keeps_caller_seed_without_durable_lease(monkeypatch):db = _DB(session_exists=False)- agent = AIAgent.__new__(AIAgent)- agent.session_id = "fresh"- agent.platform = "subagent"- agent.model = "test-model"- agent._session_db = db+ agent = _agent_with_db(db, session_id="fresh", platform="subagent")agent._session_db_created = False- agent._persist_disabled = Falseagent._parent_session_id = "parent"- agent._relay_pending_turn_id = None- agent._reset_activity_labels_after_turn = lambda: Noneagent._conversation_root_id = lambda: "parent"observed = {}@@ -99,4 +130,39 @@ def test_fresh_session_keeps_caller_seed_without_durable_lease(monkeypatch):AIAgent.run_conversation(agent, "work", conversation_history=seed)assert observed["history"] is seed- assert db.events == []\ No newline at end of file+ assert db.events == []+++def test_run_conversation_lease_timeout_returns_resend_notice(monkeypatch):+ db = _DB(acquire_result=False)+ agent = _agent_with_db(db)+ status_events = []+ agent.status_callback = lambda kind, text=None: status_events.append(+ (kind, text)+ )++ def boom(*_args, **_kwargs):+ raise AssertionError("turn must not start without a lease")++ monkeypatch.setattr("agent.conversation_loop.run_conversation", boom)+ result = AIAgent.run_conversation(+ agent,+ "new message",+ conversation_history=[{"role": "user", "content": "stale"}],+ )++ assert result["failed"] is True+ assert result["completed"] is False+ assert "session_turn_lease_timeout:" in result["error"]+ assert "send it again" in result["final_response"]+ assert [event[0] for event in db.events] == ["acquire"]+ assert any(+ kind == "lifecycle"+ and text+ and "waiting for it to finish" in text+ for kind, text in status_events+ )+ assert any(+ kind == "warn" and text and "send it again" in text+ for kind, text in status_events+ )diff --git a/tests/state/test_session_turn_lease.py b/tests/state/test_session_turn_lease.pyindex b177576fa58..5ed88ef7c4e 100644--- a/tests/state/test_session_turn_lease.py+++ b/tests/state/test_session_turn_lease.py@@ -125,4 +125,43 @@ def test_expired_turn_lease_is_reclaimed(tmp_path):assert db.try_acquire_session_turn_lease("shared", "pid=202:turn=reclaimer", ttl_seconds=5- )\ No newline at end of file+ )+++def test_acquire_turn_lease_notifies_wait_callback(tmp_path):+ """Waiters get a progress callback while another holder owns the lease."""+ path = tmp_path / "state.db"+ first = SessionDB(path)+ second = SessionDB(path)+ first.create_session("shared", source="test")++ first_holder = f"pid={os.getpid()}:turn=first"+ second_holder = f"pid={os.getpid()}:turn=second"+ assert first.try_acquire_session_turn_lease(+ "shared", first_holder, ttl_seconds=5+ )++ notices = []++ def release_first():+ time.sleep(0.12)+ first.release_session_turn_lease("shared", first_holder)++ thread = threading.Thread(target=release_first, daemon=True)+ thread.start()+ try:+ assert second.acquire_session_turn_lease(+ "shared",+ second_holder,+ ttl_seconds=5,+ wait_seconds=2,+ poll_interval_seconds=0.02,+ on_wait=notices.append,+ wait_notice_interval_seconds=0.05,+ )+ finally:+ thread.join(timeout=2)++ assert notices+ assert notices[0] < 0.05+ second.release_session_turn_lease("shared", second_holder)\ No newline at end of file