The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): keep marker-merged user rows addressable after alternation repair
liuhao1024696f6e9ff911
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex 0db6fb0c829..44df8210976 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -465,10 +465,12 @@ def _merge_assistant_into(prev: Dict, msg: Dict) -> bool:def _remember_absorbed_row(survivor: Dict[str, Any], dropped: Dict[str, Any], *, folded: bool) -> None:"""Retire *dropped*'s row ids onto *survivor*; record its uid as a merge witness only when *folded* (itstext survives). An empty incoming turn still merges; stamping an empty list would change a message that- absorbed nothing."""+ absorbed nothing. A dropped id that equals the survivor's own live id (the display-marker merge adopts+ the plain row's id, #94486) is not an absorbed row: the survivor IS that row."""+ own_id = survivor.get("_row_id")ids = []row_id = dropped.get("_row_id")- if isinstance(row_id, int) and not isinstance(row_id, bool) and row_id > 0:+ if isinstance(row_id, int) and not isinstance(row_id, bool) and row_id > 0 and row_id != own_id:ids.append(row_id)for older in dropped.get("_absorbed_row_ids") or ():if isinstance(older, int) and not isinstance(older, bool) and older > 0 and older not in ids:@@ -620,6 +622,31 @@ def _merge_consecutive_users(messages: List[Dict]) -> Tuple[List[Dict], int]:prev[MERGED_TURN_PREFIX] = prev_content# Merged content invalidates the api_content sidecar; drop it so replay cannot use stale bytes.drop_stale_api_content(prev)+ # A display-marker row (e.g. a model-switch marker persisted as role=user on+ # purpose, #48338) merging with a plain user row must not bury the plain row's+ # addressable identity: keeping the marker's display_kind hides the merged pair+ # from every user-turn index used for rewind/submit addressing (display rows are+ # excluded), so the plain row's durable id becomes unresolvable and the client's+ # next prompt.submit fails closed with the input silently dropped (#94486). Keep+ # the pair addressable instead: drop the display classification and carry the+ # plain row's id, retiring the marker's own id onto the absorbed list. display_kind+ # never reaches providers (stripped from every outgoing copy), so the merged+ # turn's wire payload is unchanged. Deliberate scope: when BOTH rows carry+ # display_kind (two consecutive model-switch markers) the pair keeps the first+ # marker's classification and id — no plain row is swallowed there, so no+ # addressable turn is lost.+ if prev.get("display_kind") and not msg.get("display_kind"):+ marker_row_id = prev.get("_row_id")+ prev.pop("display_kind", None)+ if msg.get("_row_id") is not None:+ if isinstance(marker_row_id, int) and not isinstance(marker_row_id, bool):+ absorbed_ids = prev.setdefault("_absorbed_row_ids", [])+ if marker_row_id not in absorbed_ids:+ absorbed_ids.append(marker_row_id)+ prev["_row_id"] = msg["_row_id"]+ # display_kind is part of the persisted row; reclassifying stales it even+ # when the merged bytes reproduce the persisted content (empty absorb).+ prev.pop(_DB_PERSISTED_MARKER, None)# Pop the persist marker only when the durable row actually changed: a merge that# reproduces the persisted bytes (e.g. an empty incoming turn) keeps its stamp.if merged_content != prev_content or had_api_sidecar:diff --git a/tests/agent/test_message_sequence_repair.py b/tests/agent/test_message_sequence_repair.pyindex b5692f08efe..bc73d4f7734 100644--- a/tests/agent/test_message_sequence_repair.py+++ b/tests/agent/test_message_sequence_repair.py@@ -66,6 +66,65 @@ def test_repair_preserves_user_content_when_one_side_empty():assert messages == [{"role": "user", "content": "real message"}]+def test_repair_marker_user_merge_keeps_plain_row_addressable():+ """#94486: a display-marker user row (model-switch marker, persisted as+ role=user on purpose per #48338) merging with the plain user row after it+ must keep the pair addressable — the merged row drops the display+ classification and carries the plain row's durable id, so rewind/submit+ addressing (which indexes non-display user turns) can still resolve it.+ """+ agent = _bare_agent()+ messages = [+ {"role": "assistant", "content": "reply"},+ {+ "role": "user",+ "display_kind": "model_switch",+ "_row_id": 12134,+ "content": "[System: The active model for this chat has changed to ds4.]",+ },+ {"role": "user", "_row_id": 12135, "content": "the user's real prompt"},+ ]++ repairs = AIAgent._repair_message_sequence(agent, messages)++ assert repairs == 1+ assert len(messages) == 2+ merged = messages[1]+ assert merged["role"] == "user"+ assert not merged.get("display_kind")+ assert merged["_row_id"] == 12135+ assert "the user's real prompt" in merged["content"]+ assert "[System:" in merged["content"]+++def test_repair_plain_user_then_marker_stays_addressable():+ """The mirror shape (plain user, then a display marker) already keeps the+ plain row's identity; pin that the merge does not resurrect a display+ classification or swap in the marker's id.+ """+ agent = _bare_agent()+ messages = [+ {"role": "user", "_row_id": 12134, "content": "the user's real prompt"},+ {+ "role": "user",+ "display_kind": "model_switch",+ "_row_id": 12135,+ "content": "[System: The active model for this chat has changed to ds4.]",+ },+ ]++ repairs = AIAgent._repair_message_sequence(agent, messages)++ assert repairs == 1+ assert messages == [+ {+ "role": "user",+ "_row_id": 12134,+ "content": "the user's real prompt\n\n[System: The active model for this chat has changed to ds4.]",+ }+ ]++def test_repair_does_not_rewind_ongoing_dialog_tool_pair():"""assistant(tool_calls) + tool + user is a VALID pattern (user redirectbefore the model gets its continuation turn). Repair must not touch it —diff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.pyindex f733e8c5c84..9e641aaaff1 100644--- a/tests/tui_gateway/test_tui_gateway_server.py+++ b/tests/tui_gateway/test_tui_gateway_server.py@@ -7106,6 +7106,100 @@ def test_prompt_submit_row_id_not_found(monkeypatch):server._sessions.pop("missing-row-sid", None)+def test_prompt_submit_resolves_row_id_absorbed_into_marker_merge(monkeypatch):+ """#94486: after a mid-session model switch, the marker is persisted as+ role=user (#48338) and the next real user row merges into it under+ repair. The merged row must stay addressable (plain row's _row_id kept,+ display classification dropped) so prompt.submit with+ truncate_before_row_id resolves instead of failing closed with the+ user's input silently dropped.+ """+ import copy++ from agent.agent_runtime_helpers import repair_message_sequence++ verbatim = [+ {"_row_id": 12131, "role": "user", "content": "first"},+ {"_row_id": 12133, "role": "assistant", "content": "reply 1"},+ {+ "_row_id": 12134,+ "role": "user",+ "display_kind": "model_switch",+ "content": "[System: The active model for this chat has changed to ds4.]",+ },+ {"_row_id": 12135, "role": "user", "content": "the dropped prompt"},+ ]+ repaired = copy.deepcopy(verbatim)+ assert repair_message_sequence(None, repaired) == 1+ # The merged pair survives as ONE addressable user row carrying the+ # plain row's durable id — this is the property the gateway relies on.+ assert len(repaired) == 3+ assert repaired[2]["_row_id"] == 12135+ assert not repaired[2].get("display_kind")++ replaced = []++ class _FakeDB:+ def get_messages_as_conversation(+ self, key, include_ancestors=False, repair_alternation=False,+ include_row_ids=False, **_kwargs+ ):+ assert key == "session-key"+ assert include_row_ids is True+ return copy.deepcopy(repaired if repair_alternation else verbatim)++ def replace_messages(self, key, messages, active_only=False, archive_dropped=False, **_kwargs):+ replaced.append((key, list(messages)))++ import contextlib++ @contextlib.contextmanager+ def _fake_session_db(_session):+ yield _FakeDB()++ # Live history as it looks after a session restore: the durable+ # transcript reloaded WITHOUT row-id stamps (restore doesn't request+ # them), so resolution must go through the durable fallback.+ live = [+ {"role": "user", "content": "first"},+ {"role": "assistant", "content": "reply 1"},+ {"role": "user", "content": repaired[2]["content"]},+ ]+ server._sessions["merged-marker-sid"] = _session(history=list(live))+ monkeypatch.setattr(server, "_session_db", _fake_session_db)+ monkeypatch.setattr(server, "_get_db", lambda: _FakeDB())+ monkeypatch.setattr(server, "_start_agent_build", lambda *a, **k: None)+ monkeypatch.setattr(server, "_start_inflight_turn", lambda *a, **k: None)++ try:+ resp = server.handle_request(+ {+ "id": "1",+ "method": "prompt.submit",+ "params": {+ "session_id": "merged-marker-sid",+ "text": "new turn",+ "truncate_before_row_id": 12135,+ "confirm_truncate": True,+ },+ }+ )+ assert resp.get("error") is None, resp.get("error")+ # The cut lands before the merged marker+prompt pair: everything the+ # pair would have buried is kept, the pair itself is replaced by the+ # freshly submitted turn. (Rows carry _row_id stamps because the+ # durable fallback healed the live list's missing stamps first.)+ assert len(replaced) == 1+ assert replaced[0][0] == "session-key"+ assert replaced[0][1] == [+ {"role": "user", "content": "first", "_row_id": 12131},+ {"role": "assistant", "content": "reply 1", "_row_id": 12133},+ ]+ assert len(server._sessions["merged-marker-sid"]["history"]) == 2+ finally:+ server._sessions.pop("merged-marker-sid", None)++def test_prompt_submit_row_id_ignores_platform_id_fallback(monkeypatch):"""truncate_before_row_id must not match string platform IDs."""history = [