diff --git a/agent/conversation_loop.py b/agent/conversation_loop.py index ac02f88aa3..98fd42a798 100644 --- a/agent/conversation_loop.py +++ b/agent/conversation_loop.py @@ -739,6 +739,12 @@ def _restore_or_build_system_prompt(agent, system_message, conversation_history) # First turn of a new session (or recovering from a broken stored prompt). agent._cached_system_prompt = agent._build_system_prompt(system_message) + # The rebuilt prompt describes the CURRENT surface, but a surface note left in the + # transcript by an earlier switch does not — retire it here too, or a rebuild for an + # unrelated reason (a model switch) would leave the newest interface statement in the + # request naming a surface the conversation has left (#104414). + _stage_surface_switch_note(agent, agent._cached_system_prompt, conversation_history) + # Plugin hook: on_session_start — fired once for a brand-new session, not on continuation. try: from hermes_cli.lifecycle import invoke_hook as _invoke_hook @@ -805,47 +811,55 @@ def _transcript_row_texts(msg): yield part["text"] -def _surface_already_announced(conversation_history, platform: str) -> bool: - """True when the NEWEST surface note in the transcript already names ``platform``. +def _last_announced_surface(conversation_history) -> str: + """The surface named by the NEWEST surface note in the transcript ("" when there is none). - The note is stamped into the ``api_content`` sidecar, so every later turn replays it; the - gateway builds a fresh AIAgent per turn and would otherwise stack one copy per turn until - the next compaction. Only the newest note is consulted — an older one names the surface - the conversation has since left. + The note is stamped into the ``api_content`` sidecar and persisted, so it is the last thing + the model was TOLD it is running on — and it outranks the stored prompt's own ``Platform:`` + trailer once a switch has been announced. Only the newest note counts: an older one names + a surface the conversation has since left. Reading it back is also what stops a fresh + AIAgent per turn (the gateway shape) from stacking one copy of the note per turn. """ for msg in reversed(conversation_history or []): for text in _transcript_row_texts(msg): if _SURFACE_SWITCH_NOTE_PREFIX in text: - return text.rsplit(_SURFACE_SWITCH_NOTE_PREFIX, 1)[1].startswith(f"{platform} (") - return False + return text.rsplit(_SURFACE_SWITCH_NOTE_PREFIX, 1)[1].split(".", 1)[0].strip() + return "" -def _stage_surface_switch_note(agent, stored_prompt: str, conversation_history) -> bool: - """Stage the correction note when the reused prompt describes a different surface. +def _stage_surface_switch_note(agent, prompt: str, conversation_history) -> bool: + """Stage a correction when the request would otherwise misdescribe the current surface. - Returns whether the note was staged — the caller pairs that with re-persisting the tool - names, because this is the turn the surface's toolset actually changes under it. The note - is one-shot per turn (consumed by ``agent.turn_context.consume_surface_switch_note``) and - is skipped when the transcript already carries one for this surface. + Compares the runtime surface against what the model was last told — the newest surface note + if one exists, else ``prompt``'s own ``Platform:`` trailer. Consulting the note matters in + both directions: switching BACK to the surface the prompt was built for (desktop -> tui -> + desktop) leaves the trailer agreeing with the runtime while a stale note still tells the + model otherwise, and a rebuild for an unrelated reason (a model switch) refreshes the prompt + but not that note. + + The full surface guidance is attached only when the prompt itself is out of date; when the + prompt already describes the current surface the note just retires the stale one. Returns + whether it staged — the caller pairs that with re-persisting the tool names, because this is + the turn the surface's toolset changes under it. """ current = str(getattr(agent, "platform", "") or "").strip() - stored = _stored_prompt_platform(stored_prompt) - if not current or not stored or stored == current: - return False - if _surface_already_announced(conversation_history, current): + described = _stored_prompt_platform(prompt) + told = _last_announced_surface(conversation_history) or described + if not current or not told or told == current: return False from agent.system_prompt import platform_surface_hint + hint = platform_surface_hint(agent) if described != current else "" + where = "the guidance below" if hint else "the interface section in the system prompt above" note = ( - f"{_SURFACE_SWITCH_NOTE_PREFIX}{current} (the system prompt above was written for " - f"{stored}). Its interface section no longer applies — use the guidance below for " - "formatting, file delivery and any interface-specific capability.]" + f"{_SURFACE_SWITCH_NOTE_PREFIX}{current}. Any earlier interface guidance in this " + f"conversation is superseded — follow {where} for formatting, file delivery and any " + "interface-specific capability.]" ) - hint = platform_surface_hint(agent) agent._surface_switch_note = f"{note}\n{hint}" if hint else note logger.info( "Session %s switched surface %s -> %s; keeping the stored system prompt and delivering " "the new surface guidance as a turn note (prefix cache preserved).", - agent.session_id, stored, current, + agent.session_id, told, current, ) return True diff --git a/tests/agent/test_system_prompt_restore.py b/tests/agent/test_system_prompt_restore.py index 4600a9c863..db856b7698 100644 --- a/tests/agent/test_system_prompt_restore.py +++ b/tests/agent/test_system_prompt_restore.py @@ -61,6 +61,15 @@ class TestSurfaceSwitch: f"Platform: {platform}" ) + @staticmethod + def _announced(platform: str) -> list: + """A transcript whose newest surface note says the model is on ``platform``.""" + return [ + {"role": "user", "content": "hi", + "api_content": f"hi\n\n{_SURFACE_SWITCH_NOTE_PREFIX}{platform}. superseded]"}, + {"role": "assistant", "content": "hello"}, + ] + def _restore(self, *, stored: str, current: str, history=None, tool_names=None): db = MagicMock() row = {"system_prompt": self._stored(stored)} @@ -85,7 +94,7 @@ class TestSurfaceSwitch: def test_switch_stages_the_new_surface_guidance(self): agent = self._restore(stored="desktop", current="tui") note = agent._surface_switch_note - assert note.startswith(f"{_SURFACE_SWITCH_NOTE_PREFIX}tui (") + assert note.startswith(f"{_SURFACE_SWITCH_NOTE_PREFIX}tui.") # The correction carries the CURRENT surface's hint, so the model is not left # following the desktop guidance still sitting in the reused prompt. assert "terminal UI (TUI)" in note @@ -99,22 +108,41 @@ class TestSurfaceSwitch: def test_not_restaged_once_the_transcript_carries_it(self): # The note is stamped into the byte-stable api_content sidecar, and the gateway # builds a fresh AIAgent per turn — without the dedup every turn would add a copy. - history = [ - {"role": "user", "content": "hi", - "api_content": f"hi\n\n{_SURFACE_SWITCH_NOTE_PREFIX}tui (...)]"}, - {"role": "assistant", "content": "hello"}, - ] - agent = self._restore(stored="desktop", current="tui", history=history) + agent = self._restore(stored="desktop", current="tui", history=self._announced("tui")) assert agent._surface_switch_note == "" def test_a_further_switch_is_announced_again(self): # Only the NEWEST note counts: it names the surface the conversation has left. - history = [ - {"role": "user", "content": f"hi\n\n{_SURFACE_SWITCH_NOTE_PREFIX}tui (...)]"}, - {"role": "assistant", "content": "hello"}, - ] - agent = self._restore(stored="desktop", current="cli", history=history) - assert agent._surface_switch_note.startswith(f"{_SURFACE_SWITCH_NOTE_PREFIX}cli (") + agent = self._restore(stored="desktop", current="cli", history=self._announced("tui")) + assert agent._surface_switch_note.startswith(f"{_SURFACE_SWITCH_NOTE_PREFIX}cli.") + + def test_returning_to_the_prompts_own_surface_is_announced(self): + """desktop -> tui -> desktop. + + The trailer now agrees with the runtime, so comparing against the prompt alone would + stage nothing and leave the model acting on the stale "you are on tui" note. + """ + agent = self._restore(stored="desktop", current="desktop", history=self._announced("tui")) + assert agent._surface_switch_note.startswith(f"{_SURFACE_SWITCH_NOTE_PREFIX}desktop.") + # The prompt already describes this surface, so the note retires the stale one and + # points at the prompt instead of duplicating the whole hint. + assert "the interface section in the system prompt above" in agent._surface_switch_note + + def test_rebuild_also_retires_a_stale_note(self): + # A rebuild for an unrelated reason (a model switch) refreshes the prompt but not the + # note already sitting in the transcript. + db = MagicMock() + db.get_session.return_value = {"system_prompt": self._stored("desktop")} + agent = _make_agent(session_db=db, prebuilt_prompt=self._stored("desktop")) + agent.model = "other-model" + agent.platform = "desktop" + agent._platform_hint_overrides = None + agent._surface_switch_note = "" + + _restore_or_build_system_prompt(agent, None, self._announced("tui")) + + agent._build_system_prompt.assert_called_once() + assert agent._surface_switch_note.startswith(f"{_SURFACE_SWITCH_NOTE_PREFIX}desktop.") def test_tool_prefix_is_replaced_on_the_turn_that_announces_a_switch(self): """The saved names are the PREVIOUS surface's toolset. @@ -138,12 +166,8 @@ class TestSurfaceSwitch: # turn persisted this surface's tools, so the next turn pins those. from unittest.mock import patch - history = [ - {"role": "user", "content": f"hi\n\n{_SURFACE_SWITCH_NOTE_PREFIX}tui (...)]"}, - {"role": "assistant", "content": "hello"}, - ] with patch("tools.mcp_tool_agent.restore_agent_tool_prefix") as pin: - self._restore(stored="desktop", current="tui", history=history, + self._restore(stored="desktop", current="tui", history=self._announced("tui"), tool_names='["read_file"]') pin.assert_called_once()