From ec24dd3556cabfd30baebdbd42fbad0993166bec Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Thu, 5 Nov 2026 13:57:27 -0800 Subject: [PATCH] fix(acp): replay the retained content_refused row so a reopened editor still shows the refused ask A provider safety refusal takes the whole refused turn out of the MODEL context (retain_refused_turn_for_display) so a reload can't re-send the blocked content and re-lock the chat, but KEEPS the user's ask in the DISPLAY projection as a greyed content_refused row. ACP's _replay_session_history replayed only state.history (the active-only model view), which no longer carries that row, so load_session/resume_session hid the refused ask and notice on every reopen even though SQLite retained them. Replay the durable DISPLAY projection instead (SessionManager.display_history -> get_messages_as_conversation(include_compacted=True)), falling back to state.history when the DB view is unavailable; model context stays clean. _history_replay_updates renders a content_refused user row as the (greyable) ask followed by the refusal notice as an agent message, so a reopened editor shows 'you asked X -> refused'. Test drives a REAL load_session through a fresh server on the same DB (process-restart fidelity) and asserts the replayed session/update stream carries the refused ask + notice; proven red on bde73dde794. --- acp_adapter/server.py | 59 +++++++++++++++++-- acp_adapter/session.py | 15 +++++ tests/acp_adapter/test_failed_turn_closure.py | 42 +++++++++++++ 3 files changed, 111 insertions(+), 5 deletions(-) diff --git a/acp_adapter/server.py b/acp_adapter/server.py index 9c6c237588..3744c443b8 100644 --- a/acp_adapter/server.py +++ b/acp_adapter/server.py @@ -6,6 +6,7 @@ import asyncio from datetime import datetime, timezone, UTC import contextlib import contextvars +import json import logging import os import threading @@ -38,6 +39,8 @@ from acp_adapter.provenance import session_provenance_meta from acp_adapter.session import SessionManager, SessionState, _expand_acp_enabled_toolsets from acp_adapter.tools import build_tool_complete, build_tool_start, coerce_tool_args from agent.context_compressor import (COMPRESSED_SUMMARY_METADATA_KEY, ContextCompressor) +from agent.turn_failure_copy import ( + CONTENT_REFUSED_DISPLAY_KIND, CONTENT_REFUSED_METADATA_KEY, CONTENT_REFUSED_NOTICE) from agent.interrupt_compat import request_hard_interrupt from tools.approval_context import reset_hermes_interactive_context, set_hermes_interactive_context @@ -123,6 +126,43 @@ def _history_message_chunk(role: str, message: dict[str, Any]) -> UserMessageChu ) +def _content_refused_notice(message: dict[str, Any]) -> str | None: + """The stored refusal notice when *message* is a retained ``content_refused`` display row, else + ``None``. The row keeps the user's own refused ask VISIBLE but is gone from the MODEL context + (``active = 0``), so the active-only model history never carries it — only the display projection + does. Falls back to the shared notice when the row predates a stored one.""" + if message.get("display_kind") != CONTENT_REFUSED_DISPLAY_KIND: + return None + meta = message.get("display_metadata") + if isinstance(meta, str): + try: + meta = json.loads(meta) + except (ValueError, TypeError): + meta = None + entry = meta.get(CONTENT_REFUSED_METADATA_KEY) if isinstance(meta, dict) else None + notice = entry.get("notice") if isinstance(entry, dict) else None + return notice if isinstance(notice, str) and notice.strip() else CONTENT_REFUSED_NOTICE + + +def _user_history_updates(message: dict[str, Any]): + """Replay a persisted user row. A retained ``content_refused`` row keeps the user's ask visible + (tagged ``hermes.contentRefused`` so a client can grey it) and is followed by the refusal notice + as an agent message, so a reopened editor still shows "you asked X -> refused" even though the + turn was dropped from the model context. A plain user row replays unchanged.""" + notice = _content_refused_notice(message) + if notice is not None: + if (text := _flatten_history_text(message.get("content"))): + yield UserMessageChunk( + session_update="user_message_chunk", + content=TextContentBlock(type="text", text=text), + field_meta={"hermes": {"contentRefused": True}}, + ) + yield acp.update_agent_message_text(notice) + return + if (chunk := _history_message_chunk("user", message)) is not None: + yield chunk + + def _history_replay_updates(history: list[dict[str, Any]]): """Yield ACP session updates that reconstruct a persisted transcript, in order: user/assistant text (with compaction ``_meta``), assistant thoughts, and tool-call start/complete pairs @@ -131,8 +171,7 @@ def _history_replay_updates(history: list[dict[str, Any]]): for message in history: role = str(message.get("role") or "") if role == "user": - if (chunk := _history_message_chunk(role, message)) is not None: - yield chunk + yield from _user_history_updates(message) elif role == "assistant": thought = _history_reasoning_text(message) if thought: @@ -568,10 +607,20 @@ class HermesACPAgent(SlashCommandsMixin, acp.Agent): async def _replay_session_history(self, state: SessionState) -> None: """Replay history as user/assistant/thought chunks plus reconstructed tool-call - start/complete events so the editor shows the transcript, not a clean thread.""" - if not self._conn or not state.history: + start/complete events so the editor shows the transcript, not a clean thread. + + Replays the DURABLE DISPLAY projection, not ``state.history``: a safety-refused turn is + taken out of the model context (``retain_refused_turn_for_display``) so it can't re-lock the + chat, but is KEPT in the display projection as a ``content_refused`` row. ``state.history`` is + the active-only model view and no longer carries it, so replaying that alone would hide the + user's refused ask on every reopen. The display read includes the retained row; it falls back + to ``state.history`` when the DB view is unavailable (e.g. a test agent factory).""" + if not self._conn: return - for update in _history_replay_updates(state.history): + history = self.session_manager.display_history(state.session_id) or state.history + if not history: + return + for update in _history_replay_updates(history): if not await self._send(state.session_id, update, fail_msg="Failed to replay ACP history for session %s"): return diff --git a/acp_adapter/session.py b/acp_adapter/session.py index 81f29bf359..a26b497570 100644 --- a/acp_adapter/session.py +++ b/acp_adapter/session.py @@ -250,6 +250,21 @@ class SessionManager: path = Path(self._db_instance.db_path) if self._db_instance is not None else get_hermes_home() / "state.db" return read_catalog_rows(path) + def display_history(self, session_id: str) -> Optional[list[dict[str, Any]]]: + """The DURABLE DISPLAY projection for a session (``include_compacted``): what a reopened + editor should show, which is a SUPERSET of the active-only model history. In particular it + keeps a safety-refused turn's retained ``content_refused`` row, which the model context + dropped (``active = 0``). ``None`` when the DB is unavailable (e.g. a test agent factory), + so callers fall back to the in-memory model history.""" + db = self._get_db() + if db is None: + return None + try: + return db.get_messages_as_conversation(session_id, include_compacted=True) + except Exception: + logger.debug("Failed to load ACP display history for %s", session_id, exc_info=True) + return None + def update_cwd(self, session_id: str, cwd: str) -> Optional[SessionState]: """Update the working directory for a session and its tool overrides.""" cwd = _translate_acp_cwd(cwd) diff --git a/tests/acp_adapter/test_failed_turn_closure.py b/tests/acp_adapter/test_failed_turn_closure.py index 04a73a3bf2..0ff6ccaff1 100644 --- a/tests/acp_adapter/test_failed_turn_closure.py +++ b/tests/acp_adapter/test_failed_turn_closure.py @@ -280,6 +280,48 @@ def test_acp_refused_turn_stays_in_the_display_tagged_content_refused(acp): assert CONTENT_REFUSED_METADATA_KEY in (refused_row.get("display_metadata") or {}) +def test_acp_reload_replays_the_refused_ask_and_notice_to_the_editor(acp): + """Finding #4486245780: reopening the editor must still SHOW the refused turn. + + The refused turn leaves the MODEL context (``state.history`` is active-only) but is RETAINED in + the display projection. A reopened editor replays history via ``load_session``; if that replays + only the clean model history the user's refused ask and notice vanish on every reopen even though + SQLite keeps them. This drives a REAL ``load_session`` through a FRESH server (process-restart + fidelity) sharing the same DB and asserts the replayed ``session/update`` stream — not just the + DB rows — carries the refused ask plus the refusal notice, and still the prior clean exchange. + """ + from agent.turn_failure_copy import CONTENT_REFUSED_NOTICE + from acp_adapter.server import HermesACPAgent + from acp_adapter.session import SessionManager + + provider, prompt, _rows, db, sid, _conn, server = acp + + provider.script = [{"finish_reason": "stop", "content": "Hello there."}] + prompt("hello") + provider.script = [{"finish_reason": "content_filter", "content": _REFUSAL_DETAIL}] + prompt(_REFUSED) + + cwd = server.session_manager.get_session(sid).cwd + + # Reopen from a fresh process: a new server + manager on the same DB cold-restores the session, + # then replays it to the editor. + reopened_conn = _RecordingConn() + reopened = HermesACPAgent(session_manager=SessionManager(db=db)) + reopened.on_connect(reopened_conn) + resp = asyncio.run(reopened.load_session(cwd=cwd, session_id=sid)) + assert resp is not None + + texts = [getattr(getattr(u, "content", None), "text", None) or getattr(u, "text", None) + for u in reopened_conn.updates] + # The refused ask is shown again (model history alone would hide it). + assert any(_REFUSED in (t or "") for t in texts), f"refused ask hidden on reload: {texts}" + # The refusal notice rides along so the editor shows "you asked X -> refused". + assert any(CONTENT_REFUSED_NOTICE in (t or "") for t in texts), f"refusal notice missing: {texts}" + # The prior accepted exchange is still replayed. + assert any((t or "") == "hello" for t in texts) + assert any("Hello there." in (t or "") for t in texts) + + def test_failed_turn_boundary_is_idempotent_on_the_durable_tail_and_skips_context_overflow(tmp_path, monkeypatch): """Keyed on ``SessionDB.latest_conversation_role``: a redelivery of an already-closed turn writes no second row, an assistant tail is left alone, and the context-overflow class