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 residual controller sessions and ORM models to SQLite (#40579)
Asuka Minato14bc28ffbe54
diff --git a/api/tests/unit_tests/controllers/console/workspace/test_model_providers.py b/api/tests/unit_tests/controllers/console/workspace/test_model_providers.pyindex 5fe0f47ecde..0be893a64a9 100644--- a/api/tests/unit_tests/controllers/console/workspace/test_model_providers.py+++ b/api/tests/unit_tests/controllers/console/workspace/test_model_providers.py@@ -1,11 +1,10 @@from inspect import unwrap-from types import SimpleNamespace-from typing import castfrom unittest.mock import ANY, patchimport pytestfrom flask import Flaskfrom pydantic_core import ValidationError+from sqlalchemy.orm import Sessionfrom werkzeug.exceptions import Forbiddenfrom configs import dify_config@@ -44,7 +43,9 @@ INVALID_UUID = "123"def make_account() -> Account:- return cast(Account, SimpleNamespace(id="account-1", email="[email protected]"))+ account = Account(name="Provider Owner", email="[email protected]")+ account.id = "account-1"+ return accountdef make_provider_response() -> ProviderResponse:@@ -225,10 +226,10 @@ class TestModelProviderSummaryListApi:class TestModelProviderCreditsApi:- def test_get_success(self):+ def test_get_success(self, unbound_session: Session):api = ModelProviderCreditsApi()method = unwrap(api.get)- session = SimpleNamespace()+ session = unbound_sessioncredit_pool = EffectiveCreditPool(plan="team",pool_type="paid",@@ -255,10 +256,10 @@ class TestModelProviderCreditsApi:"next_credit_reset_date": 1775001600,}- def test_get_without_effective_pool(self):+ def test_get_without_effective_pool(self, unbound_session: Session):api = ModelProviderCreditsApi()method = unwrap(api.get)- session = SimpleNamespace()+ session = unbound_sessionwith patch("controllers.console.workspace.model_providers.WorkspaceService.get_effective_credit_pool",diff --git a/api/tests/unit_tests/controllers/openapi/test_apps_permitted_external_query.py b/api/tests/unit_tests/controllers/openapi/test_apps_permitted_external_query.pyindex 038a17ad1df..b8d077e5df5 100644--- a/api/tests/unit_tests/controllers/openapi/test_apps_permitted_external_query.py+++ b/api/tests/unit_tests/controllers/openapi/test_apps_permitted_external_query.py@@ -10,7 +10,7 @@ from __future__ import annotationsimport inspectfrom types import SimpleNamespace-from unittest.mock import MagicMock, patch+from unittest.mock import patchimport pytestfrom pydantic import ValidationError@@ -20,6 +20,7 @@ from controllers.openapi.apps_permitted_external import (PermittedExternalAppDescribeApi,PermittedExternalAppsListQuery,)+from models.model import App, AppModefrom ._mode_constants import NON_LISTABLE_MODES@@ -74,7 +75,14 @@ def test_describe_forwards_request_session_to_response_builder(unbound_session:api = PermittedExternalAppDescribeApi()method = inspect.unwrap(api.get)session = unbound_session- app = MagicMock()+ app = App(+ id="app-id",+ tenant_id="tenant-1",+ name="Permitted app",+ mode=AppMode.CHAT,+ enable_site=True,+ enable_api=True,+ )auth_data = SimpleNamespace(app=app)query = SimpleNamespace(fields={"info"})response = object()diff --git a/api/tests/unit_tests/controllers/openapi/test_human_input_form.py b/api/tests/unit_tests/controllers/openapi/test_human_input_form.pyindex c4d3d21d84a..28947c69b35 100644--- a/api/tests/unit_tests/controllers/openapi/test_human_input_form.py+++ b/api/tests/unit_tests/controllers/openapi/test_human_input_form.py@@ -16,7 +16,10 @@ from werkzeug.exceptions import UnprocessableEntityfrom controllers.openapi._errors import HumanInputFormNotFound, RecipientSurfaceMismatchfrom controllers.openapi.auth.data import AuthDatafrom libs.oauth_bearer import Scope, TokenType+from models.account import Account+from models.enums import EndUserTypefrom models.human_input import RecipientType+from models.model import App, AppMode, EndUserdef _make_auth_data(app_model, caller, caller_kind):@@ -31,6 +34,33 @@ def _make_auth_data(app_model, caller, caller_kind):)+def _make_app() -> App:+ return App(+ id="app-1",+ tenant_id="tenant-1",+ name="Human input app",+ mode=AppMode.WORKFLOW,+ enable_site=True,+ enable_api=True,+ )+++def _make_account(account_id: str = "acct-1") -> Account:+ account = Account(name="Human Input User", email=f"{account_id}@example.com")+ account.id = account_id+ return account+++def _make_end_user(end_user_id: str = "eu-1") -> EndUser:+ return EndUser(+ id=end_user_id,+ tenant_id="tenant-1",+ app_id="app-1",+ type=EndUserType.OPENAPI,+ session_id=f"session-{end_user_id}",+ )++class TestOpenApiHumanInputFormGet:def test_get_success(self, app: Flask, bypass_pipeline, monkeypatch: pytest.MonkeyPatch):from controllers.openapi.human_input_form import OpenApiWorkflowHumanInputFormApi@@ -59,8 +89,8 @@ class TestOpenApiHumanInputFormGet:monkeypatch.setattr(module, "db", SimpleNamespace(engine=object()))api = OpenApiWorkflowHumanInputFormApi()- app_model = SimpleNamespace(id="app-1", tenant_id="tenant-1")- caller = SimpleNamespace(id="acct-1")+ app_model = _make_app()+ caller = _make_account()with app.test_request_context("/openapi/v1/apps/app-1/human-input-forms/tok-1"):resp = api.get.__wrapped__(@@ -86,8 +116,8 @@ class TestOpenApiHumanInputFormGet:monkeypatch.setattr(module, "db", SimpleNamespace(engine=object()))api = OpenApiWorkflowHumanInputFormApi()- app_model = SimpleNamespace(id="app-1", tenant_id="tenant-1")- caller = SimpleNamespace(id="acct-1")+ app_model = _make_app()+ caller = _make_account()with app.test_request_context("/openapi/v1/apps/app-1/human-input-forms/bad"):with pytest.raises(HumanInputFormNotFound):@@ -114,8 +144,8 @@ class TestOpenApiHumanInputFormGet:monkeypatch.setattr(module, "db", SimpleNamespace(engine=object()))api = OpenApiWorkflowHumanInputFormApi()- app_model = SimpleNamespace(id="app-1", tenant_id="tenant-1")- caller = SimpleNamespace(id="acct-1")+ app_model = _make_app()+ caller = _make_account()with app.test_request_context("/openapi/v1/apps/app-1/human-input-forms/tok-1"):with pytest.raises(HumanInputFormNotFound):@@ -142,8 +172,8 @@ class TestOpenApiHumanInputFormGet:monkeypatch.setattr(module, "db", SimpleNamespace(engine=object()))api = OpenApiWorkflowHumanInputFormApi()- app_model = SimpleNamespace(id="app-1", tenant_id="tenant-1")- caller = SimpleNamespace(id="acct-1")+ app_model = _make_app()+ caller = _make_account()with app.test_request_context("/openapi/v1/apps/app-1/human-input-forms/tok-1"):with pytest.raises(RecipientSurfaceMismatch):@@ -176,8 +206,8 @@ class TestOpenApiHumanInputFormPost:monkeypatch.setattr(module, "db", SimpleNamespace(engine=object()))api = OpenApiWorkflowHumanInputFormSubmitApi()- app_model = SimpleNamespace(id="app-1", tenant_id="tenant-1")- caller = SimpleNamespace(id="acct-42")+ app_model = _make_app()+ caller = _make_account("acct-42")with app.test_request_context("/openapi/v1/apps/app-1/human-input-forms/tok-1:submit",@@ -213,8 +243,8 @@ class TestOpenApiHumanInputFormPost:monkeypatch.setattr(module, "db", SimpleNamespace(engine=object()))api = OpenApiWorkflowHumanInputFormSubmitApi()- app_model = SimpleNamespace(id="app-1", tenant_id="tenant-1")- caller = SimpleNamespace(id="eu-7")+ app_model = _make_app()+ caller = _make_end_user("eu-7")with app.test_request_context("/openapi/v1/apps/app-1/human-input-forms/tok-1:submit",@@ -252,8 +282,8 @@ class TestOpenApiHumanInputFormPost:monkeypatch.setattr(module, "db", SimpleNamespace(engine=object()))api = OpenApiWorkflowHumanInputFormSubmitApi()- app_model = SimpleNamespace(id="app-1", tenant_id="tenant-1")- caller = SimpleNamespace(id="anyone")+ app_model = _make_app()+ caller = _make_end_user("anyone")with app.test_request_context("/openapi/v1/apps/app-1/human-input-forms/tok-1:submit",@@ -275,8 +305,8 @@ class TestOpenApiHumanInputFormPost:from controllers.openapi.human_input_form import OpenApiWorkflowHumanInputFormSubmitApiapi = OpenApiWorkflowHumanInputFormSubmitApi()- app_model = SimpleNamespace(id="app-1", tenant_id="tenant-1")- caller = SimpleNamespace(id="acct-42")+ app_model = _make_app()+ caller = _make_account("acct-42")with app.test_request_context("/openapi/v1/apps/app-1/human-input-forms/tok-1:submit",diff --git a/api/tests/unit_tests/controllers/openapi/test_input_schema.py b/api/tests/unit_tests/controllers/openapi/test_input_schema.pyindex bb042cad089..6e88fa39e54 100644--- a/api/tests/unit_tests/controllers/openapi/test_input_schema.py+++ b/api/tests/unit_tests/controllers/openapi/test_input_schema.py@@ -2,10 +2,14 @@from __future__ import annotations+import json+import pytestfrom sqlalchemy.orm import Sessionfrom controllers.openapi._input_schema import _form_to_jsonschema+from models.model import App, AppMode, AppModelConfig+from models.workflow import Workflow, WorkflowTypedef _wrap(component: dict) -> list[dict]:@@ -88,39 +92,56 @@ def test_max_length_omitted_when_zero() -> None:assert "maxLength" not in props["x"]-from unittest.mock import MagicMock-from controllers.openapi._input_schema import EMPTY_INPUT_SCHEMA, build_input_schemafrom controllers.service_api.app.error import AppUnavailableError-from models.model import AppMode-def _stub_app(mode: AppMode, *, form: list[dict] | None = None, has_workflow: bool | None = None):- """Returns a MagicMock whose explicit config getters are wired up."""- app = MagicMock()- app.id = "00000000-0000-0000-0000-000000000001"- app.mode = mode+def _persist_app(+ session: Session,+ mode: AppMode,+ *,+ form: list[dict] | None = None,+ has_config: bool = True,+) -> App:+ app = App(+ id="00000000-0000-0000-0000-000000000001",+ tenant_id="00000000-0000-0000-0000-000000000002",+ name="Input schema app",+ mode=mode,+ enable_site=False,+ enable_api=True,+ )if mode in (AppMode.WORKFLOW, AppMode.ADVANCED_CHAT):- if has_workflow is False:- app.workflow_with_session.return_value = None- else:- workflow = MagicMock()- workflow.user_input_form.return_value = form or []- workflow.features_dict = {}- app.workflow_with_session.return_value = workflow+ if has_config:+ variables = [body | {"type": row_type} for row in form or [] for row_type, body in row.items()]+ workflow = Workflow(+ id="00000000-0000-0000-0000-000000000004",+ tenant_id=app.tenant_id,+ app_id=app.id,+ type=WorkflowType.CHAT,+ version=Workflow.VERSION_DRAFT,+ graph=json.dumps({"nodes": [{"id": "start", "data": {"type": "start", "variables": variables}}]}),+ features="{}",+ created_by="00000000-0000-0000-0000-000000000003",+ )+ app.workflow_id = workflow.id+ session.add(workflow)else:- if has_workflow is False:- app.app_model_config_with_session.return_value = None- else:- app_model_config = MagicMock()- app_model_config.app_id = app.id- app_model_config.to_dict.return_value = {"user_input_form": form or []}- app.app_model_config_with_session.return_value = app_model_config+ if has_config:+ app_model_config = AppModelConfig(app_id=app.id, user_input_form=json.dumps(form or []))+ app.app_model_config_id = app_model_config.id+ session.add(app_model_config)+ session.add(app)+ session.flush()return appdef test_chat_mode_includes_query(sqlite_session: Session) -> None:- app = _stub_app(AppMode.CHAT, form=[{"text-input": {"variable": "x", "label": "X", "required": True}}])+ app = _persist_app(+ sqlite_session,+ AppMode.CHAT,+ form=[{"text-input": {"variable": "x", "label": "X", "required": True}}],+ )session = sqlite_sessionschema = build_input_schema(app, session=session)assert schema["$schema"] == "https://json-schema.org/draft/2020-12/schema"@@ -130,38 +151,38 @@ def test_chat_mode_includes_query(sqlite_session: Session) -> None:assert "query" in schema["required"]assert "inputs" in schema["required"]assert schema["properties"]["inputs"]["additionalProperties"] is False- app.app_model_config_with_session.assert_called_once_with(session=session)- app.app_model_config_with_session.return_value.to_dict.assert_called_once_with(annotation_reply={"enabled": False})+ assert session.get(AppModelConfig, app.app_model_config_id) is not Nonedef test_agent_chat_mode_includes_query(sqlite_session: Session) -> None:- app = _stub_app(AppMode.AGENT_CHAT, form=[])+ app = _persist_app(sqlite_session, AppMode.AGENT_CHAT, form=[])schema = build_input_schema(app, session=sqlite_session)assert "query" in schema["properties"]def test_advanced_chat_mode_includes_query(sqlite_session: Session) -> None:- app = _stub_app(AppMode.ADVANCED_CHAT, form=[])+ app = _persist_app(sqlite_session, AppMode.ADVANCED_CHAT, form=[])schema = build_input_schema(app, session=sqlite_session)assert "query" in schema["properties"]def test_workflow_mode_omits_query(sqlite_session: Session) -> None:- app = _stub_app(AppMode.WORKFLOW, form=[])+ app = _persist_app(sqlite_session, AppMode.WORKFLOW, form=[])schema = build_input_schema(app, session=sqlite_session)assert "query" not in schema["properties"]assert schema["required"] == ["inputs"]def test_completion_mode_omits_query(sqlite_session: Session) -> None:- app = _stub_app(AppMode.COMPLETION, form=[])+ app = _persist_app(sqlite_session, AppMode.COMPLETION, form=[])schema = build_input_schema(app, session=sqlite_session)assert "query" not in schema["properties"]assert schema["required"] == ["inputs"]def test_inputs_required_driven_by_form(sqlite_session: Session) -> None:- app = _stub_app(+ app = _persist_app(+ sqlite_session,AppMode.CHAT,form=[{"text-input": {"variable": "industry", "label": "Industry", "required": True}},@@ -173,13 +194,13 @@ def test_inputs_required_driven_by_form(sqlite_session: Session) -> None:def test_misconfigured_chat_raises_app_unavailable(sqlite_session: Session) -> None:- app = _stub_app(AppMode.CHAT, has_workflow=False)+ app = _persist_app(sqlite_session, AppMode.CHAT, has_config=False)with pytest.raises(AppUnavailableError):build_input_schema(app, session=sqlite_session)def test_misconfigured_workflow_raises_app_unavailable(sqlite_session: Session) -> None:- app = _stub_app(AppMode.WORKFLOW, has_workflow=False)+ app = _persist_app(sqlite_session, AppMode.WORKFLOW, has_config=False)with pytest.raises(AppUnavailableError):build_input_schema(app, session=sqlite_session)diff --git a/api/tests/unit_tests/controllers/openapi/test_workflow_events_openapi.py b/api/tests/unit_tests/controllers/openapi/test_workflow_events_openapi.pyindex 15044dbba0c..2e6af990003 100644--- a/api/tests/unit_tests/controllers/openapi/test_workflow_events_openapi.py+++ b/api/tests/unit_tests/controllers/openapi/test_workflow_events_openapi.py@@ -19,8 +19,12 @@ from sqlalchemy.orm import sessionmakerfrom werkzeug.exceptions import NotFoundfrom controllers.openapi.auth.data import AuthData+from graphon.enums import WorkflowExecutionStatusfrom libs.oauth_bearer import Scope, TokenType-from models.enums import CreatorUserRole+from models.account import Account+from models.enums import CreatorUserRole, EndUserType, WorkflowRunTriggeredFrom+from models.model import App, AppMode, EndUser+from models.workflow import WorkflowRun, WorkflowTypedef _make_auth_data(app_model, caller, caller_kind):@@ -42,17 +46,51 @@ def _make_workflow_run(created_by_role=CreatorUserRole.ACCOUNT,created_by="acct-1",finished_at=None,-):- return SimpleNamespace(+) -> WorkflowRun:+ return WorkflowRun(id="wf-run-1",app_id=app_id,tenant_id=tenant_id,+ workflow_id="workflow-1",+ type=WorkflowType.CHAT,+ triggered_from=WorkflowRunTriggeredFrom.APP_RUN,+ version="1",+ graph="{}",+ inputs="{}",+ status=WorkflowExecutionStatus.SUCCEEDED,created_by_role=created_by_role,created_by=created_by,finished_at=finished_at,)+def _make_app() -> App:+ return App(+ id="app-1",+ tenant_id="tenant-1",+ name="Workflow events app",+ mode=AppMode.WORKFLOW,+ enable_site=True,+ enable_api=True,+ )+++def _make_account() -> Account:+ account = Account(name="Workflow Events User", email="[email protected]")+ account.id = "acct-1"+ return account+++def _make_end_user() -> EndUser:+ return EndUser(+ id="eu-1",+ tenant_id="tenant-1",+ app_id="app-1",+ type=EndUserType.OPENAPI,+ session_id="session-1",+ )++class TestOpenApiWorkflowEventsApi:@pytest.fixture(autouse=True)def _bind_sqlite_engine(self, monkeypatch: pytest.MonkeyPatch, sqlite_engine: Engine) -> None:@@ -73,10 +111,9 @@ class TestOpenApiWorkflowEventsApi:monkeypatch.setattr(module, "DifyAPIRepositoryFactory", factory_mock)api = self._get_api()- from models.model import AppMode- app_model = SimpleNamespace(id="app-1", tenant_id="tenant-1", mode=AppMode.WORKFLOW)- caller = SimpleNamespace(id="acct-1")+ app_model = _make_app()+ caller = _make_account()with app.test_request_context("/openapi/v1/apps/app-1/tasks/wf-run-1/events"):with pytest.raises(NotFound):@@ -103,10 +140,9 @@ class TestOpenApiWorkflowEventsApi:monkeypatch.setattr(module, "DifyAPIRepositoryFactory", factory_mock)api = self._get_api()- from models.model import AppMode- app_model = SimpleNamespace(id="app-1", tenant_id="tenant-1", mode=AppMode.WORKFLOW)- caller = SimpleNamespace(id="acct-1")+ app_model = _make_app()+ caller = _make_account()with app.test_request_context("/openapi/v1/apps/app-1/tasks/wf-run-1/events"):with pytest.raises(NotFound):@@ -140,10 +176,8 @@ class TestOpenApiWorkflowEventsApi:msg_gen_mock.retrieve_events.return_value = iter([])monkeypatch.setattr(module, "MessageGenerator", lambda: msg_gen_mock)- from models.model import AppMode-- app_model = SimpleNamespace(id="app-1", tenant_id="tenant-1", mode=AppMode.WORKFLOW)- caller = SimpleNamespace(id="acct-1")+ app_model = _make_app()+ caller = _make_account()api = self._get_api()with app.test_request_context("/openapi/v1/apps/app-1/tasks/wf-run-1/events"):@@ -167,10 +201,8 @@ class TestOpenApiWorkflowEventsApi:factory_mock.create_api_workflow_run_repository.return_value = repo_mockmonkeypatch.setattr(module, "DifyAPIRepositoryFactory", factory_mock)- from models.model import AppMode-- app_model = SimpleNamespace(id="app-1", tenant_id="tenant-1", mode=AppMode.WORKFLOW)- caller = SimpleNamespace(id="acct-1")+ app_model = _make_app()+ caller = _make_account()api = self._get_api()with app.test_request_context("/openapi/v1/apps/app-1/tasks/wf-run-1/events"):@@ -202,10 +234,8 @@ class TestOpenApiWorkflowEventsApi:generator_mock.convert_to_event_stream.return_value = iter([])monkeypatch.setattr(module, "WorkflowAppGenerator", lambda: generator_mock)- from models.model import AppMode-- app_model = SimpleNamespace(id="app-1", tenant_id="tenant-1", mode=AppMode.WORKFLOW)- caller = SimpleNamespace(id="eu-1")+ app_model = _make_app()+ caller = _make_end_user()api = self._get_api()with app.test_request_context("/openapi/v1/apps/app-1/tasks/wf-run-1/events"):@@ -242,10 +272,8 @@ class TestOpenApiWorkflowEventsApi:converter_mock.workflow_run_result_to_finish_response.return_value = finish_responsemonkeypatch.setattr(module, "WorkflowResponseConverter", converter_mock)- from models.model import AppMode-- app_model = SimpleNamespace(id="app-1", tenant_id="tenant-1", mode=AppMode.WORKFLOW)- caller = SimpleNamespace(id="acct-1")+ app_model = _make_app()+ caller = _make_account()api = self._get_api()with app.test_request_context("/openapi/v1/apps/app-1/tasks/wf-run-1/events"):diff --git a/api/tests/unit_tests/controllers/web/test_app.py b/api/tests/unit_tests/controllers/web/test_app.pyindex da308ec9051..b6245da2f01 100644--- a/api/tests/unit_tests/controllers/web/test_app.py+++ b/api/tests/unit_tests/controllers/web/test_app.py@@ -11,9 +11,32 @@ from flask import Flaskfrom controllers.web.app import AppAccessMode, AppMeta, AppParameterApi, AppWebAuthPermissionfrom controllers.web.error import AgentNotPublishedError, AppUnavailableErrorfrom core.app.app_config.common.parameters_mapping import get_parameters_from_feature_dict+from models.enums import EndUserType+from models.model import App, AppMode, EndUserfrom services.app_definition_query_service import AppDefinitionNotPublishedError, AppDefinitionUnavailableError+def _make_app() -> App:+ return App(+ id="app-1",+ tenant_id="tenant-1",+ name="Web app",+ mode=AppMode.CHAT,+ enable_site=True,+ enable_api=True,+ )+++def _make_end_user() -> EndUser:+ return EndUser(+ id="end-user-1",+ tenant_id="tenant-1",+ app_id="app-1",+ type=EndUserType.BROWSER,+ session_id="session-1",+ )++# ---------------------------------------------------------------------------# AppParameterApi# ---------------------------------------------------------------------------@@ -26,10 +49,10 @@ class TestAppParameterApi:user_input_form=[],)application_services.return_value = SimpleNamespace(app_definitions=app_definitions)- app_model = SimpleNamespace(id="app-1")+ app_model = _make_app()with app.test_request_context("/parameters"):- result = AppParameterApi().get(app_model, SimpleNamespace())+ result = AppParameterApi().get(app_model, _make_end_user())assert result["opening_statement"] == "Hello"app_definitions.get_public_parameters.assert_called_once_with("app-1")@@ -55,7 +78,7 @@ class TestAppParameterApi:with app.test_request_context("/parameters"):with pytest.raises(http_error):- AppParameterApi().get(SimpleNamespace(id="app-1"), SimpleNamespace())+ AppParameterApi().get(_make_app(), _make_end_user())# ---------------------------------------------------------------------------@@ -67,10 +90,10 @@ class TestAppMeta:app_definitions = MagicMock()app_definitions.get_tool_icons.return_value = {}application_services.return_value = SimpleNamespace(app_definitions=app_definitions)- app_model = SimpleNamespace(id="app-1")+ app_model = _make_app()with app.test_request_context("/meta"):- result = AppMeta().get(app_model, SimpleNamespace())+ result = AppMeta().get(app_model, _make_end_user())assert result == {"tool_icons": {}}app_definitions.get_tool_icons.assert_called_once_with("app-1")@@ -83,7 +106,7 @@ class TestAppMeta:with app.test_request_context("/meta"):with pytest.raises(AppUnavailableError) as raised:- AppMeta().get(SimpleNamespace(id="app-1"), SimpleNamespace())+ AppMeta().get(_make_app(), _make_end_user())assert raised.value.data == {"code": "app_unavailable",