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): Stop losing tool calls from session history on mid-turn flush (#13593)
Reinier van der Leer708082db3285
diff --git a/autogpt_platform/backend/backend/copilot/db.py b/autogpt_platform/backend/backend/copilot/db.pyindex 680c934496..c690f96b29 100644--- a/autogpt_platform/backend/backend/copilot/db.py+++ b/autogpt_platform/backend/backend/copilot/db.py@@ -787,6 +787,38 @@ async def update_message_content_by_sequence(return False+async def update_chat_message_tool_calls(+ session_id: str,+ sequence: int,+ tool_calls: list[dict[str, Any]],+) -> bool:+ """Back-fill ``toolCalls`` on an already-persisted message row.++ The streaming flush can persist an assistant row (assigning its sequence)+ before the turn's tool_use blocks arrive; this updates the row so the tool+ activity survives in session history. Same authorization reasoning as+ ``update_message_content_by_sequence``.++ Returns:+ True if a message was updated, False if no row matched.++ Raises:+ Propagates Prisma/connection errors — the caller (the back-fill+ loop in ``_save_session_to_db``) owns the retry policy.+ """+ result = await PrismaChatMessage.prisma().update(+ where={"sessionId_sequence": {"sessionId": session_id, "sequence": sequence}},+ data={"toolCalls": SafeJson(tool_calls)},+ )+ if not result:+ logger.warning(+ f"No message found to update tool_calls for session "+ f"{session_id}, sequence {sequence}"+ )+ return False+ return True++async def set_turn_duration(session_id: str, duration_ms: int) -> None:"""Set durationMs on the last assistant message in a session.diff --git a/autogpt_platform/backend/backend/copilot/db_test.py b/autogpt_platform/backend/backend/copilot/db_test.pyindex 9138709829..20ee057e56 100644--- a/autogpt_platform/backend/backend/copilot/db_test.py+++ b/autogpt_platform/backend/backend/copilot/db_test.py@@ -16,6 +16,7 @@ from backend.copilot.db import (get_chat_messages_paginated,get_user_chat_sessions,set_turn_duration,+ update_chat_message_tool_calls,update_chat_session_pinned,update_message_content_by_sequence,)@@ -858,3 +859,44 @@ async def test_add_chat_message_omits_metadata_when_none() -> None:)data = create.call_args.kwargs["data"]assert "metadata" not in data+++# ---------- update_chat_message_tool_calls ----------++_TOOL_CALLS = [+ {+ "id": "c1",+ "type": "function",+ "function": {"name": "web_search", "arguments": "{}"},+ }+]+++async def test_update_chat_message_tool_calls_success():+ """Returns True when the unique-keyed update finds the row."""+ with patch.object(PrismaChatMessage, "prisma") as mock_prisma:+ mock_prisma.return_value.update = AsyncMock(return_value=object())++ result = await update_chat_message_tool_calls("sess-1", 7, _TOOL_CALLS)++ assert result is True+ where = mock_prisma.return_value.update.call_args.kwargs["where"]+ assert where == {"sessionId_sequence": {"sessionId": "sess-1", "sequence": 7}}+ payload = mock_prisma.return_value.update.call_args.kwargs["data"]["toolCalls"]+ assert payload.data == _TOOL_CALLS+++async def test_update_chat_message_tool_calls_not_found():+ """Returns False (so the caller's pending-save flag stays set) when no row matches."""+ with (+ patch.object(PrismaChatMessage, "prisma") as mock_prisma,+ patch("backend.copilot.db.logger") as mock_logger,+ ):+ mock_prisma.return_value.update = AsyncMock(return_value=None)++ result = await update_chat_message_tool_calls("sess-1", 99, _TOOL_CALLS)++ assert result is False+ mock_logger.warning.assert_called_once()diff --git a/autogpt_platform/backend/backend/copilot/model.py b/autogpt_platform/backend/backend/copilot/model.pyindex 8a91cb0209..1821ef9ba0 100644--- a/autogpt_platform/backend/backend/copilot/model.py+++ b/autogpt_platform/backend/backend/copilot/model.py@@ -1,3 +1,4 @@+import asyncioimport loggingimport uuidfrom contextlib import asynccontextmanager@@ -21,7 +22,7 @@ from openai.types.chat.chat_completion_message_tool_call_param import (from prisma.errors import UniqueViolationErrorfrom prisma.models import ChatMessage as PrismaChatMessagefrom prisma.models import ChatSession as PrismaChatSession-from pydantic import BaseModel, PrivateAttr+from pydantic import BaseModel, Field, PrivateAttrfrom backend.data.db_accessors import chat_db, library_dbfrom backend.data.graph import GraphSettings@@ -104,6 +105,33 @@ class ChatMessage(BaseModel):duration_ms: int | None = Nonecreated_at: datetime | None = None+ tool_calls_pending_save: bool = Field(default=False, exclude=True)+ """True when ``tool_calls`` mutated after this row was already persisted.++ An assistant row is often flushed to the DB (getting its ``sequence``)+ while its text streams, BEFORE the turn's tool_use blocks arrive — the+ save path only inserts ``sequence is None`` rows, so late-attached+ tool_calls would otherwise never reach the DB and the tool activity+ becomes invisible in session history. ``_save_session_to_db`` back-fills+ rows flagged here and clears the flag.++ In-memory only (``exclude=True``) by necessity, not oversight: the flag+ marks tool_calls content that exists ONLY in this process — if the+ worker dies before a back-fill succeeds, the content is gone with it,+ so a persisted flag would have nothing left to back-fill from. Residual+ window: a back-fill failure on the turn's final save is retried on any+ later save of the session, but not across a worker restart."""++ def mark_tool_calls_pending_save(self) -> None:+ """Flag this row for a toolCalls back-fill if it was already+ persisted (has a sequence). The single invariant behind the+ mid-turn-flush fix: any site that mutates ``tool_calls`` on a+ possibly-sequenced message must call this — encapsulated here so a+ future third mutation site can't silently reintroduce the+ dropped-tool-calls bug."""+ if self.sequence is not None:+ self.tool_calls_pending_save = True+# Owning session id and generic per-row JSONB bag. Today the# dispatcher uses ``metadata`` to preserve the submit-time payload# (file_ids / mode / model / permissions / context / arrival_at)@@ -408,6 +436,7 @@ class ChatSession(ChatSessionInfo):if not msg.tool_calls:msg.tool_calls = []msg.tool_calls.append(tool_call)+ msg.mark_tool_calls_pending_save()returnself.messages.append(@@ -892,6 +921,46 @@ async def _save_session_to_db()for i, msg in enumerate(new_messages):msg.sequence = actual_start + i+ msg.tool_calls_pending_save = False++ # Back-fill tool_calls onto rows that were flushed before their+ # tool_use blocks arrived (see ChatMessage.tool_calls_pending_save).+ # Save-ordering invariant: this only repairs the row if a save runs+ # AFTER the tool_use blocks arrive. That is guaranteed by the end-of-turn+ # save (every turn ends with save_chat_session, including the error paths+ # that append an error marker) — mid-turn flushes merely narrow the+ # window. On failure the flag stays set so any later save retries.+ pending = [+ m+ for m in session.messages+ if m.tool_calls_pending_save and m.sequence is not None+ ]++ async def _backfill(msg: ChatMessage) -> None:+ assert msg.sequence is not None # narrowed by the filter above+ try:+ updated = await db.update_chat_message_tool_calls(+ session_id=session.session_id,+ sequence=msg.sequence,+ tool_calls=msg.tool_calls or [],+ )+ except Exception as e:+ logger.error(+ f"Failed to back-fill tool_calls for session "+ f"{session.session_id} seq {msg.sequence}: {e}"+ )+ return++ if updated:+ msg.tool_calls_pending_save = False+ else:+ logger.warning(+ f"Failed to back-fill tool_calls for session "+ f"{session.session_id} seq {msg.sequence} (row not found)"+ )++ if pending:+ await asyncio.gather(*(_backfill(m) for m in pending))async def append_and_save_message(diff --git a/autogpt_platform/backend/backend/copilot/model_test.py b/autogpt_platform/backend/backend/copilot/model_test.pyindex d1973d7fce..b14f4121da 100644--- a/autogpt_platform/backend/backend/copilot/model_test.py+++ b/autogpt_platform/backend/backend/copilot/model_test.py@@ -1005,6 +1005,124 @@ async def test_save_session_to_db_persists_new_messages_when_windowed(assert new_msg.sequence == 1500[email protected](loop_scope="session")+async def test_save_session_to_db_backfills_late_tool_calls(+ mocker: MockerFixture,+) -> None:+ """An assistant row flushed before its tool_use blocks arrived gets its+ toolCalls back-filled on the next save, and the pending-save flag cleared."""+ calls = [+ {+ "id": "c1",+ "type": "function",+ "function": {"name": "find_block", "arguments": "{}"},+ }+ ]+ flushed = ChatMessage(+ role="assistant",+ content="Searching...",+ sequence=7,+ tool_calls=calls,+ tool_calls_pending_save=True,+ )+ session = _make_session_with_messages(flushed)++ mock_db = mocker.MagicMock()+ mock_db.update_chat_session = mocker.AsyncMock()+ mock_db.add_chat_messages_batch = mocker.AsyncMock(return_value=8)+ mock_db.update_chat_message_tool_calls = mocker.AsyncMock(return_value=True)+ mocker.patch("backend.copilot.model.chat_db", return_value=mock_db)++ await _save_session_to_db(+ session, existing_message_count=8, skip_existence_check=True+ )++ mock_db.add_chat_messages_batch.assert_not_awaited()+ mock_db.update_chat_message_tool_calls.assert_awaited_once_with(+ session_id=session.session_id, sequence=7, tool_calls=calls+ )+ assert flushed.tool_calls_pending_save is False++[email protected](loop_scope="session")+async def test_save_session_to_db_new_rows_persist_tool_calls_without_backfill(+ mocker: MockerFixture,+) -> None:+ """A not-yet-saved row keeps its tool_calls on the normal insert path —+ no back-fill update is issued and the flag is cleared by the save."""+ calls = [+ {+ "id": "c2",+ "type": "function",+ "function": {"name": "bash_exec", "arguments": "{}"},+ }+ ]+ new_msg = ChatMessage(+ role="assistant",+ content="Running...",+ tool_calls=calls,+ tool_calls_pending_save=True,+ )+ session = _make_session_with_messages(new_msg)++ mock_db = mocker.MagicMock()+ mock_db.update_chat_session = mocker.AsyncMock()+ mock_db.add_chat_messages_batch = mocker.AsyncMock(return_value=0)+ mock_db.update_chat_message_tool_calls = mocker.AsyncMock(return_value=True)+ mocker.patch("backend.copilot.model.chat_db", return_value=mock_db)++ await _save_session_to_db(+ session, existing_message_count=0, skip_existence_check=True+ )++ saved = mock_db.add_chat_messages_batch.call_args.kwargs["messages"]+ assert saved[0]["tool_calls"] == calls+ mock_db.update_chat_message_tool_calls.assert_not_awaited()+ assert new_msg.tool_calls_pending_save is False++[email protected](loop_scope="session")+async def test_save_session_to_db_backfill_failure_keeps_flag_set(+ mocker: MockerFixture,+) -> None:+ """When the back-fill UPDATE fails, the pending-save flag must stay set so a+ later save retries — this retention-on-failure is the fix's safety net."""+ calls = [+ {+ "id": "c3",+ "type": "function",+ "function": {"name": "web_search", "arguments": "{}"},+ }+ ]+ flushed = ChatMessage(+ role="assistant",+ content="Searching...",+ sequence=7,+ tool_calls=calls,+ tool_calls_pending_save=True,+ )+ session = _make_session_with_messages(flushed)++ mock_db = mocker.MagicMock()+ mock_db.update_chat_session = mocker.AsyncMock()+ mock_db.add_chat_messages_batch = mocker.AsyncMock(return_value=8)+ mock_db.update_chat_message_tool_calls = mocker.AsyncMock(return_value=False)+ mocker.patch("backend.copilot.model.chat_db", return_value=mock_db)++ await _save_session_to_db(+ session, existing_message_count=8, skip_existence_check=True+ )++ assert flushed.tool_calls_pending_save is True++ # A later save retries the back-fill; on success the flag clears.+ mock_db.update_chat_message_tool_calls = mocker.AsyncMock(return_value=True)+ await _save_session_to_db(+ session, existing_message_count=8, skip_existence_check=True+ )+ assert flushed.tool_calls_pending_save is False++# ─── _get_session_from_db cap-hit warning ──────────────────────────────@@ -1351,3 +1469,107 @@ def test_chat_session_new_carries_org_team():tenantless = ChatSession.new("u1", dry_run=False)assert tenantless.organization_id is Noneassert tenantless.team_id is None+++def test_add_tool_call_to_sequenced_row_flags_backfill():+ """Attaching a tool_call to an already-persisted assistant row must set+ the pending-save flag so the next save back-fills toolCalls (baseline path)."""+ session = _make_session_with_messages(+ ChatMessage(role="assistant", content="working...", sequence=42)+ )+ session.add_tool_call_to_current_turn(+ {"id": "c1", "type": "function", "function": {"name": "f", "arguments": "{}"}}+ )+ assert session.messages[-1].tool_calls_pending_save is True++ fresh = _make_session_with_messages(+ ChatMessage(role="assistant", content="working...")+ )+ fresh.add_tool_call_to_current_turn(+ {"id": "c2", "type": "function", "function": {"name": "f", "arguments": "{}"}}+ )+ assert fresh.messages[-1].tool_calls_pending_save is False++[email protected](loop_scope="session")+async def test_backfill_exception_keeps_flag_and_save_survives(+ mocker: MockerFixture,+) -> None:+ """A raising back-fill must not fail the save, and the pending-save flag stays+ set so a later save retries — the retry safety net for the crash case."""+ flushed = ChatMessage(+ role="assistant",+ content="working...",+ sequence=7,+ tool_calls=[+ {+ "id": "c1",+ "type": "function",+ "function": {"name": "f", "arguments": "{}"},+ }+ ],+ tool_calls_pending_save=True,+ )+ session = _make_session_with_messages(flushed)++ mock_db = mocker.MagicMock()+ mock_db.update_chat_session = mocker.AsyncMock()+ mock_db.add_chat_messages_batch = mocker.AsyncMock(return_value=8)+ mock_db.update_chat_message_tool_calls = mocker.AsyncMock(+ side_effect=RuntimeError("db down")+ )+ mocker.patch("backend.copilot.model.chat_db", return_value=mock_db)++ await _save_session_to_db(+ session, existing_message_count=8, skip_existence_check=True+ )++ assert flushed.tool_calls_pending_save is True++[email protected](loop_scope="session")+async def test_backfill_partial_failure_clears_only_successes(+ mocker: MockerFixture,+) -> None:+ """Three pending rows fan out concurrently; one raises, one reports+ not-found — only the successful row's flag clears."""++ def _msg(seq: int) -> ChatMessage:+ return ChatMessage(+ role="assistant",+ content=f"m{seq}",+ sequence=seq,+ tool_calls=[+ {+ "id": f"c{seq}",+ "type": "function",+ "function": {"name": "f", "arguments": "{}"},+ }+ ],+ tool_calls_pending_save=True,+ )++ m1, m2, m3 = _msg(1), _msg(2), _msg(3)+ session = _make_session_with_messages(m1, m2, m3)++ async def _by_sequence(session_id: str, sequence: int, tool_calls):+ if sequence == 1:+ return True+ if sequence == 2:+ raise RuntimeError("db down")+ return False++ mock_db = mocker.MagicMock()+ mock_db.update_chat_session = mocker.AsyncMock()+ mock_db.add_chat_messages_batch = mocker.AsyncMock(return_value=4)+ mock_db.update_chat_message_tool_calls = mocker.AsyncMock(side_effect=_by_sequence)+ mocker.patch("backend.copilot.model.chat_db", return_value=mock_db)++ await _save_session_to_db(+ session, existing_message_count=4, skip_existence_check=True+ )++ assert m1.tool_calls_pending_save is False+ assert m2.tool_calls_pending_save is True+ assert m3.tool_calls_pending_save is True+ assert mock_db.update_chat_message_tool_calls.await_count == 3diff --git a/autogpt_platform/backend/backend/copilot/sdk/interrupted_partial_test.py b/autogpt_platform/backend/backend/copilot/sdk/interrupted_partial_test.pyindex 0903af970e..06bc7fab79 100644--- a/autogpt_platform/backend/backend/copilot/sdk/interrupted_partial_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/interrupted_partial_test.py@@ -224,6 +224,35 @@ class TestFlushOrphanToolUses:adapter.flush_unresolved_tool_calls.assert_not_called()assert events == []+ def test_persists_tool_name_on_synthetic_rows(self):+ session = _make_session()+ state = _adapter_with_unresolved([_tool_output("t1", "r1")])+ _flush_orphan_tool_uses_to_session(session, state)+ assert session.messages[0].name == "t"++ def test_nameless_output_falls_back_to_matching_tool_call(self):+ session = _make_session(+ [+ ChatMessage(+ role="assistant",+ content="",+ tool_calls=[+ {+ "id": "t1",+ "type": "function",+ "function": {"name": "web_search", "arguments": "{}"},+ }+ ],+ )+ ]+ )+ flushed = [+ StreamToolOutputAvailable(toolCallId="t1", toolName=None, output="r1")+ ]+ state = _adapter_with_unresolved(flushed)+ _flush_orphan_tool_uses_to_session(session, state)+ assert session.messages[-1].name == "web_search"+class TestClassifyFinalFailure:"""Ensures the history marker (via finalize) and the SSE StreamError yielddiff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.pyindex 9519023969..27347045bb 100644--- a/autogpt_platform/backend/backend/copilot/sdk/service.py+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py@@ -1532,11 +1532,46 @@ def _flush_orphan_tool_uses_to_session(else json.dumps(resp.output, ensure_ascii=False))session.messages.append(- ChatMessage(role="tool", content=content, tool_call_id=resp.toolCallId)+ ChatMessage(+ role="tool",+ content=content,+ tool_call_id=resp.toolCallId,+ name=_resolve_tool_result_name(+ session, resp.toolCallId, resp.toolName+ ),+ ))return safety+def _resolve_tool_result_name(+ session: "ChatSession",+ tool_call_id: str,+ tool_name: str | None,+) -> str | None:+ """Name for a persisted tool-result row, falling back to the matching+ assistant ``tool_call`` — a nameless row is unidentifiable in history,+ which is the exact defect the ``name`` column exists to fix."""+ if tool_name:+ return tool_name+ for msg in reversed(session.messages):+ for tc in msg.tool_calls or []:+ if tc.get("id") == tool_call_id:+ if name := tc.get("function", {}).get("name"):+ return name+ logger.warning(+ f"Persisting nameless tool-result row for session "+ f"{session.session_id}: matching tool_call "+ f"{tool_call_id} has no function name"+ )+ return None+ logger.warning(+ f"Persisting nameless tool-result row for session {session.session_id}: "+ f"no name provided and no matching tool_call {tool_call_id} in history"+ )+ return None++@dataclass(frozen=True)class _FinalFailure:"""Display message + stream code + retryable flag for a final-failure exit.@@ -3069,6 +3104,7 @@ def _dispatch_response(})acc.assistant_response.tool_calls = acc.accumulated_tool_calls+ acc.assistant_response.mark_tool_calls_pending_save()if not acc.has_appended_assistant:ctx.session.messages.append(acc.assistant_response)acc.has_appended_assistant = True@@ -3107,6 +3143,9 @@ def _dispatch_response(role="tool",content=content,tool_call_id=response.toolCallId,+ name=_resolve_tool_result_name(+ ctx.session, response.toolCallId, response.toolName+ ),))if not entries_replaced:diff --git a/autogpt_platform/backend/backend/copilot/sdk/session_persistence_test.py b/autogpt_platform/backend/backend/copilot/sdk/session_persistence_test.pyindex 377469f971..6d09df3fc6 100644--- a/autogpt_platform/backend/backend/copilot/sdk/session_persistence_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/session_persistence_test.py@@ -16,9 +16,12 @@ state allows correct content accumulation by _dispatch_response.from __future__ import annotations+import loggingfrom datetime import datetime, timezonefrom unittest.mock import MagicMock+import pytest+from backend.copilot.constants import (STOPPED_BY_USER_MARKER,STREAM_ERROR_MARKER,@@ -29,10 +32,12 @@ from backend.copilot.response_model import (StreamStartStep,StreamTextDelta,StreamToolInputAvailable,+ StreamToolOutputAvailable,)from backend.copilot.sdk.service import (_dispatch_response,_intermediate_flush_blocked,+ _resolve_tool_result_name,_StreamAccumulator,)from backend.copilot.session_cleanup import prune_orphan_tool_calls@@ -594,3 +599,131 @@ class TestIntermediateFlushBlocked:session.messages[0].tool_calls[0]["function"]["name"]== "setup_agent_webhook_trigger")+++class TestLateToolCallPersistence:+ """Tool calls arriving after the assistant row was flushed to the DB must+ be flagged for back-fill, and tool-result rows must carry the tool name —+ otherwise the tool activity is invisible in session history (both UIs+ render from toolCalls / name)."""++ def _acc_with_appended_assistant(+ self, ctx: MagicMock, *, sequence: int | None+ ) -> _StreamAccumulator:+ msg = ChatMessage(role="assistant", content="Working...", sequence=sequence)+ ctx.session.messages.append(msg)+ return _StreamAccumulator(+ assistant_response=msg,+ accumulated_tool_calls=[],+ has_appended_assistant=True,+ has_tool_results=False,+ )++ def test_tool_call_after_flush_flags_row_for_backfill(self) -> None:+ ctx = _make_ctx()+ state = _make_state()+ acc = self._acc_with_appended_assistant(ctx, sequence=42)++ ev = StreamToolInputAvailable(+ toolCallId="c1", toolName="find_block", input={"query": "notion"}+ )+ _dispatch_response(ev, acc, ctx, state, False, "[test]")++ assert acc.assistant_response.tool_calls is not None+ assert acc.assistant_response.tool_calls[0]["function"]["name"] == "find_block"+ assert acc.assistant_response.tool_calls_pending_save is True++ def test_tool_call_before_flush_is_not_flagged(self) -> None:+ """Unsaved rows (sequence None) are persisted with their tool_calls by+ the normal insert path — no back-fill needed."""+ ctx = _make_ctx()+ state = _make_state()+ acc = self._acc_with_appended_assistant(ctx, sequence=None)++ ev = StreamToolInputAvailable(toolCallId="c1", toolName="find_block", input={})+ _dispatch_response(ev, acc, ctx, state, False, "[test]")++ assert acc.assistant_response.tool_calls is not None+ assert acc.assistant_response.tool_calls_pending_save is False++ def test_tool_result_row_carries_tool_name(self) -> None:+ ctx = _make_ctx()+ state = _make_state()+ acc = self._acc_with_appended_assistant(ctx, sequence=None)++ ev = StreamToolOutputAvailable(+ toolCallId="c1", toolName="find_block", output="found 3 blocks"+ )+ _dispatch_response(ev, acc, ctx, state, False, "[test]")++ tool_rows = [m for m in ctx.session.messages if m.role == "tool"]+ assert len(tool_rows) == 1+ assert tool_rows[0].name == "find_block"+ assert tool_rows[0].tool_call_id == "c1"++ def test_nameless_tool_result_resolves_name_from_matching_call(self) -> None:+ ctx = _make_ctx()+ state = _make_state()+ acc = self._acc_with_appended_assistant(ctx, sequence=None)+ acc.assistant_response.tool_calls = [+ {"id": "c1", "type": "function", "function": {"name": "run_agent"}}+ ]++ ev = StreamToolOutputAvailable(toolCallId="c1", toolName=None, output="done")+ _dispatch_response(ev, acc, ctx, state, False, "[test]")++ tool_rows = [m for m in ctx.session.messages if m.role == "tool"]+ assert len(tool_rows) == 1+ assert tool_rows[0].name == "run_agent"++ def test_nameless_tool_result_with_no_matching_call_warns(+ self, caplog: pytest.LogCaptureFixture+ ) -> None:+ """No adapter name AND no matching tool_call in history: the row is+ persisted nameless (nothing to resolve from), but loudly."""+ ctx = _make_ctx()+ state = _make_state()+ acc = self._acc_with_appended_assistant(ctx, sequence=None)++ ev = StreamToolOutputAvailable(toolCallId="ghost", toolName=None, output="?")+ with caplog.at_level(logging.WARNING):+ _dispatch_response(ev, acc, ctx, state, False, "[test]")++ tool_rows = [m for m in ctx.session.messages if m.role == "tool"]+ assert len(tool_rows) == 1+ assert tool_rows[0].name is None+ assert any("nameless tool-result" in r.message for r in caplog.records)++ def test_resolve_tool_result_name_matched_but_nameless_call_warns(+ self, caplog: pytest.LogCaptureFixture+ ) -> None:+ """A matching tool_call whose function dict carries no name must not+ bypass the nameless warning."""+ session = _make_session()+ session.messages.append(+ ChatMessage(+ role="assistant",+ content="",+ tool_calls=[{"id": "c1", "type": "function", "function": {}}],+ )+ )+ with caplog.at_level(logging.WARNING):+ assert _resolve_tool_result_name(session, "c1", None) is None+ assert any("has no function name" in r.message for r in caplog.records)++ def test_resolve_tool_result_name_no_match_returns_none(+ self, caplog: pytest.LogCaptureFixture+ ) -> None:+ session = _make_session()+ session.messages.append(+ ChatMessage(+ role="assistant",+ content="",+ tool_calls=[+ {"id": "other", "type": "function", "function": {"name": "x"}}+ ],+ )+ )+ with caplog.at_level(logging.WARNING):+ assert _resolve_tool_result_name(session, "missing", None) is None+ assert any("nameless tool-result" in r.message for r in caplog.records)diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.pyindex 7035cb676e..d4361e1ed4 100644--- a/autogpt_platform/backend/backend/data/db_manager.py+++ b/autogpt_platform/backend/backend/data/db_manager.py@@ -488,6 +488,7 @@ class DatabaseManager(AppService):get_next_sequence = _(chat_db.get_next_sequence)update_tool_message_content = _(chat_db.update_tool_message_content)update_message_content_by_sequence = _(chat_db.update_message_content_by_sequence)+ update_chat_message_tool_calls = _(chat_db.update_chat_message_tool_calls)update_chat_session_title = _(chat_db.update_chat_session_title)update_chat_session_pinned = _(chat_db.update_chat_session_pinned)set_turn_duration = _(chat_db.set_turn_duration)@@ -761,6 +762,7 @@ class DatabaseManagerAsyncClient(AppServiceClient):get_next_sequence = d.get_next_sequenceupdate_tool_message_content = d.update_tool_message_contentupdate_message_content_by_sequence = d.update_message_content_by_sequence+ update_chat_message_tool_calls = d.update_chat_message_tool_callsupdate_chat_session_title = d.update_chat_session_titleupdate_chat_session_pinned = d.update_chat_session_pinnedset_turn_duration = d.set_turn_duration