Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
test: migrate agent runtime sessions and ORM models to SQLite (#40587)
Asuka Minatof2dfa462e140
diff --git a/api/tests/unit_tests/core/agent/test_cot_agent_runner.py b/api/tests/unit_tests/core/agent/test_cot_agent_runner.pyindex 4f3c7bbc3b5..9537d4387c6 100644--- a/api/tests/unit_tests/core/agent/test_cot_agent_runner.py+++ b/api/tests/unit_tests/core/agent/test_cot_agent_runner.py@@ -1,9 +1,11 @@import jsonfrom collections.abc import Iterator+from decimal import Decimalfrom unittest.mock import MagicMockimport pytestfrom pytest_mock import MockerFixture+from sqlalchemy import eventfrom sqlalchemy.engine import Enginefrom sqlalchemy.orm import Session@@ -11,6 +13,38 @@ from core.agent.cot_agent_runner import CotAgentRunnerfrom core.agent.entities import AgentScratchpadUnitfrom core.agent.errors import AgentMaxIterationErrorfrom graphon.model_runtime.entities.llm_entities import LLMUsage+from libs.datetime_utils import naive_utc_now+from models.enums import ConversationFromSource, MessageStatus+from models.model import AppMode, Conversation, Message+++def _make_conversation(*, conversation_id: str = "conv1") -> Conversation:+ return Conversation(+ id=conversation_id,+ app_id="app",+ mode=AppMode.AGENT_CHAT,+ name="Agent Conversation",+ inputs={},+ from_source=ConversationFromSource.API,+ )+++def _make_message(*, message_id: str = "msg-id", conversation_id: str = "conv1") -> Message:+ return Message(+ id=message_id,+ app_id="app",+ conversation_id=conversation_id,+ inputs={},+ query="query",+ message={},+ answer="",+ status=MessageStatus.NORMAL,+ message_unit_price=Decimal(0),+ answer_unit_price=Decimal(0),+ currency="USD",+ from_source=ConversationFromSource.API,+ created_at=naive_utc_now(),+ )class DummyRunner(CotAgentRunner):@@ -59,12 +93,12 @@ def runner(mocker: MockerFixture, sqlite_engine: Engine) -> Iterator[DummyRunnermodel_config.model = "test-model"queue_manager = MagicMock()- message = MagicMock()+ message = _make_message()runner = DummyRunner(tenant_id="tenant",application_generate_entity=application_generate_entity,- conversation=MagicMock(),+ conversation=_make_conversation(),app_config=app_config,model_config=model_config,config=MagicMock(),@@ -200,7 +234,7 @@ class TestOrganizeHistoricPromptMessages:class TestRun:def test_run_handles_empty_parser_output(self, runner: DummyRunner, mocker: MockerFixture):- message = MagicMock()+ message = _make_message()message.id = "msg-id"mocker.patch(@@ -214,7 +248,7 @@ class TestRun:assert all("session" not in call.kwargs for call in runner.save_agent_thought.call_args_list)def test_run_with_action_and_tool_invocation(self, runner: DummyRunner, mocker: MockerFixture):- message = MagicMock()+ message = _make_message()message.id = "msg-id"action = AgentScratchpadUnit.Action(action_name="tool", action_input={})@@ -236,7 +270,7 @@ class TestRun:def test_run_respects_max_iteration_boundary(self, runner: DummyRunner, mocker: MockerFixture):runner.app_config.agent.max_iteration = 1- message = MagicMock()+ message = _make_message()message.id = "msg-id"action = AgentScratchpadUnit.Action(action_name="tool", action_input={})@@ -257,7 +291,7 @@ class TestRun:list(runner.run(runner.session, message, "query", {"tool": MagicMock()}))def test_run_basic_flow(self, runner: DummyRunner, mocker: MockerFixture):- message = MagicMock()+ message = _make_message()message.id = "msg-id"mocker.patch(@@ -270,7 +304,7 @@ class TestRun:def test_run_max_iteration_error(self, runner: DummyRunner, mocker: MockerFixture):runner.app_config.agent.max_iteration = 0- message = MagicMock()+ message = _make_message()message.id = "msg-id"action = AgentScratchpadUnit.Action(action_name="tool", action_input={})@@ -284,7 +318,7 @@ class TestRun:list(runner.run(runner.session, message, "query", {}))def test_run_increase_usage_aggregation(self, runner: DummyRunner, mocker: MockerFixture):- message = MagicMock()+ message = _make_message()message.id = "msg-id"runner.app_config.agent.max_iteration = 2@@ -341,23 +375,22 @@ class TestRun:assert final_usage.total_price == 4def test_run_when_no_action_branch(self, runner: DummyRunner, mocker: MockerFixture):- message = MagicMock()- message.id = "msg-id"events: list[str] = []session = runner.session- original_close = session.close- original_commit = session.commit-- def close_session() -> None:- events.append("close")- original_close()+ conversation = _make_conversation()+ message = _make_message(conversation_id=conversation.id)+ session.add_all([conversation, message])+ session.commit()- def commit_session() -> None:+ def record_commit(_session: Session) -> None:events.append("commit")- original_commit()- mocker.patch.object(session, "close", side_effect=close_session)- mocker.patch.object(session, "commit", side_effect=commit_session)+ def record_detach(_session: Session, instance: object) -> None:+ if instance is message:+ events.append("close")++ event.listen(session, "after_commit", record_commit)+ event.listen(session, "persistent_to_detached", record_detach)def provider_chunks():events.append("first-chunk")@@ -375,7 +408,7 @@ class TestRun:assert results[-1].delta.message.content == ""def test_run_usage_missing_key_branch(self, runner: DummyRunner, mocker: MockerFixture):- message = MagicMock()+ message = _make_message()message.id = "msg-id"mocker.patch(@@ -388,7 +421,7 @@ class TestRun:list(runner.run(runner.session, message, "query", {}))def test_run_prompt_tool_update_branch(self, runner: DummyRunner, mocker: MockerFixture):- message = MagicMock()+ message = _make_message()message.id = "msg-id"action = AgentScratchpadUnit.Action(action_name="tool", action_input={})@@ -529,7 +562,7 @@ class TestOrganizeHistoricPromptMessagesExtended:class TestRunAdditionalBranches:def test_run_with_no_action_final_answer_empty(self, runner: DummyRunner, mocker: MockerFixture):- message = MagicMock()+ message = _make_message()message.id = "msg-id"mocker.patch(@@ -541,7 +574,7 @@ class TestRunAdditionalBranches:assert any(hasattr(r, "delta") for r in results)def test_run_with_final_answer_action_string(self, runner: DummyRunner, mocker: MockerFixture):- message = MagicMock()+ message = _make_message()message.id = "msg-id"action = AgentScratchpadUnit.Action(action_name="Final Answer", action_input="done")@@ -555,7 +588,7 @@ class TestRunAdditionalBranches:assert results[-1].delta.message.content == "done"def test_run_with_final_answer_action_dict(self, runner: DummyRunner, mocker: MockerFixture):- message = MagicMock()+ message = _make_message()message.id = "msg-id"action = AgentScratchpadUnit.Action(action_name="Final Answer", action_input={"a": 1})@@ -569,7 +602,7 @@ class TestRunAdditionalBranches:assert json.loads(results[-1].delta.message.content) == {"a": 1}def test_run_with_string_final_answer(self, runner: DummyRunner, mocker: MockerFixture):- message = MagicMock()+ message = _make_message()message.id = "msg-id"# Remove invalid branch: Pydantic enforces str|dict for action_inputdiff --git a/api/tests/unit_tests/core/agent/test_fc_agent_runner.py b/api/tests/unit_tests/core/agent/test_fc_agent_runner.pyindex ea8c3b87c42..c8f186ce7f5 100644--- a/api/tests/unit_tests/core/agent/test_fc_agent_runner.py+++ b/api/tests/unit_tests/core/agent/test_fc_agent_runner.py@@ -1,11 +1,13 @@import jsonfrom collections.abc import Iteratorfrom datetime import UTC, datetime+from decimal import Decimalfrom typing import Anyfrom unittest.mock import MagicMockimport pytestfrom pytest_mock import MockerFixture+from sqlalchemy import eventfrom sqlalchemy.engine import Enginefrom sqlalchemy.orm import Session@@ -21,8 +23,9 @@ from graphon.model_runtime.entities.message_entities import (TextPromptMessageContent,UserPromptMessage,)-from models.enums import CreatorUserRole-from models.model import StorageType, UploadFile+from libs.datetime_utils import naive_utc_now+from models.enums import ConversationFromSource, CreatorUserRole, MessageStatus+from models.model import AppMode, Conversation, Message, StorageType, UploadFile# ==============================# Dummy Helper Classes@@ -40,6 +43,35 @@ def build_usage(pt=1, ct=1, tt=2) -> LLMUsage:return usage+def _make_conversation(*, conversation_id: str = "conv1") -> Conversation:+ return Conversation(+ id=conversation_id,+ app_id="app",+ mode=AppMode.AGENT_CHAT,+ name="Agent Conversation",+ inputs={},+ from_source=ConversationFromSource.API,+ )+++def _make_message(*, message_id: str = "m1", conversation_id: str = "conv1") -> Message:+ return Message(+ id=message_id,+ app_id="app",+ conversation_id=conversation_id,+ inputs={},+ query="query",+ message={},+ answer="",+ status=MessageStatus.NORMAL,+ message_unit_price=Decimal(0),+ answer_unit_price=Decimal(0),+ currency="USD",+ from_source=ConversationFromSource.API,+ created_at=naive_utc_now(),+ )++class DummyMessage:def __init__(self, content: str | None = None, tool_calls: list[Any] | None = None):self.content: str | None = content@@ -104,8 +136,8 @@ def runner(mocker: MockerFixture, sqlite_engine: Engine) -> Iterator[FunctionCalmodel_instance.model = "test-model"model_instance.model_name = "test-model"- message = MagicMock(id="msg1")- conversation = MagicMock(id="conv1")+ message = _make_message(message_id="msg1")+ conversation = _make_conversation()runner = FunctionCallAgentRunner(tenant_id="tenant",@@ -393,7 +425,7 @@ class TestBuildDatasetToolImageContents:class TestRunMethod:def test_run_non_streaming_no_tool_calls(self, runner: FunctionCallAgentRunner):- message = MagicMock(id="m1")+ message = _make_message()dummy_message = DummyMessage(content="hello")result = DummyResult(message=dummy_message, usage=build_usage())@@ -409,24 +441,24 @@ class TestRunMethod:queue_calls = runner.queue_manager.publish.call_args_listassert any(call.args and call.args[0].__class__.__name__ == "QueueMessageEndEvent" for call in queue_calls)- def test_run_streaming_branch(self, runner: FunctionCallAgentRunner, mocker: MockerFixture):- message = MagicMock(id="m1")+ def test_run_streaming_branch(self, runner: FunctionCallAgentRunner):runner.stream_tool_call = Trueevents: list[str] = []session = runner.session- original_commit = session.commit- original_close = session.close+ conversation = _make_conversation()+ message = _make_message(conversation_id=conversation.id)+ session.add_all([conversation, message])+ session.commit()- def commit_session() -> None:+ def record_commit(_session: Session) -> None:events.append("commit")- original_commit()- def close_session() -> None:- events.append("close")- original_close()+ def record_detach(_session: Session, instance: object) -> None:+ if instance is message:+ events.append("close")- mocker.patch.object(session, "commit", side_effect=commit_session)- mocker.patch.object(session, "close", side_effect=close_session)+ event.listen(session, "after_commit", record_commit)+ event.listen(session, "persistent_to_detached", record_detach)content = [TextPromptMessageContent(data="hi")]chunk = DummyChunk(message=DummyMessage(content=content), usage=build_usage())@@ -442,7 +474,7 @@ class TestRunMethod:assert len(outputs) == 1def test_run_streaming_tool_calls_list_content(self, runner: FunctionCallAgentRunner):- message = MagicMock(id="m1")+ message = _make_message()runner.stream_tool_call = Truetool_call = MagicMock()@@ -465,7 +497,7 @@ class TestRunMethod:assert len(outputs) >= 1def test_run_non_streaming_list_content(self, runner: FunctionCallAgentRunner):- message = MagicMock(id="m1")+ message = _make_message()content = [TextPromptMessageContent(data="hi")]dummy_message = DummyMessage(content=content)result = DummyResult(message=dummy_message, usage=build_usage())@@ -477,7 +509,7 @@ class TestRunMethod:assert runner.save_agent_thought.call_args.kwargs["thought"] == "hi"def test_run_streaming_tool_call_inputs_type_error(self, runner: FunctionCallAgentRunner, mocker: MockerFixture):- message = MagicMock(id="m1")+ message = _make_message()runner.stream_tool_call = Truetool_call = MagicMock()@@ -505,7 +537,7 @@ class TestRunMethod:assert len(outputs) == 1def test_run_with_missing_tool_instance(self, runner: FunctionCallAgentRunner):- message = MagicMock(id="m1")+ message = _make_message()tool_call = MagicMock()tool_call.id = "1"@@ -523,7 +555,7 @@ class TestRunMethod:assert len(outputs) >= 1def test_run_with_tool_instance_and_files(self, runner: FunctionCallAgentRunner, mocker: MockerFixture):- message = MagicMock(id="m1")+ message = _make_message()tool_call = MagicMock()tool_call.id = "1"@@ -560,7 +592,7 @@ class TestRunMethod:def test_run_max_iteration_error(self, runner: FunctionCallAgentRunner):runner.app_config.agent.max_iteration = 0- message = MagicMock(id="m1")+ message = _make_message()tool_call = MagicMock()tool_call.id = "1"diff --git a/api/tests/unit_tests/core/app/apps/advanced_chat/test_app_runner_conversation_variables.py b/api/tests/unit_tests/core/app/apps/advanced_chat/test_app_runner_conversation_variables.pyindex 1f592ddec82..4b34242e5dd 100644--- a/api/tests/unit_tests/core/app/apps/advanced_chat/test_app_runner_conversation_variables.py+++ b/api/tests/unit_tests/core/app/apps/advanced_chat/test_app_runner_conversation_variables.py@@ -10,7 +10,8 @@ from core.app.apps.advanced_chat import app_runner as app_runner_modulefrom core.app.apps.advanced_chat.app_runner import AdvancedChatAppRunnerfrom factories import variable_factoryfrom graphon.variables import SegmentType-from models import ConversationVariable+from models import App, Conversation, ConversationVariable, Message+from models.workflow import Workflow, WorkflowTypeAPP_ID = "11111111-1111-1111-1111-111111111111"CONVERSATION_ID = "22222222-2222-2222-2222-222222222222"@@ -31,19 +32,28 @@ def _variable(variable_id: str, name: str, value: str):def _runner(workflow_variables: list[object]) -> AdvancedChatAppRunner:- workflow = MagicMock()+ workflow = Workflow(+ id="55555555-5555-5555-5555-555555555555",+ tenant_id="66666666-6666-6666-6666-666666666666",+ app_id=APP_ID,+ type=WorkflowType.CHAT,+ version=Workflow.VERSION_DRAFT,+ graph="{}",+ features="{}",+ created_by="44444444-4444-4444-4444-444444444444",+ )workflow.conversation_variables = workflow_variables- conversation = MagicMock(app_id=APP_ID, id=CONVERSATION_ID)+ conversation = Conversation(id=CONVERSATION_ID, app_id=APP_ID)return AdvancedChatAppRunner(application_generate_entity=MagicMock(),queue_manager=MagicMock(),conversation=conversation,- message=MagicMock(),+ message=Message(id="77777777-7777-7777-7777-777777777777"),dialogue_count=1,variable_loader=MagicMock(),workflow=workflow,system_user_id="44444444-4444-4444-4444-444444444444",- app=MagicMock(),+ app=App(id=APP_ID, tenant_id=workflow.tenant_id),workflow_execution_repository=MagicMock(),workflow_node_execution_repository=MagicMock(),)diff --git a/api/tests/unit_tests/core/app/apps/advanced_chat/test_app_runner_input_moderation.py b/api/tests/unit_tests/core/app/apps/advanced_chat/test_app_runner_input_moderation.pyindex 7811ab78739..bb1c2cf8573 100644--- a/api/tests/unit_tests/core/app/apps/advanced_chat/test_app_runner_input_moderation.py+++ b/api/tests/unit_tests/core/app/apps/advanced_chat/test_app_runner_input_moderation.py@@ -1,3 +1,4 @@+import jsonfrom contextlib import contextmanagerfrom unittest.mock import MagicMock, patchfrom uuid import uuid4@@ -12,7 +13,8 @@ from core.app.apps.advanced_chat.app_runner import AdvancedChatAppRunnerfrom core.app.entities.app_invoke_entities import AdvancedChatAppGenerateEntity, InvokeFromfrom core.app.entities.queue_entities import QueueAnnotationReplyEvent, QueueStopEventfrom core.moderation.base import ModerationError-from models.model import App, AppMode, IconType+from models.model import App, AppMode, Conversation, IconType, Message, MessageAnnotation+from models.workflow import Workflow, WorkflowTypeMINIMAL_GRAPH = {"nodes": [@@ -38,39 +40,36 @@ def build_runner(sqlite_session: Session):# Mocks for constructor argsmock_queue_manager = MagicMock()- mock_conversation = MagicMock()- mock_conversation.id = str(uuid4())- mock_conversation.app_id = app_id-- mock_message = MagicMock()- mock_message.id = str(uuid4())-- mock_workflow = MagicMock()- mock_workflow.id = workflow_id- mock_workflow.tenant_id = tenant_id- mock_workflow.app_id = app_id- mock_workflow.type = "chat"- mock_workflow.graph_dict = MINIMAL_GRAPH- mock_workflow.environment_variables = []+ conversation = Conversation(id=str(uuid4()), app_id=app_id)+ message = Message(id=str(uuid4()), app_id=app_id, conversation_id=conversation.id)+ workflow = Workflow(+ id=workflow_id,+ tenant_id=tenant_id,+ app_id=app_id,+ type=WorkflowType.CHAT,+ version=Workflow.VERSION_DRAFT,+ graph=json.dumps(MINIMAL_GRAPH),+ features="{}",+ created_by=str(uuid4()),+ )mock_app_config = MagicMock()mock_app_config.app_id = app_idmock_app_config.workflow_id = workflow_idmock_app_config.tenant_id = tenant_id- sqlite_session.add(- App(- id=app_id,- tenant_id=tenant_id,- name="Advanced chat app",- mode=AppMode.ADVANCED_CHAT,- icon_type=IconType.EMOJI,- icon="chat",- icon_background="#ffffff",- enable_site=False,- enable_api=False,- )+ app = App(+ id=app_id,+ tenant_id=tenant_id,+ name="Advanced chat app",+ mode=AppMode.ADVANCED_CHAT,+ icon_type=IconType.EMOJI,+ icon="chat",+ icon_background="#ffffff",+ enable_site=False,+ enable_api=False,)+ sqlite_session.add(app)sqlite_session.commit()gen = MagicMock(spec=AdvancedChatAppGenerateEntity)@@ -91,13 +90,13 @@ def build_runner(sqlite_session: Session):runner = AdvancedChatAppRunner(application_generate_entity=gen,queue_manager=mock_queue_manager,- conversation=mock_conversation,- message=mock_message,+ conversation=conversation,+ message=message,dialogue_count=1,variable_loader=MagicMock(),- workflow=mock_workflow,+ workflow=workflow,system_user_id=str(uuid4()),- app=MagicMock(),+ app=app,workflow_execution_repository=MagicMock(),workflow_node_execution_repository=MagicMock(),)@@ -125,7 +124,7 @@ def test_handle_input_moderation_stops_on_moderation_error(build_runner):patch.object(runner, "_complete_with_stream_output") as mock_complete,):stop, new_inputs, new_query = runner.handle_input_moderation(- app_record=MagicMock(),+ app_record=runner._app,app_generate_entity=runner.application_generate_entity,inputs={"k": "v"},query="hello",@@ -206,7 +205,12 @@ def test_run_publishes_annotation_after_commit(build_runner, sqlite_engine: Engievents.append("commit")event.listen(Session, "after_commit", record_commit)- annotation_reply = MagicMock(id="annotation-1", content="annotated answer")+ annotation_reply = MessageAnnotation(+ app_id=runner._app.id,+ question="question",+ content="annotated answer",+ account_id=str(uuid4()),+ )def publish(event):if isinstance(event, QueueAnnotationReplyEvent):diff --git a/api/tests/unit_tests/core/app/apps/agent_app/test_resolve_agent.py b/api/tests/unit_tests/core/app/apps/agent_app/test_resolve_agent.pyindex 37ea3338000..aff8efd111e 100644--- a/api/tests/unit_tests/core/app/apps/agent_app/test_resolve_agent.py+++ b/api/tests/unit_tests/core/app/apps/agent_app/test_resolve_agent.py@@ -1,23 +1,35 @@"""Unit tests for AgentAppGenerator agent/snapshot resolution.Covers the DB-backed resolution helpers (the bound roster Agent + its published-Agent Soul snapshot) including every not-found error path, using a fake session-that returns queued rows.+Agent Soul snapshot) including every not-found error path, using persisted rows+in the shared SQLite test database."""from __future__ import annotations-from types import SimpleNamespace-from typing import Anyfrom unittest.mock import MagicMockimport pytest+from sqlalchemy import event, select+from sqlalchemy.orm import Sessionfrom core.app.apps.agent_app import app_generatorfrom core.app.apps.agent_app.app_generator import AgentAppGenerator, AgentAppGeneratorError, AgentAppNotPublishedErrorfrom core.app.entities.app_invoke_entities import InvokeFrom-from models.agent import AgentConfigDraft, AgentConfigDraftType, AgentConfigVersionKind, AgentScope, AgentSource+from models.account import Account+from models.agent import (+ Agent,+ AgentConfigDraft,+ AgentConfigDraftType,+ AgentConfigSnapshot,+ AgentConfigVersionKind,+ AgentScope,+ AgentSource,+ AgentWorkingResourceStatus,+ AgentWorkspaceBinding,+)from models.agent_config_entities import AgentSoulConfig+from models.model import App, AppMode, Conversationfrom services.agent.workspace_service import (AgentWorkspaceBindingGenerationMismatchError,AgentWorkspaceService,@@ -33,38 +45,99 @@ _SOUL_DICT = {}-class _FakeScalarSession:- """Session stub whose scalar() pops the next queued row."""+def _agent(+ *,+ agent_id: str = "agent-1",+ scope: AgentScope = AgentScope.ROSTER,+ source: AgentSource = AgentSource.AGENT_APP,+ active_snapshot_id: str | None = "snap-1",+ published: bool = True,+) -> Agent:+ return Agent(+ id=agent_id,+ tenant_id="t1",+ name=f"Agent {agent_id}",+ scope=scope,+ source=source,+ app_id="app-1" if scope == AgentScope.ROSTER else None,+ backing_app_id="app-1" if scope == AgentScope.WORKFLOW_ONLY else None,+ active_config_snapshot_id=active_snapshot_id,+ active_config_has_model=True,+ active_config_is_published=published,+ created_by="creator-1",+ updated_by="updater-1",+ )+++def _snapshot(+ *, snapshot_id: str = "snap-1", agent_id: str = "agent-1", home_snapshot_id: str = "home-1"+) -> AgentConfigSnapshot:+ return AgentConfigSnapshot(+ id=snapshot_id,+ tenant_id="t1",+ agent_id=agent_id,+ version=1,+ config_snapshot=AgentSoulConfig.model_validate(_SOUL_DICT),+ home_snapshot_id=home_snapshot_id,+ created_by="creator-1",+ )- def __init__(self, values: list[Any]) -> None:- self._values = list(values)- self.added: list[Any] = []- self.flush_count = 0- self.scalar_statements: list[Any] = []- def scalar(self, stmt: Any) -> Any:- self.scalar_statements.append(stmt)- return self._values.pop(0) if self._values else None+def _app() -> App:+ return App(+ id="app-1",+ tenant_id="t1",+ name="Agent App",+ mode=AppMode.AGENT_CHAT,+ enable_site=False,+ enable_api=False,+ )- def add(self, value: Any) -> None:- self.added.append(value)- def flush(self) -> None:- self.flush_count += 1+def _account() -> Account:+ account = Account(name="Agent User", email="[email protected]")+ account.id = "user-1"+ return account+++def _conversation(*, binding_id: str) -> Conversation:+ return Conversation(id="conversation-1", app_id="app-1", agent_workspace_binding_id=binding_id)+++def _binding(+ *,+ home_snapshot_id: str = "home-1",+ version_id: str = "snap-1",+ version_kind: AgentConfigVersionKind = AgentConfigVersionKind.SNAPSHOT,+) -> AgentWorkspaceBinding:+ return AgentWorkspaceBinding(+ id="binding-1",+ tenant_id="t1",+ app_id="app-1",+ workspace_id="workspace-1",+ agent_id="agent-1",+ base_home_snapshot_id=home_snapshot_id,+ agent_config_version_id=version_id,+ agent_config_version_kind=version_kind,+ backend_binding_ref="backend-binding-1",+ status=AgentWorkingResourceStatus.ACTIVE,+ )-def _snapshot() -> SimpleNamespace:- return SimpleNamespace(id="snap-1", home_snapshot_id="home-1", config_snapshot_dict=_SOUL_DICT)+def _persist(session: Session, *models: object) -> None:+ session.add_all(models)+ session.commit()class TestResolveAgentById:- def test_success_returns_agent_snapshot_soul(self):- agent = SimpleNamespace(id="agent-1")+ def test_success_returns_agent_snapshot_soul(self, sqlite_session: Session):+ agent = _agent()snapshot = _snapshot()- session = _FakeScalarSession([agent, snapshot])+ sqlite_session.add_all([agent, snapshot])+ sqlite_session.commit()resolved_agent, resolved_snapshot, soul = AgentAppGenerator._resolve_agent_by_id(- tenant_id="t1", agent_id="agent-1", snapshot_id="snap-1", session=session+ tenant_id="t1", agent_id="agent-1", snapshot_id="snap-1", session=sqlite_session)assert resolved_agent is agent@@ -73,38 +146,44 @@ class TestResolveAgentById:assert soul.model is not Noneassert soul.model.model == "gpt-4o-mini"- def test_agent_missing_raises(self):- session = _FakeScalarSession([None])+ def test_agent_missing_raises(self, sqlite_session: Session):with pytest.raises(AgentAppGeneratorError, match="Agent not found"):- AgentAppGenerator._resolve_agent_by_id(tenant_id="t1", agent_id="x", snapshot_id="snap-1", session=session)+ AgentAppGenerator._resolve_agent_by_id(+ tenant_id="t1", agent_id="x", snapshot_id="snap-1", session=sqlite_session+ )- def test_no_published_version_raises(self):- session = _FakeScalarSession([SimpleNamespace(id="agent-1")])+ def test_no_published_version_raises(self, sqlite_session: Session):+ sqlite_session.add(_agent(active_snapshot_id=None))+ sqlite_session.commit()with pytest.raises(AgentAppGeneratorError, match="no published version"):AgentAppGenerator._resolve_agent_by_id(- tenant_id="t1", agent_id="agent-1", snapshot_id=None, session=session+ tenant_id="t1", agent_id="agent-1", snapshot_id=None, session=sqlite_session)- def test_snapshot_missing_raises(self):- session = _FakeScalarSession([SimpleNamespace(id="agent-1"), None])+ def test_snapshot_missing_raises(self, sqlite_session: Session):+ sqlite_session.add(_agent())+ sqlite_session.commit()with pytest.raises(AgentAppGeneratorError, match="published version not found"):AgentAppGenerator._resolve_agent_by_id(tenant_id="t1",agent_id="agent-1",snapshot_id="snap-1",- session=session,+ session=sqlite_session,)class TestResolveDebugDraft:- def test_missing_shared_draft_is_created_with_supplied_session(self):- agent = SimpleNamespace(- id="agent-1",- active_config_snapshot_id="snap-1",- created_by="creator-1",- updated_by="updater-1",- )- session = _FakeScalarSession([None, _snapshot()])+ def test_missing_shared_draft_is_created_with_supplied_session(self, sqlite_session: Session):+ agent = _agent()+ sqlite_session.add_all([agent, _snapshot()])+ sqlite_session.commit()+ flush_count = 0++ def _record_flush(_session: Session, _context: object) -> None:+ nonlocal flush_count+ flush_count += 1++ event.listen(sqlite_session, "after_flush", _record_flush)draft = AgentAppGenerator._resolve_debug_draft(tenant_id="t1",@@ -112,22 +191,16 @@ class TestResolveDebugDraft:draft_type=None,draft_id=None,account_id=None,- session=session,+ session=sqlite_session,)assert draft.draft_type == AgentConfigDraftType.DRAFTassert draft.base_snapshot_id == "snap-1"- assert session.added == [draft]- assert session.flush_count == 1-- def test_stale_workflow_only_shared_draft_is_rebased_to_active_snapshot(self):- agent = SimpleNamespace(- id="agent-1",- scope=AgentScope.WORKFLOW_ONLY,- active_config_snapshot_id="snap-2",- created_by="creator-1",- updated_by="updater-1",- )+ assert sqlite_session.scalar(select(AgentConfigDraft).where(AgentConfigDraft.id == draft.id)) is draft+ assert flush_count == 1++ def test_stale_workflow_only_shared_draft_is_rebased_to_active_snapshot(self, sqlite_session: Session):+ agent = _agent(scope=AgentScope.WORKFLOW_ONLY, active_snapshot_id="snap-2")draft = AgentConfigDraft(id="draft-1",tenant_id="t1",@@ -139,19 +212,31 @@ class TestResolveDebugDraft:home_snapshot_id="home-1",config_snapshot=AgentSoulConfig.model_validate({"prompt": {"system_prompt": "old"}}),)- active_snapshot = SimpleNamespace(+ active_snapshot = AgentConfigSnapshot(id="snap-2",+ tenant_id="t1",+ agent_id="agent-1",+ version=2,+ config_snapshot=AgentSoulConfig.model_validate({"prompt": {"system_prompt": "new"}}),home_snapshot_id="home-2",- config_snapshot_dict={"prompt": {"system_prompt": "new"}},+ created_by="creator-1",)- session = _FakeScalarSession([draft, active_snapshot])+ sqlite_session.add_all([agent, draft, active_snapshot])+ sqlite_session.commit()+ flush_count = 0++ def _record_flush(_session: Session, _context: object) -> None:+ nonlocal flush_count+ flush_count += 1++ event.listen(sqlite_session, "after_flush", _record_flush)resolved = AgentAppGenerator._resolve_debug_draft(tenant_id="t1",agent=agent,draft_type=None,account_id=None,- session=session,+ session=sqlite_session,)assert resolved is draft@@ -159,16 +244,10 @@ class TestResolveDebugDraft:assert resolved.base_snapshot_id == "snap-2"assert resolved.home_snapshot_id == "home-2"assert resolved.config_snapshot_dict["prompt"]["system_prompt"] == "new"- assert session.flush_count == 1+ assert flush_count == 1- def test_build_draft_is_not_rebased_to_active_snapshot(self):- agent = SimpleNamespace(- id="agent-1",- scope=AgentScope.WORKFLOW_ONLY,- active_config_snapshot_id="snap-2",- created_by="creator-1",- updated_by="updater-1",- )+ def test_build_draft_is_not_rebased_to_active_snapshot(self, sqlite_session: Session):+ agent = _agent(scope=AgentScope.WORKFLOW_ONLY, active_snapshot_id="snap-2")draft = AgentConfigDraft(id="build-draft-1",tenant_id="t1",@@ -180,29 +259,24 @@ class TestResolveDebugDraft:home_snapshot_id="home-build",config_snapshot=AgentSoulConfig.model_validate({"prompt": {"system_prompt": "build edit"}}),)- session = _FakeScalarSession([draft])+ sqlite_session.add_all([agent, draft])+ sqlite_session.commit()resolved = AgentAppGenerator._resolve_debug_draft(tenant_id="t1",agent=agent,draft_type=AgentConfigDraftType.DEBUG_BUILD.value,account_id="account-1",- session=session,+ session=sqlite_session,)assert resolved is draftassert resolved.base_snapshot_id == "snap-1"assert resolved.config_snapshot_dict["prompt"]["system_prompt"] == "build edit"- assert session.flush_count == 0+ assert not sqlite_session.dirty- def test_build_draft_uses_exact_draft_id(self):- agent = SimpleNamespace(- id="agent-1",- scope=AgentScope.WORKFLOW_ONLY,- active_config_snapshot_id="snap-2",- created_by="creator-1",- updated_by="updater-1",- )+ def test_build_draft_uses_exact_draft_id(self, sqlite_session: Session):+ agent = _agent(scope=AgentScope.WORKFLOW_ONLY, active_snapshot_id="snap-2")draft = AgentConfigDraft(id="exact-build-draft",tenant_id="t1",@@ -214,15 +288,19 @@ class TestResolveDebugDraft:home_snapshot_id="home-build",config_snapshot=AgentSoulConfig(),)- session = _FakeScalarSession([draft])- statements: list[Any] = []- scalar = session.scalar-- def capture_scalar(statement: Any) -> Any:- statements.append(statement)- return scalar(statement)-- session.scalar = capture_scalar # type: ignore[method-assign]+ newer_decoy = AgentConfigDraft(+ id="newer-build-draft",+ tenant_id="t1",+ agent_id="agent-1",+ draft_type=AgentConfigDraftType.DEBUG_BUILD,+ account_id="account-1",+ draft_owner_key="account-1-decoy",+ base_snapshot_id="snap-2",+ home_snapshot_id="home-decoy",+ config_snapshot=AgentSoulConfig(prompt={"system_prompt": "decoy"}),+ )+ sqlite_session.add_all([agent, draft, newer_decoy])+ sqlite_session.commit()resolved = AgentAppGenerator._resolve_debug_draft(tenant_id="t1",@@ -230,20 +308,17 @@ class TestResolveDebugDraft:draft_type=AgentConfigDraftType.DEBUG_BUILD.value,draft_id="exact-build-draft",account_id="account-1",- session=session,+ session=sqlite_session,)assert resolved is draft- assert "agent_config_drafts.id =" in str(statements[0])- assert "exact-build-draft" in statements[0].compile().params.values()+ assert resolved.id == "exact-build-draft"class TestResolveAgent:@pytest.fixture(autouse=True)def _publish_visibility(self, monkeypatch: pytest.MonkeyPatch) -> None:- def is_publish_visible(*, agent: SimpleNamespace, **_kwargs: object) -> bool:- if "publish_visible" in vars(agent):- return bool(agent.publish_visible)+ def is_publish_visible(*, agent: Agent, **_kwargs: object) -> bool:return bool(agent.active_config_is_published)monkeypatch.setattr(@@ -252,52 +327,41 @@ class TestResolveAgent:is_publish_visible,)- def test_success_chains_to_resolve_by_id(self):- bound_agent = SimpleNamespace(- id="agent-1",- source=AgentSource.AGENT_APP,- active_config_snapshot_id="snap-1",- active_config_is_published=True,- )- inner_agent = SimpleNamespace(id="agent-1")+ def test_success_chains_to_resolve_by_id(self, sqlite_session: Session):+ bound_agent = _agent()snapshot = _snapshot()- # scalar order: bound agent (in _resolve_agent), then agent + snapshot (in _resolve_agent_by_id)- session = _FakeScalarSession([bound_agent, inner_agent, snapshot])- app_model = SimpleNamespace(id="app-1", tenant_id="t1")+ _persist(sqlite_session, bound_agent, snapshot)+ app_model = _app()agent, config_id, config_version_kind, soul = AgentAppGenerator()._resolve_agent(app_model,invoke_from=InvokeFrom.WEB_APP,draft_type=None,- user=SimpleNamespace(id="user-1"),- session=session,- ) # type: ignore[arg-type]+ user=_account(),+ session=sqlite_session,+ )assert agent is bound_agentassert config_id == snapshot.idassert config_version_kind == "snapshot"assert soul.model is not None- def test_unpublished_draft_still_resolves_active_snapshot(self):- bound_agent = SimpleNamespace(- id="agent-1",- source=AgentSource.AGENT_APP,- active_config_snapshot_id="snap-1",- active_config_is_published=False,- publish_visible=True,- )- inner_agent = SimpleNamespace(id="agent-1")+ def test_unpublished_draft_still_resolves_active_snapshot(+ self, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session+ ):+ bound_agent = _agent(published=False)snapshot = _snapshot()- session = _FakeScalarSession([bound_agent, inner_agent, snapshot])- app_model = SimpleNamespace(id="app-1", tenant_id="t1")+ _persist(sqlite_session, bound_agent, snapshot)+ app_model = _app()+ monkeypatch.setattr(app_generator, "agent_has_workflow_callable_active_snapshot", lambda **_kwargs: True)agent, config_id, config_version_kind, soul = AgentAppGenerator()._resolve_agent(app_model,invoke_from=InvokeFrom.WEB_APP,draft_type=None,- user=SimpleNamespace(id="user-1"),- session=session,- ) # type: ignore[arg-type]+ user=_account(),+ session=sqlite_session,+ )assert agent is bound_agentassert config_id == snapshot.id@@ -305,43 +369,27 @@ class TestResolveAgent:assert soul.prompt.system_prompt == "You are Iris."def test_existing_conversation_resolves_binding_snapshot_instead_of_latest_active_snapshot(- self, monkeypatch: pytest.MonkeyPatch+ self, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session):- bound_agent = SimpleNamespace(- id="agent-1",- source=AgentSource.AGENT_APP,- active_config_snapshot_id="snap-2",- active_config_is_published=True,- )- inner_agent = SimpleNamespace(id="agent-1")- pinned_snapshot = SimpleNamespace(- id="snap-1",- home_snapshot_id="home-1",- config_snapshot_dict=_SOUL_DICT,- )- conversation = SimpleNamespace(id="conversation-1", agent_workspace_binding_id="binding-1")- binding = SimpleNamespace(- id="binding-1",- agent_id="agent-1",- base_home_snapshot_id="home-1",- agent_config_version_id="snap-1",- agent_config_version_kind=AgentConfigVersionKind.SNAPSHOT,- )+ bound_agent = _agent(active_snapshot_id="snap-2")+ pinned_snapshot = _snapshot()+ _persist(sqlite_session, bound_agent, pinned_snapshot)+ conversation = _conversation(binding_id="binding-1")+ binding = _binding()get_active_binding = MagicMock(return_value=binding)validate_generation = MagicMock()monkeypatch.setattr(AgentWorkspaceService, "get_active_binding", get_active_binding)monkeypatch.setattr(AgentWorkspaceService, "validate_binding_generation", validate_generation)- session = _FakeScalarSession([bound_agent, inner_agent, pinned_snapshot])- app_model = SimpleNamespace(id="app-1", tenant_id="t1")+ app_model = _app()_, config_id, config_version_kind, soul = AgentAppGenerator()._resolve_agent(app_model,invoke_from=InvokeFrom.WEB_APP,draft_type=None,- user=SimpleNamespace(id="user-1"),- session=session,+ user=_account(),+ session=sqlite_session,conversation=conversation,- ) # type: ignore[arg-type]+ )assert config_id == "snap-1"assert config_version_kind == "snapshot"@@ -354,25 +402,23 @@ class TestResolveAgent:agent_config_version_kind=AgentConfigVersionKind.SNAPSHOT,)- def test_existing_conversation_rejects_unavailable_binding(self, monkeypatch: pytest.MonkeyPatch):- bound_agent = SimpleNamespace(- id="agent-1",- source=AgentSource.AGENT_APP,- active_config_snapshot_id="snap-active",- active_config_is_published=True,- )- conversation = SimpleNamespace(id="conversation-1", agent_workspace_binding_id="binding-missing")+ def test_existing_conversation_rejects_unavailable_binding(+ self, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session+ ):+ bound_agent = _agent(active_snapshot_id="snap-active")+ _persist(sqlite_session, bound_agent)+ conversation = _conversation(binding_id="binding-missing")monkeypatch.setattr(AgentWorkspaceService, "get_active_binding", MagicMock(return_value=None))with pytest.raises(AgentAppGeneratorError, match="Conversation participant Binding is unavailable"):AgentAppGenerator()._resolve_agent(- SimpleNamespace(id="app-1", tenant_id="t1"),+ _app(),invoke_from=InvokeFrom.WEB_APP,draft_type=None,- user=SimpleNamespace(id="user-1"),- session=_FakeScalarSession([bound_agent]),+ user=_account(),+ session=sqlite_session,conversation=conversation,- ) # type: ignore[arg-type]+ )@pytest.mark.parametrize(("binding_home_id", "binding_version_kind", "snapshot_home_id"),@@ -384,137 +430,109 @@ class TestResolveAgent:def test_existing_conversation_generation_mismatch_does_not_fallback_to_active_snapshot(self,monkeypatch: pytest.MonkeyPatch,+ sqlite_session: Session,binding_home_id: str,binding_version_kind: AgentConfigVersionKind,snapshot_home_id: str,):- bound_agent = SimpleNamespace(- id="agent-1",- source=AgentSource.AGENT_APP,- active_config_snapshot_id="snap-active",- active_config_is_published=True,- )- conversation = SimpleNamespace(id="conversation-1", agent_workspace_binding_id="binding-1")- binding = SimpleNamespace(- id="binding-1",- agent_id="agent-1",- base_home_snapshot_id=binding_home_id,- agent_config_version_id="snap-pinned",- agent_config_version_kind=binding_version_kind,- )- pinned_snapshot = SimpleNamespace(- id="snap-pinned",- home_snapshot_id=snapshot_home_id,- config_snapshot_dict=_SOUL_DICT,+ bound_agent = _agent(active_snapshot_id="snap-active")+ conversation = _conversation(binding_id="binding-1")+ binding = _binding(+ home_snapshot_id=binding_home_id,+ version_id="snap-pinned",+ version_kind=binding_version_kind,)+ pinned_snapshot = _snapshot(snapshot_id="snap-pinned", home_snapshot_id=snapshot_home_id)+ _persist(sqlite_session, bound_agent, pinned_snapshot)monkeypatch.setattr(AgentWorkspaceService, "get_active_binding", MagicMock(return_value=binding))- session = _FakeScalarSession([bound_agent, SimpleNamespace(id="agent-1"), pinned_snapshot])with pytest.raises(AgentWorkspaceBindingGenerationMismatchError):AgentAppGenerator()._resolve_agent(- SimpleNamespace(id="app-1", tenant_id="t1"),+ _app(),invoke_from=InvokeFrom.WEB_APP,draft_type=None,- user=SimpleNamespace(id="user-1"),- session=session,+ user=_account(),+ session=sqlite_session,conversation=conversation,- ) # type: ignore[arg-type]-- snapshot_query_params = session.scalar_statements[-1].compile().params.values()- assert "snap-pinned" in snapshot_query_params- assert "snap-active" not in snapshot_query_params-- def test_unpublished_imported_agent_is_not_available_to_public_runtime(self):- bound_agent = SimpleNamespace(- id="agent-1",- source=AgentSource.IMPORTED,- active_config_snapshot_id="snap-1",- active_config_is_published=False,- )- session = _FakeScalarSession([bound_agent])- app_model = SimpleNamespace(id="app-1", tenant_id="t1")+ )++ def test_unpublished_imported_agent_is_not_available_to_public_runtime(self, sqlite_session: Session):+ bound_agent = _agent(source=AgentSource.IMPORTED, published=False)+ _persist(sqlite_session, bound_agent)+ app_model = _app()with pytest.raises(AgentAppNotPublishedError, match="not been published"):AgentAppGenerator()._resolve_agent(app_model,invoke_from=InvokeFrom.WEB_APP,draft_type=None,- user=SimpleNamespace(id="user-1"),- session=session,- ) # type: ignore[arg-type]-- def test_never_published_agent_app_is_not_available_to_public_runtime(self):- bound_agent = SimpleNamespace(- id="agent-1",- source=AgentSource.AGENT_APP,- active_config_snapshot_id="snap-1",- active_config_is_published=False,- publish_visible=False,- )+ user=_account(),+ session=sqlite_session,+ )++ def test_never_published_agent_app_is_not_available_to_public_runtime(self, sqlite_session: Session):+ bound_agent = _agent(published=False)+ _persist(sqlite_session, bound_agent)with pytest.raises(AgentAppNotPublishedError, match="not been published"):AgentAppGenerator()._resolve_agent(- SimpleNamespace(id="app-1", tenant_id="t1"),+ _app(),invoke_from=InvokeFrom.WEB_APP,draft_type=None,- user=SimpleNamespace(id="user-1"),- session=_FakeScalarSession([bound_agent]),- ) # type: ignore[arg-type]-- def test_unpublished_imported_agent_remains_available_to_debugger(self):- bound_agent = SimpleNamespace(- id="agent-1",- scope=AgentScope.ROSTER,- source=AgentSource.IMPORTED,- active_config_snapshot_id="snap-1",- active_config_is_published=False,- created_by="creator-1",- updated_by="updater-1",+ user=_account(),+ session=sqlite_session,+ )++ def test_unpublished_imported_agent_remains_available_to_debugger(self, sqlite_session: Session):+ bound_agent = _agent(source=AgentSource.IMPORTED, published=False)+ draft = AgentConfigDraft(+ id="draft-1",+ tenant_id="t1",+ agent_id="agent-1",+ draft_type=AgentConfigDraftType.DRAFT,+ account_id=None,+ draft_owner_key="",+ base_snapshot_id="snap-1",+ home_snapshot_id="home-1",+ config_snapshot=AgentSoulConfig.model_validate(_SOUL_DICT),)- draft = SimpleNamespace(id="draft-1", draft_type="draft", config_snapshot_dict=_SOUL_DICT)- session = _FakeScalarSession([bound_agent, draft])- app_model = SimpleNamespace(id="app-1", tenant_id="t1")+ _persist(sqlite_session, bound_agent, draft)+ app_model = _app()agent, config_id, config_version_kind, soul = AgentAppGenerator()._resolve_agent(app_model,invoke_from=InvokeFrom.DEBUGGER,draft_type=None,- user=SimpleNamespace(id="user-1"),- session=session,- ) # type: ignore[arg-type]+ user=_account(),+ session=sqlite_session,+ )assert agent is bound_agentassert config_id == draft.idassert config_version_kind == "draft"assert soul.prompt.system_prompt == "You are Iris."- def test_agent_without_active_snapshot_raises_before_model_resolution(self):- bound_agent = SimpleNamespace(- id="agent-1",- source=AgentSource.AGENT_APP,- active_config_snapshot_id=None,- active_config_is_published=False,- )- session = _FakeScalarSession([bound_agent])- app_model = SimpleNamespace(id="app-1", tenant_id="t1")+ def test_agent_without_active_snapshot_raises_before_model_resolution(self, sqlite_session: Session):+ bound_agent = _agent(active_snapshot_id=None, published=False)+ _persist(sqlite_session, bound_agent)+ app_model = _app()with pytest.raises(AgentAppNotPublishedError, match="not been published"):AgentAppGenerator()._resolve_agent(app_model,invoke_from=InvokeFrom.WEB_APP,draft_type=None,- user=SimpleNamespace(id="user-1"),- session=session,- ) # type: ignore[arg-type]+ user=_account(),+ session=sqlite_session,+ )- def test_unbound_app_raises(self):- session = _FakeScalarSession([None])- app_model = SimpleNamespace(id="app-1", tenant_id="t1")+ def test_unbound_app_raises(self, sqlite_session: Session):+ app_model = _app()with pytest.raises(AgentAppGeneratorError, match="has no bound Agent"):AgentAppGenerator()._resolve_agent(app_model,invoke_from=InvokeFrom.WEB_APP,draft_type=None,- user=SimpleNamespace(id="user-1"),- session=session,- ) # type: ignore[arg-type]+ user=_account(),+ session=sqlite_session,+ )diff --git a/api/tests/unit_tests/core/tools/utils/test_model_invocation_utils.py b/api/tests/unit_tests/core/tools/utils/test_model_invocation_utils.pyindex 357a62e9b11..9a65ca99e70 100644--- a/api/tests/unit_tests/core/tools/utils/test_model_invocation_utils.py+++ b/api/tests/unit_tests/core/tools/utils/test_model_invocation_utils.py@@ -3,8 +3,8 @@Covers success and error branches for ModelInvocationUtils, includingInvokeModelError and invoke error mappings for InvokeAuthorizationError,InvokeBadRequestError, InvokeConnectionError, InvokeRateLimitError, and-InvokeServerUnavailableError. Assumes mocked model instances and managers.-Invocation logging uses a real SQLite-backed SQLAlchemy session.+InvokeServerUnavailableError. Model-provider collaborators remain mocked, while+invocation logging uses real SQLite-backed SQLAlchemy sessions."""from __future__ import annotations@@ -15,8 +15,8 @@ from typing import Anyfrom unittest.mock import Mock, patchimport pytest-from sqlalchemy import select-from sqlalchemy.orm import Session+from sqlalchemy import event, select+from sqlalchemy.orm import Session, sessionmakerfrom core.tools.entities.tool_entities import ToolProviderTypefrom core.tools.utils.model_invocation_utils import InvokeModelError, ModelInvocationUtils@@ -89,7 +89,7 @@ def test_calculate_tokens_handles_missing_model():mock_factory.assert_called_once_with(tenant_id="tenant", user_id=None)-def test_invoke_success_and_error_mappings(sqlite_session: Session):+def test_invoke_success_and_error_mappings(sqlite_session: Session, sqlite_session_factory: sessionmaker[Session]):model_instance = _mock_model_instance(schema={ModelPropertyKey.CONTEXT_SIZE: 2048})model_instance.invoke_llm.return_value = SimpleNamespace(message=SimpleNamespace(content="ok"),@@ -106,12 +106,23 @@ def test_invoke_success_and_error_mappings(sqlite_session: Session):manager.get_default_model_instance.return_value = model_instancedatabase = SimpleNamespace(session=sqlite_session)+ attached_invocations: list[ToolModelInvoke] = []+ commit_count = 0++ def _record_attach(_session: Session, instance: object) -> None:+ if isinstance(instance, ToolModelInvoke):+ attached_invocations.append(instance)++ def _record_commit(_session: Session) -> None:+ nonlocal commit_count+ commit_count += 1++ event.listen(sqlite_session, "after_attach", _record_attach)+ event.listen(sqlite_session, "after_commit", _record_commit)with (patch("core.tools.utils.model_invocation_utils.ModelManager.for_tenant", return_value=manager) as mock_factory,patch("core.tools.utils.model_invocation_utils.db", database),- patch.object(sqlite_session, "add", wraps=sqlite_session.add) as mock_session_add,- patch.object(sqlite_session, "commit", wraps=sqlite_session.commit) as mock_session_commit,):response = ModelInvocationUtils.invoke(user_id=USER_ID,@@ -123,18 +134,19 @@ def test_invoke_success_and_error_mappings(sqlite_session: Session):)assert response.message.content == "ok"- assert mock_session_add.call_count == 1- assert mock_session_commit.call_count == 2+ assert len(attached_invocations) == 1+ assert commit_count == 2assert not sqlite_session.in_transaction()- persisted = sqlite_session.scalar(select(ToolModelInvoke))- assert persisted is not None- assert persisted.user_id == USER_ID- assert persisted.tenant_id == TENANT_ID- assert persisted.tool_type == ToolProviderType.BUILT_IN- assert persisted.model_response == "ok"- assert persisted.prompt_tokens == 5- assert persisted.answer_tokens == 7- assert persisted.total_price == Decimal("0.7000000")+ with sqlite_session_factory() as observer_session:+ persisted = observer_session.scalar(select(ToolModelInvoke))+ assert persisted is not None+ assert persisted.user_id == USER_ID+ assert persisted.tenant_id == TENANT_ID+ assert persisted.tool_type == ToolProviderType.BUILT_IN+ assert persisted.model_response == "ok"+ assert persisted.prompt_tokens == 5+ assert persisted.answer_tokens == 7+ assert persisted.total_price == Decimal("0.7000000")mock_factory.assert_called_once_with(tenant_id=TENANT_ID, user_id=CALLER_ID)