Skip to content

The agent that grows with you

fix(gateway): read an untyped recovery note as a timeline event

Brooklyn Nicholson7ab55679534b
diff --git a/tests/test_tui_gateway_server.py b/tests/test_tui_gateway_server.py
index 7ba25acc55c..1425e6dd75e 100644
--- a/tests/test_tui_gateway_server.py
+++ b/tests/test_tui_gateway_server.py
@@ -1753,6 +1753,29 @@ def test_history_to_messages_drops_display_hidden_scaffolding():
assert all("api_content" not in m for m in projected)
+def test_history_to_messages_types_a_legacy_auto_continue_row():
+ # A crash-interrupted turn used to be typed only AFTER it finished, so a
+ # turn killed a second time (or any row written before turn-start typing
+ # landed) sits in the DB untyped and painted the raw recovery note as a
+ # user bubble. The projection recognizes the synthetic note's fixed
+ # prefix so those rows still read as a timeline event.
+ history = [
+ {"role": "user", "content": "keep going"},
+ {"role": "user", "content": server._auto_continue_note("keep going")},
+ ]
+
+ projected = server._history_to_messages(history)
+
+ assert projected == [
+ {"role": "user", "text": "keep going"},
+ {
+ "role": "user",
+ "text": server._auto_continue_note("keep going"),
+ "display_kind": "auto_continue",
+ },
+ ]
+
+
def test_history_to_messages_keeps_real_user_bracket_text():
# Only role=user rows whose text OPENS with the [System: marker sentinel are
# bookkeeping notices. A genuine user turn that merely mentions the token is
diff --git a/tests/tui_gateway/test_auto_continue.py b/tests/tui_gateway/test_auto_continue.py
index 28a70e3e420..09641b70a1e 100644
--- a/tests/tui_gateway/test_auto_continue.py
+++ b/tests/tui_gateway/test_auto_continue.py
@@ -245,6 +245,62 @@ def test_continuation_turn_records_attempt_and_original_prompt(
assert "_auto_continue_prompt" not in session
+def test_continuation_is_typed_at_turn_start(emits, turn_env, marker_home):
+ """The recovery note's row must be typed BEFORE the turn runs.
+
+ Typing it after run_conversation returns leaves the row a raw user bubble
+ for the whole turn — and permanently if the continuation is itself killed,
+ which is exactly the scenario it exists for. The model still receives the
+ note as an ordinary user message.
+ """
+ seen: list = []
+
+ def _run(message, *, persist_user_display_kind=None, **kwargs):
+ seen.append((message, persist_user_display_kind))
+ return {"final_response": "done"}
+
+ agent = types.SimpleNamespace(
+ session_id="session-key", run_conversation=_run, clear_interrupt=lambda: None
+ )
+ note = server._auto_continue_note("the original prompt")
+
+ server._run_prompt_submit(
+ "rid", "sid", _session(agent=agent, running=True), note,
+ display_kind="auto_continue",
+ )
+
+ assert seen == [(note, "auto_continue")]
+
+
+def test_older_agent_still_gets_the_post_turn_stamp(emits, turn_env, marker_home):
+ """An agent whose run_conversation predates turn-start typing keeps the
+ original behavior — the row is typed once the turn concludes."""
+ stamped: list = []
+
+ class _LegacyDB:
+ def set_latest_matching_message_display_kind(self, session_id, **kwargs):
+ stamped.append((session_id, kwargs["display_kind"]))
+ return True
+
+ def _run(message, conversation_history=None, stream_callback=None, **_kwargs):
+ return {"final_response": "done"}
+
+ agent = types.SimpleNamespace(
+ session_id="session-key",
+ run_conversation=_run,
+ clear_interrupt=lambda: None,
+ _session_db=_LegacyDB(),
+ )
+ note = server._auto_continue_note("the original prompt")
+
+ server._run_prompt_submit(
+ "rid", "sid", _session(agent=agent, running=True), note,
+ display_kind="auto_continue",
+ )
+
+ assert stamped == [("session-key", "auto_continue")]
+
+
# ── Scheduling decision ────────────────────────────────────────────────
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index 14228035c43..f6f7241da89 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -6237,6 +6237,28 @@ def _is_display_hidden_marker(role: str | None, text: str) -> bool:
return role == "user" and text.lstrip().startswith("[System:")
+# Opening of the crash-recovery note synthesized by _auto_continue_note.
+# Matched (not just built) so a row persisted before the display type was
+# stamped at turn start still reads as a timeline event, and to recognize the
+# messaging gateway's twin note.
+_AUTO_CONTINUE_NOTE_PREFIX = "[System note: Your previous turn was interrupted mid-run"
+
+
+def _legacy_display_kind(role: str, text: str) -> str | None:
+ """Infer the display type of a synthetic row persisted without one.
+
+ Turn-start typing (see ``persist_user_display_kind``) covers everything
+ written from here on. Sessions already on disk carry untyped rows — and a
+ turn killed mid-run never reached the post-turn stamp at all, which is
+ exactly the auto-continue case — so the raw recovery note would paint as a
+ user bubble forever. Sniffing the one fixed synthetic prefix is the
+ migration for those rows; it is not how new rows get typed.
+ """
+ if role == "user" and text.lstrip().startswith(_AUTO_CONTINUE_NOTE_PREFIX):
+ return "auto_continue"
+ return None
+
+
def _history_to_messages(history: list[dict]) -> list[dict]:
messages = []
tool_call_args = {}
@@ -6304,8 +6326,9 @@ def _history_to_messages(history: list[dict]) -> list[dict]:
# Forward display-only timeline metadata so the TUI can render
# model switches and delegation completions as events instead of
# opaque user messages, and hide compaction handoffs entirely.
- if m.get("display_kind"):
- msg["display_kind"] = m["display_kind"]
+ display_kind = m.get("display_kind") or _legacy_display_kind(role, content_text)
+ if display_kind:
+ msg["display_kind"] = display_kind
if m.get("display_metadata"):
msg["display_metadata"] = m["display_metadata"]
messages.append(msg)
@@ -6515,10 +6538,10 @@ def _auto_continue_note(prompt: str) -> str:
# crash persists nothing of the interrupted turn to the session DB — this
# note is the only copy the model will see.
return (
- "[System note: Your previous turn was interrupted mid-run — the app or "
- "its backend process stopped before the turn could finish. Some of the "
- "work may already be complete; check the current state before redoing "
- "anything, then finish the task. The interrupted request was:]\n\n"
+ f"{_AUTO_CONTINUE_NOTE_PREFIX} — the app or its backend process "
+ "stopped before the turn could finish. Some of the work may already "
+ "be complete; check the current state before redoing anything, then "
+ "finish the task. The interrupted request was:]\n\n"
f"{prompt}"
)
@@ -11902,11 +11925,21 @@ def _run_prompt_submit(
_build_persist_user_message(prompt, images, run_message) if images else prompt
),
}
+ # Type a synthesized turn at turn START so the crash persist writes
+ # its row as a timeline event, instead of leaving a raw user bubble
+ # until the turn ends — and forever if it never does, which is
+ # exactly the auto-continue case. The post-turn stamp below is the
+ # fallback for an older agent without the parameter; re-stamping
+ # the same value is a no-op.
try:
- if "task_id" in inspect.signature(agent.run_conversation).parameters:
- run_kwargs["task_id"] = session["session_key"]
+ _run_params = inspect.signature(agent.run_conversation).parameters
except (TypeError, ValueError):
- pass
+ _run_params = {}
+ if "task_id" in _run_params:
+ run_kwargs["task_id"] = session["session_key"]
+ if display_kind and "persist_user_display_kind" in _run_params:
+ run_kwargs["persist_user_display_kind"] = display_kind
+ run_kwargs["persist_user_display_metadata"] = display_metadata
result = agent.run_conversation(run_message, **run_kwargs)
if display_kind and isinstance(text, str):
db = getattr(agent, "_session_db", None)