Skip to content

The agent that grows with you

fix(gateway): retain pre-admission interrupted input

Ayush Nangia24ae31f7e7af
diff --git a/agent/session_persistence.py b/agent/session_persistence.py
index 7a5977acce7..5af23d1aa36 100644
--- a/agent/session_persistence.py
+++ b/agent/session_persistence.py
@@ -40,6 +40,7 @@ _EPHEMERAL_SCAFFOLDING_FLAGS = (
_IMAGE_PART_TYPES = {"image", "image_url", "input_image"}
# Reasoning/codex fields are role-gated (assistant-only) inside _insert_message_rows.
_ROW_REASONING_KEYS = ("reasoning", "reasoning_content", "reasoning_details", "codex_reasoning_items", "codex_message_items")
+_PERSIST_AFTER_ADMISSION_INTERRUPT = "_persist_after_admission_interrupt"
def _is_ephemeral_scaffolding(msg: Any) -> bool:
@@ -201,7 +202,9 @@ def _db_flush_collect(agent, messages: List[Dict], conversation_history: Optiona
if not isinstance(msg, dict) or _is_ephemeral_scaffolding(msg) or msg.get(_DB_PERSISTED_MARKER):
continue
# Already durable (history copy or caller-seeded): stamp so future flushes skip it.
- if id(msg) in history_ids or id(msg) in seed_ids:
+ if (
+ id(msg) in history_ids or id(msg) in seed_ids
+ ) and not msg.get(_PERSIST_AFTER_ADMISSION_INTERRUPT):
msg[_DB_PERSISTED_MARKER] = True
continue
batch_rows.append(_db_flush_row(agent, msg, ov_idx == msg_idx or msg is pending_cli_message))
diff --git a/agent/turn_context.py b/agent/turn_context.py
index 27fe703a9b8..b4b75662721 100644
--- a/agent/turn_context.py
+++ b/agent/turn_context.py
@@ -966,6 +966,17 @@ def build_turn_context(
_ensure_session_row(agent, pending_cli_message)
+ # A turn interrupted before admission could not write its accepted input because
+ # it did not own the session lease. Persist that carried-forward row now, before
+ # compaction can rewrite or drop it.
+ from agent.session_persistence import _PERSIST_AFTER_ADMISSION_INTERRUPT
+
+ if conversation_history and any(
+ isinstance(msg, dict) and msg.get(_PERSIST_AFTER_ADMISSION_INTERRUPT)
+ for msg in conversation_history
+ ):
+ agent._flush_messages_to_session_db(conversation_history, conversation_history)
+
compaction = run_turn_start_compaction(
agent, messages=messages, system_message=system_message,
active_system_prompt=active_system_prompt, conversation_history=conversation_history,
diff --git a/agent/turn_facade.py b/agent/turn_facade.py
index 5eb2b500d8a..7b6fccbabde 100644
--- a/agent/turn_facade.py
+++ b/agent/turn_facade.py
@@ -82,6 +82,45 @@ class TurnFacadeMixin:
conversation_history=conversation_history,
)
if admission.early_result is not None:
+ hard_interrupted = bool(
+ admission.early_result.pop("_hard_interrupted", False)
+ )
+ if (
+ admission.early_result.get("interrupted")
+ and not hard_interrupted
+ and user_message is not None
+ and user_message != ""
+ ):
+ from agent.message_metadata import append_message
+ from agent.session_persistence import _PERSIST_AFTER_ADMISSION_INTERRUPT
+
+ durable_content = user_message
+ if persist_user_message is not None and (
+ not isinstance(user_message, list)
+ or isinstance(persist_user_message, list)
+ ):
+ durable_content = persist_user_message
+ deferred_user = {
+ "role": "user",
+ "content": durable_content,
+ _PERSIST_AFTER_ADMISSION_INTERRUPT: True,
+ }
+ if (
+ isinstance(user_message, str)
+ and user_message != durable_content
+ ):
+ deferred_user["api_content"] = user_message
+ if persist_user_display_kind:
+ deferred_user["display_kind"] = persist_user_display_kind
+ if persist_user_display_metadata:
+ deferred_user["display_metadata"] = persist_user_display_metadata
+ if persist_user_platform_id is not None:
+ deferred_user["platform_message_id"] = persist_user_platform_id
+ append_message(
+ admission.early_result["messages"],
+ deferred_user,
+ timestamp=persist_user_timestamp,
+ )
relay_outcome = (
"cancelled" if admission.early_result.get("interrupted") else "timed_out"
)
diff --git a/agent/turn_facade_lease.py b/agent/turn_facade_lease.py
index d15727d8885..23b1ab617bd 100644
--- a/agent/turn_facade_lease.py
+++ b/agent/turn_facade_lease.py
@@ -306,6 +306,10 @@ def _lease_not_acquired_result(agent, session_id: str, conversation_history) ->
base = {"messages": list(conversation_history or []), "api_calls": 0, "completed": False}
if getattr(agent, "_interrupt_requested", False):
logger.info("session turn lease wait aborted by interrupt: %s", session_id)
+ hard_event = getattr(agent, "_hard_interrupt_requested", None)
+ hard_interrupted = bool(
+ callable(getattr(hard_event, "is_set", None)) and hard_event.is_set()
+ )
result = {
"final_response": (
"Stopped waiting for another Hermes process on this session. "
@@ -314,6 +318,8 @@ def _lease_not_acquired_result(agent, session_id: str, conversation_history) ->
**base,
"interrupted": True,
}
+ if hard_interrupted:
+ result["_hard_interrupted"] = True
if getattr(agent, "_interrupt_message", None):
result["interrupt_message"] = agent._interrupt_message
# The finalizer never runs on this early return; clear so a cached agent doesn't
diff --git a/tests/agent/test_cross_process_turn_lease.py b/tests/agent/test_cross_process_turn_lease.py
index a248dc31901..d6c7c798646 100644
--- a/tests/agent/test_cross_process_turn_lease.py
+++ b/tests/agent/test_cross_process_turn_lease.py
@@ -6,6 +6,7 @@ import sqlite3
import threading
import time
from types import SimpleNamespace
+from unittest.mock import MagicMock
from agent import relay_runtime
from hermes_state import SessionDB
@@ -252,8 +253,13 @@ def test_run_conversation_lease_wait_honors_interrupt(monkeypatch):
monkeypatch.setattr("agent.conversation_loop.run_conversation", boom)
result = AIAgent.run_conversation(
agent,
- "new message",
+ "[Monday 12:00] new message",
conversation_history=[{"role": "user", "content": "stale"}],
+ persist_user_message="new message",
+ persist_user_timestamp=123.0,
+ persist_user_display_kind="internal_notification",
+ persist_user_display_metadata={"kind": "test"},
+ persist_user_platform_id="platform-1",
)
assert result.get("interrupted") is True
@@ -261,12 +267,86 @@ def test_run_conversation_lease_wait_honors_interrupt(monkeypatch):
assert result.get("final_response")
assert "not processed" in result["final_response"]
assert result.get("interrupt_message") == "follow-up while waiting"
+ assert result["messages"][-1] == {
+ "role": "user",
+ "content": "new message",
+ "api_content": "[Monday 12:00] new message",
+ "timestamp": 123.0,
+ "display_kind": "internal_notification",
+ "display_metadata": {"kind": "test"},
+ "platform_message_id": "platform-1",
+ "_persist_after_admission_interrupt": True,
+ }
assert "session_turn_lease_timeout" not in str(result.get("error", ""))
assert [event[0] for event in db.events] == ["acquire"]
assert agent._interrupt_requested is False
assert agent._interrupt_message is None
+def test_pre_admission_hard_stop_does_not_requeue_original(monkeypatch):
+ db = _DB()
+ agent = _agent_with_db(db)
+ agent._hard_interrupt_requested = threading.Event()
+
+ def acquire_with_hard_stop(session_id, holder, **kwargs):
+ db.events.append(("acquire", session_id, holder))
+ agent._interrupt_requested = True
+ agent._interrupt_message = "Stop requested"
+ agent._hard_interrupt_requested.set()
+ assert kwargs["should_abort"]()
+ return False
+
+ db.acquire_session_turn_lease = acquire_with_hard_stop
+ monkeypatch.setattr(
+ "agent.conversation_loop.run_conversation",
+ lambda *_args, **_kwargs: (_ for _ in ()).throw(
+ AssertionError("hard-stopped turn must not start")
+ ),
+ )
+
+ history = [{"role": "user", "content": "stale"}]
+ result = AIAgent.run_conversation(agent, "cancel me", conversation_history=history)
+
+ assert result["interrupted"] is True
+ assert result["messages"] == history
+
+
+def test_pre_admission_user_row_in_history_is_flushed_once():
+ db = MagicMock()
+ db.append_messages_batch.return_value = [1, 2]
+ agent = AIAgent.__new__(AIAgent)
+ agent._session_db = db
+ agent._session_db_created = True
+ agent._persist_disabled = False
+ agent._persist_user_message_idx = 2
+ agent._persist_user_message_override = None
+ agent._persist_user_message_timestamp = None
+ agent._persist_user_message_platform_id = None
+ agent._flushed_db_message_ids = set()
+ agent._last_flushed_db_idx = 0
+ agent.session_id = "session"
+
+ persisted = {"role": "assistant", "content": "old reply"}
+ interrupted = {
+ "role": "user",
+ "content": "original",
+ "_persist_after_admission_interrupt": True,
+ }
+ current = {"role": "user", "content": "follow-up"}
+ history = [persisted, interrupted]
+ messages = [*history, current]
+
+ agent._flush_messages_to_session_db(messages, conversation_history=history)
+ agent._flush_messages_to_session_db(messages, conversation_history=history)
+
+ rows = db.append_messages_batch.call_args.kwargs["messages"]
+ assert [(row["role"], row["content"]) for row in rows] == [
+ ("user", "original"),
+ ("user", "follow-up"),
+ ]
+ assert db.append_messages_batch.call_count == 1
+
+
def test_run_conversation_second_turn_after_lease_wait_abort(monkeypatch):
db = _DB()
agent = _agent_with_db(db)
diff --git a/tests/agent/test_turn_context.py b/tests/agent/test_turn_context.py
index a08d6665e2b..bcd882066c7 100644
--- a/tests/agent/test_turn_context.py
+++ b/tests/agent/test_turn_context.py
@@ -260,6 +260,24 @@ def test_user_message_preserves_platform_event_timestamp():
assert ctx.messages[-1]["timestamp"] == 123.5
+def test_interrupted_admission_input_is_flushed_before_turn_compaction():
+ agent = _FakeAgent()
+ agent._flush_messages_to_session_db = MagicMock()
+ deferred = {
+ "role": "user",
+ "content": "original",
+ "_persist_after_admission_interrupt": True,
+ }
+ history = [{"role": "assistant", "content": "old reply"}, deferred]
+
+ _build(agent, conversation_history=history, user_message="follow-up")
+
+ agent._flush_messages_to_session_db.assert_called_once()
+ flushed, known_history = agent._flush_messages_to_session_db.call_args.args
+ assert flushed == history
+ assert known_history is history
+
+
# ── Trivial-prompt prefetch gate (PR #25350 salvage) ─────────────────────────
#
# The prologue is the ONLY place the per-turn synchronous