Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

fix(backend/copilot): apply the building-mode guide on restart instead of re-deriving it from history (#14721)

Reinier van der Leercdc8611c83a2
diff --git a/autogpt_platform/backend/backend/copilot/builder_context.py b/autogpt_platform/backend/backend/copilot/builder_context.py
index 6751350e6b..e4b53016a6 100644
--- a/autogpt_platform/backend/backend/copilot/builder_context.py
+++ b/autogpt_platform/backend/backend/copilot/builder_context.py
@@ -149,7 +149,9 @@ def _format_links(
return f"<links>\n{body}\n</links>"
-async def build_builder_system_prompt_suffix(session: ChatSession) -> str:
+async def build_builder_system_prompt_suffix(
+ session: ChatSession, *, force: bool = False
+) -> str:
"""Return the cacheable system-prompt suffix for a building session.
Two cases include the full agent-building guide in the system prompt so
@@ -164,11 +166,15 @@ async def build_builder_system_prompt_suffix(session: ChatSession) -> str:
is needed and the suffix stays byte-identical across the rest of the
session (one prompt-cache re-write when the mode first activates).
+ *force* skips that history check for the caller that already knows the
+ answer — the SDK building-mode restart, which runs only because the enter
+ tool set the flag in *this* turn, before its row is in ``messages``.
+
Holds only static content so the bytes are identical across turns AND
across sessions — live graph id/name/version ride on the per-turn prefix.
"""
is_builder = bool(session.metadata.builder_graph_id)
- if not is_builder and not session_entered_building_mode(session):
+ if not force and not is_builder and not session_entered_building_mode(session):
return ""
try:
diff --git a/autogpt_platform/backend/backend/copilot/builder_context_test.py b/autogpt_platform/backend/backend/copilot/builder_context_test.py
index 44b66b64b1..d6172cfea7 100644
--- a/autogpt_platform/backend/backend/copilot/builder_context_test.py
+++ b/autogpt_platform/backend/backend/copilot/builder_context_test.py
@@ -386,6 +386,36 @@ async def test_system_prompt_suffix_for_building_session():
assert "do not call" in result.lower()
+async def test_system_prompt_suffix_force_bypasses_the_history_read():
+ """``force`` serves the caller that already knows the answer — the SDK
+ building-mode restart, which runs in the same turn as the enter call and
+ so cannot find it in persisted history yet."""
+ session = _session(None)
+ assert session.messages == []
+
+ assert await build_builder_system_prompt_suffix(session) == ""
+ with patch(
+ "backend.copilot.builder_context._load_guide",
+ return_value="# Guide body",
+ ):
+ forced = await build_builder_system_prompt_suffix(session, force=True)
+
+ assert "<building_guide>" in forced
+ assert "# Guide body" in forced
+ assert "<builder_session>" not in forced
+
+
+async def test_system_prompt_suffix_force_still_empty_when_guide_load_fails():
+ session = _session(None)
+ with patch(
+ "backend.copilot.builder_context._load_guide",
+ side_effect=OSError("missing"),
+ ):
+ assert await build_builder_system_prompt_suffix(session, force=True) == ""
+
+
@pytest.mark.asyncio
async def test_system_prompt_suffix_empty_without_prior_guide_read():
session = _session(None)
diff --git a/autogpt_platform/backend/backend/copilot/sdk/building_mode_restart_test.py b/autogpt_platform/backend/backend/copilot/sdk/building_mode_restart_test.py
index 8b359969cd..8102fb6fee 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/building_mode_restart_test.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/building_mode_restart_test.py
@@ -140,14 +140,68 @@ class TestApplyBuildingModeRestart:
assert marker in text
@pytest.mark.asyncio
- async def test_empty_suffix_degrades_without_prompt_upgrade(self, mocker):
- session, state, _, _ = await self._run(mocker, suffix="")
-
- assert session.building_mode_requested is False
+ async def test_empty_suffix_relaunches_without_the_confirmation(self, mocker):
+ """An empty suffix means the guide is genuinely absent, so the model
+ must not be told it is present — that sentence costs it the rest of
+ the turn chasing a gate that cannot clear."""
+ session, state, _, continuation = await self._run(mocker, suffix="")
+
+ assert state.query_message != continuation
+ assert "could not be loaded" in state.query_message
assert session.guide_in_system_prompt is False
- # The restart still proceeds — resume wiring is unconditional.
+ # Cleared as on the success path, which is what stops the restart
+ # re-firing at the next message boundary of this turn.
+ assert session.building_mode_requested is False
+ # The relaunch itself still proceeds — resume wiring is unconditional.
assert state.use_resume is True
+ @pytest.mark.asyncio
+ async def test_guide_applied_although_history_lacks_the_enter_call(self, mocker):
+ """Production shape: the restart runs microseconds after the enter
+ tool ran, before its row is in ``messages``. Deriving "is this session
+ building?" from history there answers False and strands the turn with
+ no guide — this is the case dev logged 16 times in six hours.
+
+ The real suffix builder runs here on purpose: patching it would prove
+ only the wiring, never that the predicate underneath it answers.
+ """
+ from backend.copilot.sdk.service import (
+ _BUILDING_MODE_CONTINUATION,
+ _apply_building_mode_restart,
+ )
+
+ session = _session(requested=True, guide_loaded=False)
+ assert session.messages == []
+ assert session.has_tool_been_called("enter_agent_building_mode") is False
+ state = self._state(prior_emitted=False, thinking_reprompted=False)
+ mocker.patch(
+ "backend.copilot.builder_context._load_guide",
+ return_value="# Guide body",
+ )
+
+ await _apply_building_mode_restart(
+ session=session,
+ state=state,
+ sdk_options=MagicMock(),
+ base_system_prompt="BASE",
+ delegation_supplement="",
+ oversight_supplement="",
+ team_building_supplement="",
+ graphiti_supplement="",
+ use_e2b=False,
+ session_id="sess-1",
+ message_id="msg-1",
+ log_prefix="[test]",
+ )
+
+ prompt = state.options.system_prompt
+ text = prompt if isinstance(prompt, str) else prompt["append"]
+ assert "<building_guide>" in text
+ assert "# Guide body" in text
+ assert session.guide_in_system_prompt is True
+ assert session.building_mode_requested is False
+ assert state.query_message == _BUILDING_MODE_CONTINUATION
+
@pytest.mark.asyncio
async def test_adapter_carry_over(self, mocker):
_, state, _, _ = await self._run(
diff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.py
index 564a838455..1ee3ab8751 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/service.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py
@@ -970,6 +970,15 @@ _BUILDING_MODE_CONTINUATION = (
"Continue working on the user's request from where you left off."
)
+# Sent instead when the guide could not be loaded, so the model is never told
+# a <building_guide> block is present that is not. The building-mode gates stay
+# closed, which is correct — the guide really is absent.
+_BUILDING_MODE_UNAVAILABLE_CONTINUATION = (
+ "The agent-building guide could not be loaded into your system prompt. "
+ "Continue working on the user's request from where you left off, and do "
+ "not retry enter_agent_building_mode in this turn."
+)
+
# Synthetic message injected when a turn ends with extended thinking but no
# visible TextBlock. Bounded to one re-prompt per turn — if the model still
# returns thinking-only the adapter promotes the last thinking block to
@@ -1722,12 +1731,19 @@ async def _apply_building_mode_restart(
building_mode_requested flips False either way.
"""
session.building_mode_requested = False
- building_suffix = await build_builder_system_prompt_suffix(session)
+ # ``force``: the enter tool set the flag in this very turn, so re-deriving
+ # "is this session building?" from persisted history asks a question the
+ # caller already answered — and answers it wrong, because the tool call is
+ # not in ``messages`` yet.
+ building_suffix = await build_builder_system_prompt_suffix(session, force=True)
session.guide_in_system_prompt = bool(building_suffix)
if not building_suffix:
+ # Only a guide-load failure reaches here now.
logger.error(
- f"{log_prefix} Building-mode restart: guide suffix "
- f"empty — continuing without prompt upgrade"
+ "%s Building-mode restart: guide suffix empty — relaunching "
+ "without the guide (session_id=%s)",
+ log_prefix,
+ session.session_id,
)
expert_session_suffix = await build_expert_identity_suffix(
session.user_id,
@@ -1764,7 +1780,11 @@ async def _apply_building_mode_restart(
state.options = sdk_options_restart
state.use_resume = True
state.resume_file = session_id
- state.query_message = _BUILDING_MODE_CONTINUATION
+ state.query_message = (
+ _BUILDING_MODE_CONTINUATION
+ if building_suffix
+ else _BUILDING_MODE_UNAVAILABLE_CONTINUATION
+ )
# Fresh adapter, same carry-over rules as a transient retry.
# NOTE: the transcript builder is NOT restored — its partial
# entries are real; the relaunched run's `append_user` adds
@@ -1779,6 +1799,8 @@ async def _apply_building_mode_restart(
state.adapter.thinking_only_reprompted = state.thinking_only_reprompted
if prior_adapter.emitted_real_content_to_wire:
state.adapter.prior_attempt_emitted_visible_content = True
+ if not building_suffix:
+ return StreamStatus(message="Continuing without the agent guide…")
return StreamStatus(message="Entering building mode — loading the agent guide…")