diff --git a/astrbot/core/agent/context/round_utils.py b/astrbot/core/agent/context/round_utils.py index c93057ef44..660ef3fa2e 100644 --- a/astrbot/core/agent/context/round_utils.py +++ b/astrbot/core/agent/context/round_utils.py @@ -20,13 +20,25 @@ def split_into_rounds( ) -> list[list[RoundSegment]]: """Split a flat contexts list into logical rounds. - A round begins at a ``user`` segment and includes all subsequent - ``assistant`` / ``tool`` segments until the next ``user`` segment. + A round begins at a user input and includes subsequent assistant, tool, + and generated user-role segments until the next user input. Generated + messages marked ``_turn_continuation`` do not start a new round. + + Args: + contexts: Flat messages, optionally including a pre-user fragment. + + Returns: + Logical rounds, with any pre-user fragment in a separate first group. """ rounds: list[list[RoundSegment]] = [] current: list[RoundSegment] = [] for seg in contexts: - if _segment_role(seg) == "user" and current: + starts_turn = _segment_role(seg) == "user" and not ( + seg._turn_continuation + if isinstance(seg, Message) + else seg.get("_turn_continuation", False) + ) + if starts_turn and current: rounds.append(current) current = [] current.append(seg) diff --git a/astrbot/core/agent/context/truncator.py b/astrbot/core/agent/context/truncator.py index 9abf574336..7ee7f34673 100644 --- a/astrbot/core/agent/context/truncator.py +++ b/astrbot/core/agent/context/truncator.py @@ -1,4 +1,7 @@ +from typing import cast + from ..message import Message +from .round_utils import split_into_rounds class ContextTruncator: @@ -21,7 +24,7 @@ def _split_system_rest( Returns: tuple: (system_messages, non_system_messages) """ - first_non_system = 0 + first_non_system = len(messages) for i, msg in enumerate(messages): if msg.role != "system": first_non_system = i @@ -103,15 +106,21 @@ def truncate_by_turns( keep_most_recent_turns: int, drop_turns: int = 1, ) -> list[Message]: - """ - Turn-based truncation strategy, which drops the oldest turns while keeping the most recent N turns. - A turn consists of a user message and an assistant message. - This method ensures that the truncated context list conforms to OpenAI's context format. + """Keep the most recent complete user turns when the limit is exceeded. + + A turn starts at a user input and includes all subsequent assistant + messages, tool calls, tool results and generated user-role messages + until the next user input. A pre-user fragment does not count as a turn + and is discarded when truncation occurs. + The current, possibly unfinished turn counts towards the limit and is + always retained along with the leading system messages. Args: messages: The original list of messages in the context. keep_most_recent_turns: The number of most recent turns to keep. If set to -1, it means keeping all turns (no truncation). - drop_turns: The number of turns to drop from the beginning. + drop_turns: Additional retention reduction on overflow. Retains + ``keep_most_recent_turns - drop_turns + 1`` turns, with a minimum + of one so the current task is not discarded. Returns: The truncated list of messages. @@ -120,27 +129,15 @@ def truncate_by_turns( return messages system_messages, non_system_messages = self._split_system_rest(messages) + rounds = cast(list[list[Message]], split_into_rounds(non_system_messages)) + if rounds and (rounds[0][0].role != "user" or rounds[0][0]._turn_continuation): + rounds = rounds[1:] - if len(non_system_messages) // 2 <= keep_most_recent_turns: + if len(rounds) <= max(1, keep_most_recent_turns): return messages - num_to_keep = keep_most_recent_turns - drop_turns + 1 - if num_to_keep <= 0: - truncated_contexts = [] - else: - truncated_contexts = non_system_messages[-num_to_keep * 2 :] - - # Find the first user message - index = next( - (i for i, item in enumerate(truncated_contexts) if item.role == "user"), - None, - ) - if index is not None and index > 0: - truncated_contexts = truncated_contexts[index:] - - result = self._ensure_user_message( - system_messages, truncated_contexts, messages - ) + num_to_keep = max(1, keep_most_recent_turns - drop_turns + 1) + result = system_messages + [msg for rnd in rounds[-num_to_keep:] for msg in rnd] return self.fix_messages(result) def truncate_by_dropping_oldest_turns( @@ -148,28 +145,32 @@ def truncate_by_dropping_oldest_turns( messages: list[Message], drop_turns: int = 1, ) -> list[Message]: - """Drop the oldest N turns, regardless of the number of turns to keep.""" + """Drop the oldest complete user turns while preserving the latest one. + + A pre-user fragment is discarded along with the removed turns and + does not count towards the number of turns dropped. + + Args: + messages: Context including any leading system messages. + drop_turns: Number of oldest turns to remove. Nonpositive values + disable truncation; at least the latest complete turn is kept. + + Returns: + Context with leading system messages and the retained turns. + """ if drop_turns <= 0: return messages system_messages, non_system_messages = self._split_system_rest(messages) + rounds = cast(list[list[Message]], split_into_rounds(non_system_messages)) + if rounds and (rounds[0][0].role != "user" or rounds[0][0]._turn_continuation): + rounds = rounds[1:] - if len(non_system_messages) // 2 <= drop_turns: - truncated_non_system = [] - else: - truncated_non_system = non_system_messages[drop_turns * 2 :] - - # Find the first user message - index = next( - (i for i, item in enumerate(truncated_non_system) if item.role == "user"), - None, - ) - if index is not None: - truncated_non_system = truncated_non_system[index:] + if len(rounds) <= 1: + return messages - result = self._ensure_user_message( - system_messages, truncated_non_system, messages - ) + num_to_drop = min(drop_turns, len(rounds) - 1) + result = system_messages + [msg for rnd in rounds[num_to_drop:] for msg in rnd] return self.fix_messages(result) def truncate_by_halving( diff --git a/astrbot/core/agent/message.py b/astrbot/core/agent/message.py index a38e066e60..ed0895adb5 100644 --- a/astrbot/core/agent/message.py +++ b/astrbot/core/agent/message.py @@ -206,6 +206,8 @@ class Message(BaseModel): """The ID of the tool call.""" _no_save: bool = PrivateAttr(default=False) + _turn_continuation: bool = PrivateAttr(default=False) + """Whether a generated user-role message continues the current user turn.""" @model_validator(mode="after") def check_content_required(self): @@ -255,13 +257,13 @@ class SystemMessageSegment(Message): def load_messages(history: list[dict]) -> list[Message]: - """Load working messages while restoring temporary-content markers. + """Load working messages with temporary-content and turn-boundary markers. Args: history: Serialized conversation messages. Returns: - Validated messages with their temporary-content markers restored. + Validated messages with their internal context markers restored. Raises: ValueError: A message has an invalid role or content. @@ -271,6 +273,8 @@ def load_messages(history: list[dict]) -> list[Message]: message = Message.model_validate(item) if item.get("_no_save"): message._no_save = True + if item.get("_turn_continuation"): + message._turn_continuation = True messages.append(message) return messages @@ -279,18 +283,20 @@ def load_messages(history: list[dict]) -> list[Message]: def dump_messages( messages: list[Message], *, include_temporary: bool = False ) -> list[dict]: - """Serialize working messages with optional temporary-content markers. + """Serialize working messages with turn boundaries and optional exclusions. Args: messages: Runtime working messages. include_temporary: Preserve exclusion markers for the event journal. Returns: - Serialized messages with optional temporary-content markers. + Serialized messages retaining turn boundaries and optional exclusions. """ dumped: list[dict] = [] for message in messages: message_data = message.model_dump() + if message._turn_continuation: + message_data["_turn_continuation"] = True if include_temporary and message._no_save: message_data["_no_save"] = True if isinstance(message.content, list): diff --git a/astrbot/core/agent/runners/tool_loop_agent_runner.py b/astrbot/core/agent/runners/tool_loop_agent_runner.py index 6508051100..d62befcf3e 100644 --- a/astrbot/core/agent/runners/tool_loop_agent_runner.py +++ b/astrbot/core/agent/runners/tool_loop_agent_runner.py @@ -1503,10 +1503,10 @@ async def _step_until_done( if self.req: self.req.func_tool = None self.run_context.tools = None - # 注入提示词 - await self._append_context_messages( - [Message(role="user", content=self.MAX_STEPS_REACHED_PROMPT)] - ) + # Keep the generated instruction in the active user turn. + limit_message = Message(role="user", content=self.MAX_STEPS_REACHED_PROMPT) + limit_message._turn_continuation = True + await self._append_context_messages([limit_message]) # 再执行最后一步 async with aclosing(self.step()) as responses: async for resp in responses: @@ -1630,9 +1630,9 @@ async def append_tool_result_images( if content is not None: content.extend(image_parts) else: - await self._append_context_messages( - [Message(role="user", content=image_parts)] - ) + image_message = Message(role="user", content=image_parts) + image_message._turn_continuation = True + await self._append_context_messages([image_message]) logger.debug( f"Appended {len(cached_images)} cached image(s) to context for LLM review" ) diff --git a/astrbot/core/astr_agent_runtime/delegated_session.py b/astrbot/core/astr_agent_runtime/delegated_session.py index 1a124a5e78..61ffa2e404 100644 --- a/astrbot/core/astr_agent_runtime/delegated_session.py +++ b/astrbot/core/astr_agent_runtime/delegated_session.py @@ -415,13 +415,7 @@ async def _prepare_turn( ) req = ProviderRequest( system_prompt=instructions.system_prompt, - contexts=[ - { - **message.model_dump(), - **({"_no_save": True} if message._no_save else {}), - } - for message in history - ], + contexts=dump_messages(history, include_temporary=True), func_tool=tools if tools.tools else None, conversation=Conversation( platform_id=caller.event.get_platform_id(), diff --git a/astrbot/core/provider/provider.py b/astrbot/core/provider/provider.py index 7232551647..983d0a42a5 100644 --- a/astrbot/core/provider/provider.py +++ b/astrbot/core/provider/provider.py @@ -206,6 +206,10 @@ def _ensure_message_to_dicts( for message in messages: if isinstance(message, Message): dicts.append(message.model_dump()) + elif "_turn_continuation" in message: + dicts.append( + {k: v for k, v in message.items() if k != "_turn_continuation"} + ) else: dicts.append(message) diff --git a/tests/agent/test_context_manager.py b/tests/agent/test_context_manager.py index 756a268d0a..02cc5284eb 100644 --- a/tests/agent/test_context_manager.py +++ b/tests/agent/test_context_manager.py @@ -694,6 +694,36 @@ async def test_fallback_keeps_latest_round_when_it_alone_exceeds_limit( assert result == [messages[0], messages[-1]] assert "only the latest round left" in caplog.text + @pytest.mark.asyncio + @pytest.mark.parametrize("summary", [False, True]) + async def test_token_fallback_keeps_internal_notice_with_oversized_request( + self, summary + ): + """The last internal notice cannot replace the active request in fallback.""" + from astrbot.core.agent.message import dump_messages, load_messages + + original = self._rounds_with_tool_chain("f" * 900) + messages = load_messages( + dump_messages(original) + + [ + {"role": "assistant", "content": "Working"}, + { + "role": "user", + "content": "Internal notice", + "_turn_continuation": True, + }, + ] + ) + config = ContextConfig( + max_context_tokens=1000, + llm_compress_provider=FailingProvider() if summary else None, + custom_token_counter=CharTokenCounter(), + ) + + result = await ContextManager(config).process(messages) + + assert result == [messages[0], *messages[-3:]] + @pytest.mark.asyncio @pytest.mark.parametrize("summary", [False, True]) @pytest.mark.parametrize("custom_counter", [False, True]) @@ -1228,6 +1258,25 @@ def test_split_rounds_empty(self): rounds = split_into_rounds([]) assert len(rounds) == 0 + @pytest.mark.parametrize("as_models", [False, True]) + def test_split_rounds_keeps_internal_user_messages_in_current_round( + self, as_models + ): + """Internal notices must not split a user's request from its result.""" + from astrbot.core.agent.context.round_utils import split_into_rounds + from astrbot.core.agent.message import load_messages + + history = [ + {"role": "user", "content": "Request"}, + {"role": "assistant", "content": "Working"}, + {"role": "user", "content": "Internal notice", "_turn_continuation": True}, + {"role": "assistant", "content": "Done"}, + {"role": "user", "content": "Follow-up"}, + ] + messages = load_messages(history) if as_models else history + + assert split_into_rounds(messages) == [messages[:4], messages[4:]] + def test_split_rounds_accepts_message_objects(self): """Message objects can be split without converting them to dictionaries.""" from astrbot.core.agent.context.round_utils import split_into_rounds diff --git a/tests/agent/test_truncator.py b/tests/agent/test_truncator.py index 7dac80f9ce..660e4ce490 100644 --- a/tests/agent/test_truncator.py +++ b/tests/agent/test_truncator.py @@ -1,7 +1,9 @@ """Tests for ContextTruncator.""" +import pytest + from astrbot.core.agent.context.truncator import ContextTruncator -from astrbot.core.agent.message import Message +from astrbot.core.agent.message import Message, ToolCall, load_messages class TestContextTruncator: @@ -32,6 +34,216 @@ def create_messages( messages.append(self.create_message(role, f"Message {i}")) return messages + def create_tool_turn(self, tool_calls: int, prefix: str = "task") -> list[Message]: + """Create one complete user turn with paired tool calls and results. + + Args: + tool_calls: Number of sequential tool calls in the turn. + prefix: Unique prefix for message contents and tool call IDs. + + Returns: + The user request, tool chain and final assistant reply. + """ + messages = [self.create_message("user", f"{prefix} request")] + for i in range(tool_calls): + call_id = f"{prefix}-{i}" + messages.extend( + [ + Message( + role="assistant", + tool_calls=[ + ToolCall( + id=call_id, + function=ToolCall.FunctionBody( + name="read", arguments="{}" + ), + ) + ], + ), + Message(role="tool", tool_call_id=call_id, content=f"result {i}"), + ] + ) + messages.append(self.create_message("assistant", f"{prefix} done")) + return messages + + @pytest.mark.parametrize("tool_calls", [22, 100]) + @pytest.mark.parametrize("with_follow_up", [False, True]) + @pytest.mark.parametrize("limit", [-1, 2, 20]) + def test_long_tool_turn_does_not_consume_extra_turns( + self, tool_calls, with_follow_up, limit + ): + """Count a tool-heavy task as one turn, including its final reply.""" + messages = [self.create_message("system", "Persona")] + messages.extend(self.create_tool_turn(tool_calls)) + if with_follow_up: + messages.append(self.create_message("user", "Continue")) + before = [message.model_dump() for message in messages] + + result = ContextTruncator().truncate_by_turns( + messages, keep_most_recent_turns=limit + ) + + assert result is messages + assert [message.model_dump() for message in messages] == before + + @pytest.mark.parametrize("limit, drop_turns, retained", [(2, 1, 2), (3, 2, 2)]) + def test_turn_limit_keeps_complete_recent_tool_turns( + self, limit, drop_turns, retained + ): + """Remove complete oldest turns while retaining both tool calls and results.""" + systems = [ + self.create_message("system", "Persona"), + self.create_message("system", "Memo"), + ] + turns = [ + self.create_tool_turn(count, f"task-{i}") + for i, count in enumerate([1, 22, 3, 2]) + ] + messages = systems + [message for turn in turns for message in turn] + before = [message.model_dump() for message in messages] + + result = ContextTruncator().truncate_by_turns(messages, limit, drop_turns) + + assert result == systems + [ + message for turn in turns[-retained:] for message in turn + ] + assert [message.model_dump() for message in messages] == before + + def test_in_progress_user_counts_towards_turn_limit(self): + """An unanswered user input starts a new turn at the exact boundary.""" + messages = self.create_messages(4) + [self.create_message("user", "Current")] + + result = ContextTruncator().truncate_by_turns( + messages, keep_most_recent_turns=2 + ) + + assert result == messages[2:] + + @pytest.mark.parametrize("drop_turns", [1, 2, 20]) + def test_drop_oldest_removes_complete_tool_turns(self, drop_turns): + """Dropping turns never splits a tool chain or removes the latest turn.""" + systems = [ + self.create_message("system", "Persona"), + self.create_message("system", "Memo"), + ] + turns = [ + self.create_tool_turn(count, f"task-{i}") + for i, count in enumerate([22, 3, 2]) + ] + messages = systems + [message for turn in turns for message in turn] + before = [message.model_dump() for message in messages] + + result = ContextTruncator().truncate_by_dropping_oldest_turns( + messages, drop_turns + ) + + assert result == systems + [ + message for turn in turns[min(drop_turns, 2) :] for message in turn + ] + assert [message.model_dump() for message in messages] == before + + def test_dropping_sole_tool_turn_preserves_entire_turn(self): + """Keep the current task intact when there is no older turn to remove.""" + messages = [ + self.create_message("system", "Persona"), + *self.create_tool_turn(22), + ] + + result = ContextTruncator().truncate_by_dropping_oldest_turns(messages, 10) + + assert result == messages + + @pytest.mark.parametrize("limit, drop_turns", [(0, 1), (1, 10)]) + def test_nonpositive_retention_keeps_latest_complete_turn(self, limit, drop_turns): + """Always retain the latest turn instead of reinserting an unrelated old user.""" + older = self.create_tool_turn(1, "old") + latest = self.create_tool_turn(3, "current") + + result = ContextTruncator().truncate_by_turns(older + latest, limit, drop_turns) + + assert result == latest + + @pytest.mark.parametrize( + "method", ["truncate_by_turns", "truncate_by_dropping_oldest_turns"] + ) + @pytest.mark.parametrize("system_count", [0, 1, 3]) + def test_round_truncation_preserves_empty_and_system_only_context( + self, method, system_count + ): + """Do not count or delete a leading system-only context as a turn.""" + messages = [ + self.create_message("system", f"System {i}") for i in range(system_count) + ] + truncator = ContextTruncator() + if method == "truncate_by_turns": + result = truncator.truncate_by_turns(messages, keep_most_recent_turns=0) + else: + result = truncator.truncate_by_dropping_oldest_turns( + messages, drop_turns=10 + ) + + assert result == messages + + @pytest.mark.parametrize("drop_turns", [0, 1, 2]) + def test_turn_limit_ignores_pre_user_fragment(self, drop_turns): + """Do not count an assistant/tool prelude or retain it after truncation.""" + systems = [self.create_message("system", "Persona")] + prelude = self.create_tool_turn(1, "prelude")[1:] + turns = [self.create_tool_turn(1, f"task-{i}") for i in range(3)] + messages = systems + prelude + [msg for turn in turns for msg in turn] + truncator = ContextTruncator() + + assert truncator.truncate_by_turns(messages, 3) is messages + result = truncator.truncate_by_turns(messages, 2, drop_turns) + + retained = max(1, 3 - drop_turns) + assert result == systems + [msg for turn in turns[-retained:] for msg in turn] + assert result[len(systems)].role == "user" + + @pytest.mark.parametrize("drop_turns", [1, 2, 10]) + def test_drop_oldest_does_not_count_pre_user_fragment(self, drop_turns): + """A pre-user fragment never uses up a requested whole-turn drop.""" + systems = [self.create_message("system", "Persona")] + prelude = self.create_tool_turn(1, "prelude")[1:] + turns = [self.create_tool_turn(1, f"task-{i}") for i in range(3)] + messages = systems + prelude + [msg for turn in turns for msg in turn] + + result = ContextTruncator().truncate_by_dropping_oldest_turns( + messages, drop_turns + ) + + assert result == systems + [ + msg for turn in turns[min(drop_turns, 2) :] for msg in turn + ] + + @pytest.mark.parametrize("method", ["limit", "drop"]) + def test_internal_user_messages_stay_with_their_originating_turn(self, method): + """Keep and drop persisted internal user messages with the actual request.""" + current = load_messages( + [ + {"role": "user", "content": "Inspect the output"}, + {"role": "assistant", "content": "Working"}, + {"role": "user", "content": "Tool image", "_turn_continuation": True}, + {"role": "assistant", "content": "Image reviewed"}, + {"role": "user", "content": "Step limit", "_turn_continuation": True}, + ] + ) + older = self.create_tool_turn(1, "old") + messages = older + current + truncator = ContextTruncator() + + if method == "limit": + assert truncator.truncate_by_turns(messages, 2) is messages + assert truncator.truncate_by_turns(messages, 1) == current + else: + assert truncator.truncate_by_dropping_oldest_turns(messages, 1) == current + + next_turn = self.create_tool_turn(1, "next") + assert ( + truncator.truncate_by_dropping_oldest_turns(current + next_turn, 1) + == next_turn + ) + # ==================== fix_messages Tests ==================== def test_fix_messages_empty_list(self): @@ -81,8 +293,7 @@ def test_truncate_by_turns_basic(self): messages, keep_most_recent_turns=3, drop_turns=1 ) - # Should keep 3 most recent turns (6 messages) - assert len(result) <= 8 # (3-1+1)*2 = 6, but may adjust for correct format + assert result == messages[-6:] def test_truncate_by_turns_with_system_message(self): """Test truncate_by_turns preserves system messages.""" @@ -104,9 +315,8 @@ def test_truncate_by_turns_zero_keep(self): messages, keep_most_recent_turns=0, drop_turns=1 ) - # 截断后至少保留一条 user 消息 (#6196) - assert len(result) >= 1 - assert result[0].role == "user" + # Keep the latest complete turn even when the configured limit is zero. + assert result == messages[-2:] def test_truncate_by_turns_below_threshold(self): """Test truncate_by_turns when messages are below threshold.""" @@ -154,8 +364,8 @@ def test_truncate_by_turns_multiple_drop(self): messages, keep_most_recent_turns=5, drop_turns=3 ) - # Should drop 3 turns when limit exceeded - assert len(result) < len(messages) + # Preserve the existing retention target: 5 - 3 + 1 = 3 turns. + assert result == messages[-6:] # ==================== truncate_by_dropping_oldest_turns Tests ==================== @@ -202,9 +412,7 @@ def test_truncate_by_dropping_oldest_turns_drop_all(self): messages = self.create_messages(4) result = truncator.truncate_by_dropping_oldest_turns(messages, drop_turns=2) - # 即使 drop 掉所有 turn,也会把 user 消息补回来 (#6196) - assert len(result) >= 1 - assert result[0].role == "user" + assert result == messages[-2:] def test_truncate_by_dropping_oldest_turns_drop_more_than_available(self): """Test truncate_by_dropping_oldest_turns with drop_turns > available turns.""" @@ -213,9 +421,7 @@ def test_truncate_by_dropping_oldest_turns_drop_more_than_available(self): messages = self.create_messages(4) result = truncator.truncate_by_dropping_oldest_turns(messages, drop_turns=5) - # 同理,user 消息会被保留 (#6196) - assert len(result) >= 1 - assert result[0].role == "user" + assert result == messages[-2:] def test_truncate_by_dropping_oldest_turns_ensures_user_first(self): """Test that result starts with user message after dropping.""" diff --git a/tests/test_agent_history.py b/tests/test_agent_history.py index 269825aac3..9d498c50ee 100644 --- a/tests/test_agent_history.py +++ b/tests/test_agent_history.py @@ -48,6 +48,30 @@ def test_working_messages_round_trip_preserves_temporary_markers(): ] +@pytest.mark.parametrize("include_temporary", [False, True]) +def test_turn_continuation_survives_history_without_provider_metadata( + include_temporary, +): + """Retain internal turn boundaries in storage but omit them from API messages.""" + history = [ + {"role": "user", "content": "Actual request"}, + {"role": "user", "content": "Internal notice", "_turn_continuation": True}, + {"role": "assistant", "content": "Done"}, + ] + messages = load_messages(history) + + assert messages[0]._turn_continuation is False + assert messages[1]._turn_continuation is True + assert dump_messages(messages, include_temporary=include_temporary) == history + expected = [ + {key: value for key, value in item.items() if key != "_turn_continuation"} + for item in history + ] + assert Provider._ensure_message_to_dicts(object(), messages) == expected + assert Provider._ensure_message_to_dicts(object(), history) == expected + assert history[1]["_turn_continuation"] is True + + def test_dump_messages_filters_temp_content_parts(): messages = [ Message( diff --git a/tests/test_tool_loop_agent_runner.py b/tests/test_tool_loop_agent_runner.py index 5665a254d8..b9d069803c 100644 --- a/tests/test_tool_loop_agent_runner.py +++ b/tests/test_tool_loop_agent_runner.py @@ -2248,6 +2248,168 @@ async def test_follow_up_after_stop_not_added_to_context( pytest.main([__file__, "-v"]) +@pytest.mark.asyncio +@pytest.mark.parametrize("streaming", [False, True]) +async def test_turn_limit_preserves_long_tool_history_on_next_saved_reply( + tmp_path, runner, mock_provider, mock_tool_executor, mock_hooks, streaming +): + """Keep a completed tool-heavy turn when the next reply is persisted.""" + from astrbot.core.agent.conversation_events import ConversationEventWriter + from astrbot.core.agent.message import ToolCall, dump_messages + from astrbot.core.db.sqlite import SQLiteDatabase + + previous = [ + Message(role="system", content="Earlier memory"), + Message(role="user", content="Inspect the files"), + ] + # Seventeen batches and twenty-two calls produce forty-one non-system messages. + for batch, width in enumerate([2, 1, 1, 2, 1, 2, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1]): + calls = [ + ToolCall( + id=f"read-{batch}-{i}", + function=ToolCall.FunctionBody(name="read", arguments="{}"), + ) + for i in range(width) + ] + previous.append(Message(role="assistant", tool_calls=calls)) + previous.extend( + Message(role="tool", tool_call_id=call.id, content="File contents") + for call in calls + ) + previous.append(Message(role="assistant", content="Inspection complete")) + initial_history = dump_messages(previous) + assert len(initial_history) == 42 + + db = SQLiteDatabase(str(tmp_path / "logical_turn_history.db")) + await db.initialize() + try: + conv = await db.create_conversation("umo", "p") + writer = ConversationEventWriter( + db.conversation_store, + await db.conversation_store.read(conv.conversation_id), + ) + await writer.save_history(initial_history) + mock_provider.should_call_tools = False + await runner.reset( + provider=mock_provider, + request=ProviderRequest(prompt="Continue", contexts=writer.get_messages()), + run_context=ContextWrapper(context=None), + tool_executor=mock_tool_executor, + agent_hooks=mock_hooks, + streaming=streaming, + enforce_max_turns=20, + conversation_event_sink=writer.consume, + ) + await writer.start_turn({"kind": "agent"}) + + await collect_events(runner.step_until_done(3)) + await writer.save_history(dump_messages(runner.run_context.messages)) + await writer.finish_turn("completed") + + history = (await db.conversation_store.read(conv.conversation_id)).messages + assert history[:42] == initial_history + assert [message["role"] for message in history[42:]] == ["user", "assistant"] + assert len(history) == 44 + assert mock_provider.call_count == 1 + finally: + await db.engine.dispose() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streaming", [False, True]) +@pytest.mark.parametrize("internal_message", ["budget", "image"]) +async def test_internal_user_messages_preserve_current_turn_and_reloaded_history( + tmp_path, + runner, + provider_request, + mock_hooks, + monkeypatch, + streaming, + internal_message, +): + """A generated user-role message stays in its request across SQLite reloads.""" + from astrbot.core.agent.conversation_events import ConversationEventWriter + from astrbot.core.agent.message import dump_messages + from astrbot.core.agent.tool_image_cache import tool_image_cache + from astrbot.core.db.sqlite import SQLiteDatabase + + monkeypatch.setattr( + tool_image_cache, + "save_image", + lambda **kwargs: SimpleNamespace( + file_path="cached.png", mime_type="image/png", tool_name="test_tool" + ), + ) + monkeypatch.setattr( + tool_image_cache, + "get_image_base64_by_path", + lambda *args: ("dGVzdA==", "image/png"), + ) + db = SQLiteDatabase(str(tmp_path / "internal_turn_history.db")) + await db.initialize() + try: + conv = await db.create_conversation("umo", "p") + writer = ConversationEventWriter( + db.conversation_store, + await db.conversation_store.read(conv.conversation_id), + ) + provider = CapturingToolLoopProvider("test_tool") + await runner.reset( + provider=provider, + request=provider_request, + run_context=ContextWrapper(context=None), + tool_executor=MockMixedContentToolExecutor + if internal_message == "image" + else MockToolExecutor, + agent_hooks=mock_hooks, + streaming=streaming, + enforce_max_turns=1, + conversation_event_sink=writer.consume, + ) + original_request = runner.run_context.messages[0] + await writer.start_turn({"kind": "agent"}) + await collect_events( + runner.step_until_done(1 if internal_message == "budget" else 3) + ) + + final_context = provider.received_contexts[-1] + assert final_context[0] == original_request + assert [message.role for message in final_context] == [ + "user", + "assistant", + "tool", + "user", + ] + await writer.save_history(dump_messages(runner.run_context.messages)) + await writer.finish_turn("completed") + snapshot = await db.conversation_store.read(conv.conversation_id) + history = snapshot.messages + assert history[3]["_turn_continuation"] is True + assert history[0] == original_request.model_dump() + + writer = ConversationEventWriter(db.conversation_store, snapshot) + await runner.reset( + provider=provider, + request=ProviderRequest(prompt="Follow-up", contexts=writer.get_messages()), + run_context=ContextWrapper(context=None), + tool_executor=MockToolExecutor, + agent_hooks=mock_hooks, + streaming=streaming, + enforce_max_turns=2, + conversation_event_sink=writer.consume, + ) + await writer.start_turn({"kind": "agent"}) + await collect_events(runner.step_until_done(3)) + await writer.save_history(dump_messages(runner.run_context.messages)) + await writer.finish_turn("completed") + + saved = (await db.conversation_store.read(conv.conversation_id)).messages + assert saved[: len(history)] == history + assert len(saved) == len(history) + 2 + finally: + await db.engine.dispose() + + @pytest.mark.asyncio @pytest.mark.parametrize("streaming", [False, True]) async def test_event_journal_records_requests_tools_and_final_context( diff --git a/tests/unit/subagent/test_native.py b/tests/unit/subagent/test_native.py index f88f37d5e9..fb668e43fc 100644 --- a/tests/unit/subagent/test_native.py +++ b/tests/unit/subagent/test_native.py @@ -13,6 +13,46 @@ from astrbot.core.provider.entities import LLMResponse +@pytest.mark.asyncio +async def test_native_followup_preserves_internal_turn_boundaries_after_restore( + environment, +): + """Reloading delegated history must not promote an internal notice to a turn.""" + env = environment + selected = await env.save_agent("worker", config={"compression": {"max_turns": 2}}) + agent = await env.service.spawn( + env.root, [{"type": "plain", "text": "Initial"}], config_id=selected.config_id + ) + await env.service.wait(env.root, [agent["agent_id"]], 2000, "all") + record = env.store.get(agent["agent_id"], env.scope) + session = await env.native.open_session( + env.scope.umo, + session_id=record.conversation_id, + options={"profile": "subagent"}, + ) + history = [ + {"role": "user", "content": "Original request"}, + {"role": "user", "content": "Internal notice", "_turn_continuation": True}, + {"role": "assistant", "content": "Done"}, + ] + await session._commit_history(history, None) + await session.close() + + await env.service.send( + env.root, record.agent_id, [{"type": "plain", "text": "Continue"}] + ) + result = await env.service.wait(env.root, [record.agent_id], 2000, "all") + assert result["agents"][0]["state"] == "completed" + restored = await env.native.open_session( + env.scope.umo, + session_id=record.conversation_id, + options={"profile": "subagent"}, + ) + saved = await restored.history() + assert saved[: len(history)] == history + assert len(saved) == len(history) + 2 + + @pytest.mark.asyncio async def test_native_runtime_owns_computer_initialization_and_shutdown( environment, monkeypatch