Skip to content

armgit / dify

Public Imported from GitHub
0

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.

refactor(api): thin console app controllers (#42511)

Byron.wang5b6e850b250e
diff --git a/api/controllers/console/agent/app_helpers.py b/api/controllers/console/agent/app_helpers.py
index de401351980..c33ed4e3eb2 100644
--- a/api/controllers/console/agent/app_helpers.py
+++ b/api/controllers/console/agent/app_helpers.py
@@ -6,11 +6,6 @@ from models.model import App
from services.agent.roster_service import AgentRosterService
-def resolve_agent_app_model(*, session: Session, tenant_id: str, agent_id: UUID) -> App:
- """Resolve a roster Agent's public Agent App."""
- return AgentRosterService(session).get_agent_app_model(tenant_id=tenant_id, agent_id=str(agent_id))
-
-
def resolve_agent_runtime_app_model(*, session: Session, tenant_id: str, agent_id: UUID) -> App:
"""Resolve the App that backs an Agent runtime surface.
diff --git a/api/controllers/console/app/advanced_prompt_template.py b/api/controllers/console/app/advanced_prompt_template.py
index 8ded3ff7234..bc96b4f422e 100644
--- a/api/controllers/console/app/advanced_prompt_template.py
+++ b/api/controllers/console/app/advanced_prompt_template.py
@@ -9,10 +9,11 @@ from controllers.common.schema import (
register_response_schema_models,
)
from controllers.console import console_ns
-from controllers.console.wraps import account_initialization_required, model_validate, setup_required
+from controllers.console.flask_admission import console_account_admission
+from controllers.console.wraps import validate_request
+from extensions.ext_application_services import application_services
from fields.base import ResponseModel
-from libs.login import login_required
-from services.advanced_prompt_template_service import AdvancedPromptTemplateArgs, AdvancedPromptTemplateService
+from machinery.context import RequestContext
class AdvancedPromptTemplateQuery(BaseModel):
@@ -45,15 +46,13 @@ class AdvancedPromptTemplateList(Resource):
console_ns.models[AdvancedPromptTemplateResponse.__name__],
)
@console_ns.response(400, "Invalid request parameters")
- @setup_required
- @login_required
- @account_initialization_required
- @model_validate(AdvancedPromptTemplateQuery)
- def get(self, req_data: AdvancedPromptTemplateQuery):
- prompt_args: AdvancedPromptTemplateArgs = {
- "app_mode": req_data.app_mode,
- "model_mode": req_data.model_mode,
- "model_name": req_data.model_name,
- "has_context": req_data.has_context,
- }
- return AdvancedPromptTemplateService.get_prompt(prompt_args)
+ @console_account_admission()
+ def get(self, context: RequestContext):
+ req_data = validate_request(AdvancedPromptTemplateQuery)
+ result = application_services().advanced_prompt_templates.get_prompt(
+ app_mode=req_data.app_mode,
+ model_mode=req_data.model_mode,
+ model_name=req_data.model_name,
+ has_context=req_data.has_context,
+ )
+ return AdvancedPromptTemplateResponse.model_validate(result).model_dump(mode="json", exclude_unset=True)
diff --git a/api/controllers/console/app/agent_app_access.py b/api/controllers/console/app/agent_app_access.py
index b8b81d26bc3..d0d15681513 100644
--- a/api/controllers/console/app/agent_app_access.py
+++ b/api/controllers/console/app/agent_app_access.py
@@ -9,23 +9,18 @@ from uuid import UUID
from flask_restx import Resource
from pydantic import Field
-from sqlalchemy.orm import Session
from controllers.common.rbac import AgentId, RBACCheck
from controllers.common.schema import register_response_schema_models
-from controllers.common.session import with_session
from controllers.console import console_ns
-from controllers.console.agent.app_helpers import resolve_agent_app_model
-from controllers.console.wraps import (
- RBACPermission,
- account_initialization_required,
- rbac_permission_required,
- setup_required,
- with_current_tenant_id,
-)
+from controllers.console.flask_admission import console_account_admission
+from controllers.console.wraps import RBACPermission
+from extensions.ext_application_services import application_services
from fields.base import ResponseModel
-from libs.login import login_required
-from services.agent.roster_service import AgentRosterService
+from libs.helper import dump_response
+from machinery.context import RequestContext
+from services.agent.errors import AgentNotFoundError
+from services.app.agent_app_contracts import AgentAppNotFoundError
class AgentReferencingWorkflowResponse(ResponseModel):
@@ -59,17 +54,10 @@ class AgentAppReferencingWorkflowsResource(Resource):
console_ns.models[AgentReferencingWorkflowsResponse.__name__],
)
@console_ns.response(404, "Agent not found")
- @setup_required
- @login_required
- @account_initialization_required
- @rbac_permission_required(RBACCheck(RBACPermission.AGENT_PREVIEW, AgentId()))
- @with_current_tenant_id
- @with_session(write=False)
- def get(self, session: Session, tenant_id: str, agent_id: UUID):
- app_model = resolve_agent_app_model(session=session, tenant_id=tenant_id, agent_id=agent_id)
- workflows = AgentRosterService(session).list_workflows_referencing_app_agent(
- tenant_id=tenant_id, app_id=app_model.id
- )
- return AgentReferencingWorkflowsResponse(
- data=[AgentReferencingWorkflowResponse.model_validate(workflow) for workflow in workflows]
- ).model_dump(mode="json")
+ @console_account_admission(rbac_checks=(RBACCheck(RBACPermission.AGENT_PREVIEW, AgentId()),))
+ def get(self, context: RequestContext, agent_id: UUID):
+ try:
+ workflows = application_services().agent_apps.access.list_referencing_workflows(context, str(agent_id))
+ except AgentAppNotFoundError as exc:
+ raise AgentNotFoundError from exc
+ return dump_response(AgentReferencingWorkflowsResponse, {"data": workflows})
diff --git a/api/controllers/console/app/agent_app_feature.py b/api/controllers/console/app/agent_app_feature.py
index a826177f8d5..3956a5ec477 100644
--- a/api/controllers/console/app/agent_app_feature.py
+++ b/api/controllers/console/app/agent_app_feature.py
@@ -13,34 +13,24 @@ from uuid import UUID
from flask_restx import Resource
from pydantic import BaseModel, Field
-from sqlalchemy.orm import Session
from controllers.common.fields import SimpleResultResponse
from controllers.common.rbac import AgentId, RBACCheck
from controllers.common.schema import register_response_schema_models, register_schema_models
-from controllers.common.session import with_session
from controllers.console import console_ns
-from controllers.console.agent.app_helpers import resolve_agent_runtime_app_model
-from controllers.console.wraps import (
- RBACPermission,
- account_initialization_required,
- edit_permission_required,
- model_validate,
- rbac_permission_required,
- setup_required,
- with_current_tenant_id,
- with_current_user,
-)
-from events.app_event import app_model_config_was_updated
-from libs.login import login_required
-from models import Account
+from controllers.console.flask_admission import console_account_admission
+from controllers.console.wraps import RBACPermission, validate_request
+from extensions.ext_application_services import application_services
+from machinery.context import RequestContext
+from models.account import TenantAccountRole
from models.agent_config_entities import (
AgentFeatureToggleConfig,
AgentSensitiveWordAvoidanceFeatureConfig,
AgentSuggestedQuestionsAfterAnswerFeatureConfig,
AgentTextToSpeechFeatureConfig,
)
-from services.agent_app_feature_service import AgentAppFeatureConfigService
+from services.agent.errors import AgentNotFoundError
+from services.app.agent_app_contracts import AgentAppNotFoundError
class AgentAppFeaturesPayload(BaseModel):
@@ -80,37 +70,16 @@ class AgentAppFeatureConfigResource(Resource):
@console_ns.response(200, "Features updated successfully", console_ns.models[SimpleResultResponse.__name__])
@console_ns.response(400, "Invalid configuration")
@console_ns.response(404, "Agent not found")
- @setup_required
- @login_required
- @edit_permission_required
- @rbac_permission_required(RBACCheck(RBACPermission.AGENT_EDIT, AgentId()))
- @account_initialization_required
- @with_current_user
- @with_current_tenant_id
- @with_session
- @model_validate(AgentAppFeaturesPayload)
- def post(
- self,
- req_data: AgentAppFeaturesPayload,
- session: Session,
- tenant_id: str,
- current_user: Account,
- agent_id: UUID,
- ):
- app_model = resolve_agent_runtime_app_model(session=session, tenant_id=tenant_id, agent_id=agent_id)
-
- new_app_model_config = AgentAppFeatureConfigService.update_features(
- app_model=app_model,
- account=current_user,
- config=req_data.model_dump(exclude_none=True),
- session=session,
- )
-
- app_model_config_was_updated.send(
- app_model,
- app_model_config=new_app_model_config,
- session=session,
- )
- session.commit()
-
+ @console_account_admission(
+ allowed_roles=frozenset({TenantAccountRole.OWNER, TenantAccountRole.ADMIN, TenantAccountRole.EDITOR}),
+ rbac_checks=(RBACCheck(RBACPermission.AGENT_EDIT, AgentId()),),
+ )
+ def post(self, context: RequestContext, agent_id: UUID):
+ payload = validate_request(AgentAppFeaturesPayload)
+ try:
+ application_services().agent_apps.features.update_features(
+ context, str(agent_id), payload.model_dump(exclude_none=True)
+ )
+ except AgentAppNotFoundError as exc:
+ raise AgentNotFoundError from exc
return SimpleResultResponse(result="success").model_dump(mode="json")
diff --git a/api/controllers/console/app/agent_app_sandbox.py b/api/controllers/console/app/agent_app_sandbox.py
index 165994d5a4e..f9bbb8ea466 100644
--- a/api/controllers/console/app/agent_app_sandbox.py
+++ b/api/controllers/console/app/agent_app_sandbox.py
@@ -24,25 +24,21 @@ from controllers.common.schema import (
)
from controllers.console import console_ns
from controllers.console.app.error import AppNotFoundError
-from controllers.console.app.wraps import get_app_model
-from controllers.console.wraps import (
- RBACPermission,
- account_initialization_required,
- model_validate,
- rbac_permission_required,
- setup_required,
- with_current_tenant_id,
- with_current_user,
-)
-from extensions.ext_database import db
+from controllers.console.flask_admission import console_account_admission
+from controllers.console.wraps import RBACPermission, validate_request
+from extensions.ext_application_services import application_services
from fields.base import ResponseModel
-from libs.login import login_required
-from models import Account
-from models.model import App, AppMode
-from services.agent_app_sandbox_service import (
- AgentAppSandboxService,
- AgentSandboxInspectorError,
- WorkflowAgentSandboxService,
+from libs.helper import dump_response
+from machinery.context import RequestContext
+from services.agent.errors import AgentNotFoundError
+from services.app.agent_app_contracts import (
+ AgentAppNotFoundError,
+ AgentSandboxBindingNotFoundError,
+ AgentSandboxCaller,
+ AgentSandboxDownloadUnavailableError,
+ AgentSandboxUnavailableError,
+ WorkflowSandboxAppNotFoundError,
+ WorkflowSandboxCaller,
)
_BINDING_PATH_DESCRIPTION = (
@@ -134,8 +130,16 @@ register_response_schema_models(
def _handle(exc: Exception) -> tuple[dict[str, object], int]:
- if isinstance(exc, AgentSandboxInspectorError):
- return {"code": exc.code, "message": exc.message}, exc.status_code
+ if isinstance(exc, AgentAppNotFoundError):
+ raise AgentNotFoundError from exc
+ if isinstance(exc, WorkflowSandboxAppNotFoundError):
+ raise AppNotFoundError from exc
+ if isinstance(exc, AgentSandboxBindingNotFoundError):
+ return {"code": "no_active_binding", "message": str(exc)}, 404
+ if isinstance(exc, AgentSandboxUnavailableError):
+ return {"code": "inspector_unavailable", "message": str(exc)}, 503
+ if isinstance(exc, AgentSandboxDownloadUnavailableError):
+ return {"code": "binding_file_download_unavailable", "message": str(exc)}, 502
if isinstance(exc, DifyAgentHTTPError) and backend_reported_failure(exc):
code, message = backend_error_detail(exc)
return {"code": code, "message": message}, exc.status_code
@@ -150,28 +154,16 @@ class AgentAppSandboxInfoResource(Resource):
@console_ns.doc(description="Get basic information for an Agent App conversation sandbox")
@console_ns.doc(params={"agent_id": "Agent ID", **query_params_from_model(AgentSandboxInfoQuery)})
@console_ns.response(200, "Sandbox information returned", console_ns.models[SandboxInfoResponse.__name__])
- @setup_required
- @login_required
- @account_initialization_required
- @rbac_permission_required(RBACCheck(RBACPermission.AGENT_PREVIEW, AgentId()))
- @with_current_tenant_id
- @with_current_user
- def get(self, current_user: Account, tenant_id: str, agent_id: UUID):
- service = AgentAppSandboxService()
- app_id = service.resolve_app_id(tenant_id=tenant_id, agent_id=str(agent_id))
+ @console_account_admission(rbac_checks=(RBACCheck(RBACPermission.AGENT_PREVIEW, AgentId()),))
+ def get(self, context: RequestContext, agent_id: UUID):
query = query_params_from_request(AgentSandboxInfoQuery)
try:
- result = service.get_info(
- tenant_id=tenant_id,
- app_id=app_id,
- agent_id=str(agent_id),
- caller_type=query.caller_type,
- caller_id=query.caller_id,
- account_id=current_user.id,
+ result = application_services().agent_apps.sandbox.get_info(
+ context, AgentSandboxCaller(str(agent_id), query.caller_type, query.caller_id)
)
except Exception as exc:
return _handle(exc)
- return result.model_dump()
+ return dump_response(SandboxInfoResponse, result)
@console_ns.route("/agent/<uuid:agent_id>/sandbox/files")
@@ -180,29 +172,16 @@ class AgentAppSandboxListResource(Resource):
@console_ns.doc(description="List a directory in an Agent App conversation sandbox")
@console_ns.doc(params={"agent_id": "Agent ID", **query_params_from_model(AgentSandboxListQuery)})
@console_ns.response(200, "Listing returned", console_ns.models[SandboxListResponse.__name__])
- @setup_required
- @login_required
- @account_initialization_required
- @rbac_permission_required(RBACCheck(RBACPermission.AGENT_PREVIEW, AgentId()))
- @with_current_tenant_id
- @with_current_user
- def get(self, current_user: Account, tenant_id: str, agent_id: UUID):
- service = AgentAppSandboxService()
- app_id = service.resolve_app_id(tenant_id=tenant_id, agent_id=str(agent_id))
+ @console_account_admission(rbac_checks=(RBACCheck(RBACPermission.AGENT_PREVIEW, AgentId()),))
+ def get(self, context: RequestContext, agent_id: UUID):
query = query_params_from_request(AgentSandboxListQuery)
try:
- result = service.list_files(
- tenant_id=tenant_id,
- app_id=app_id,
- agent_id=str(agent_id),
- caller_type=query.caller_type,
- caller_id=query.caller_id,
- account_id=current_user.id,
- path=query.path,
+ result = application_services().agent_apps.sandbox.list_files(
+ context, AgentSandboxCaller(str(agent_id), query.caller_type, query.caller_id), query.path
)
except Exception as exc:
return _handle(exc)
- return result.model_dump()
+ return dump_response(SandboxListResponse, result)
@console_ns.route("/agent/<uuid:agent_id>/sandbox/files/read")
@@ -211,29 +190,16 @@ class AgentAppSandboxReadResource(Resource):
@console_ns.doc(description="Read a text/binary preview file in an Agent App conversation sandbox")
@console_ns.doc(params={"agent_id": "Agent ID", **query_params_from_model(AgentSandboxFileQuery)})
@console_ns.response(200, "Preview returned", console_ns.models[SandboxReadResponse.__name__])
- @setup_required
- @login_required
- @account_initialization_required
- @rbac_permission_required(RBACCheck(RBACPermission.AGENT_PREVIEW, AgentId()))
- @with_current_tenant_id
- @with_current_user
- def get(self, current_user: Account, tenant_id: str, agent_id: UUID):
- service = AgentAppSandboxService()
- app_id = service.resolve_app_id(tenant_id=tenant_id, agent_id=str(agent_id))
+ @console_account_admission(rbac_checks=(RBACCheck(RBACPermission.AGENT_PREVIEW, AgentId()),))
+ def get(self, context: RequestContext, agent_id: UUID):
query = query_params_from_request(AgentSandboxFileQuery)
try:
- result = service.read_file(
- tenant_id=tenant_id,
- app_id=app_id,
- agent_id=str(agent_id),
- caller_type=query.caller_type,
- caller_id=query.caller_id,
- account_id=current_user.id,
- path=query.path,
+ result = application_services().agent_apps.sandbox.read_file(
+ context, AgentSandboxCaller(str(agent_id), query.caller_type, query.caller_id), query.path
)
except Exception as exc:
return _handle(exc)
- return result.model_dump()
+ return dump_response(SandboxReadResponse, result)
@console_ns.route("/agent/<uuid:agent_id>/sandbox/files/download")
@@ -242,35 +208,16 @@ class AgentAppSandboxDownloadResource(Resource):
@console_ns.doc(description="Create a ToolFile from one Agent App Binding file and return its download URL")
@console_ns.expect(console_ns.models[AgentSandboxDownloadPayload.__name__])
@console_ns.response(200, "Download URL returned", console_ns.models[SandboxDownloadResponse.__name__])
- @setup_required
- @login_required
- @account_initialization_required
- @rbac_permission_required(RBACCheck(RBACPermission.AGENT_EDIT, AgentId()))
- @with_current_tenant_id
- @with_current_user
- @model_validate(AgentSandboxDownloadPayload)
- def post(
- self,
- req_data: AgentSandboxDownloadPayload,
- current_user: Account,
- tenant_id: str,
- agent_id: UUID,
- ):
- service = AgentAppSandboxService()
- app_id = service.resolve_app_id(tenant_id=tenant_id, agent_id=str(agent_id))
+ @console_account_admission(rbac_checks=(RBACCheck(RBACPermission.AGENT_EDIT, AgentId()),))
+ def post(self, context: RequestContext, agent_id: UUID):
+ query = validate_request(AgentSandboxDownloadPayload)
try:
- result = service.download_file(
- tenant_id=tenant_id,
- app_id=app_id,
- agent_id=str(agent_id),
- caller_type=req_data.caller_type,
- caller_id=req_data.caller_id,
- account_id=current_user.id,
- path=req_data.path,
+ result = application_services().agent_apps.sandbox.download_file(
+ context, AgentSandboxCaller(str(agent_id), query.caller_type, query.caller_id), query.path
)
except Exception as exc:
return _handle(exc)
- return result.model_dump()
+ return dump_response(SandboxDownloadResponse, result)
@console_ns.route("/apps/<uuid:app_id>/workflow-runs/<uuid:workflow_run_id>/agent-nodes/<string:node_id>/sandbox/files")
@@ -286,27 +233,18 @@ class WorkflowAgentSandboxListResource(Resource):
}
)
@console_ns.response(200, "Listing returned", console_ns.models[SandboxListResponse.__name__])
- @setup_required
- @login_required
- @account_initialization_required
- @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp()))
- @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])
- @with_current_tenant_id
- def get(self, tenant_id: str, app_model: App, workflow_run_id: UUID, node_id: str):
+ @console_account_admission(rbac_checks=(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp()),))
+ def get(self, context: RequestContext, app_id: UUID, workflow_run_id: UUID, node_id: str):
query = query_params_from_request(WorkflowAgentSandboxListQuery)
try:
- result = WorkflowAgentSandboxService().list_files(
- tenant_id=tenant_id,
- app_id=app_model.id,
- workflow_run_id=str(workflow_run_id),
- node_id=node_id,
- node_execution_id=query.node_execution_id,
- path=query.path,
- session=db.session(),
+ result = application_services().agent_apps.sandbox.list_files(
+ context,
+ WorkflowSandboxCaller(str(app_id), str(workflow_run_id), node_id, query.node_execution_id),
+ query.path,
)
except Exception as exc:
return _handle(exc)
- return result.model_dump()
+ return dump_response(SandboxListResponse, result)
@console_ns.route(
@@ -324,27 +262,18 @@ class WorkflowAgentSandboxReadResource(Resource):
}
)
@console_ns.response(200, "Preview returned", console_ns.models[SandboxReadResponse.__name__])
- @setup_required
- @login_required
- @account_initialization_required
- @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp()))
- @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])
- @with_current_tenant_id
- def get(self, tenant_id: str, app_model: App, workflow_run_id: UUID, node_id: str):
+ @console_account_admission(rbac_checks=(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp()),))
+ def get(self, context: RequestContext, app_id: UUID, workflow_run_id: UUID, node_id: str):
query = query_params_from_request(WorkflowAgentSandboxFileQuery)
try:
- result = WorkflowAgentSandboxService().read_file(
- tenant_id=tenant_id,
- app_id=app_model.id,
- workflow_run_id=str(workflow_run_id),
- node_id=node_id,
- node_execution_id=query.node_execution_id,
- path=query.path,
- session=db.session(),
+ result = application_services().agent_apps.sandbox.read_file(
+ context,
+ WorkflowSandboxCaller(str(app_id), str(workflow_run_id), node_id, query.node_execution_id),
+ query.path,
)
except Exception as exc:
return _handle(exc)
- return result.model_dump()
+ return dump_response(SandboxReadResponse, result)
@console_ns.route(
@@ -355,36 +284,15 @@ class WorkflowAgentSandboxDownloadResource(Resource):
@console_ns.doc(description="Create a ToolFile from one workflow Agent Binding file and return its download URL")
@console_ns.expect(console_ns.models[WorkflowAgentSandboxDownloadPayload.__name__])
@console_ns.response(200, "Download URL returned", console_ns.models[SandboxDownloadResponse.__name__])
- @setup_required
- @login_required
- @account_initialization_required
- @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp()))
- @with_current_user
- @with_current_tenant_id
- @model_validate(WorkflowAgentSandboxDownloadPayload)
- def post(
- self,
- req_data: WorkflowAgentSandboxDownloadPayload,
- tenant_id: str,
- current_user: Account,
- app_id: UUID,
- workflow_run_id: UUID,
- node_id: str,
- ):
- service = WorkflowAgentSandboxService()
- resolved_app_id = service.resolve_app_id(tenant_id=tenant_id, app_id=str(app_id))
- if resolved_app_id is None:
- raise AppNotFoundError()
+ @console_account_admission(rbac_checks=(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp()),))
+ def post(self, context: RequestContext, app_id: UUID, workflow_run_id: UUID, node_id: str):
+ query = validate_request(WorkflowAgentSandboxDownloadPayload)
try:
- result = service.download_file(
- tenant_id=tenant_id,
- app_id=resolved_app_id,
- workflow_run_id=str(workflow_run_id),
- node_id=node_id,
- node_execution_id=req_data.node_execution_id,
- account_id=current_user.id,
- path=req_data.path,
+ result = application_services().agent_apps.sandbox.download_file(
+ context,
+ WorkflowSandboxCaller(str(app_id), str(workflow_run_id), node_id, query.node_execution_id),
+ query.path,
)
except Exception as exc:
return _handle(exc)
- return result.model_dump()
+ return dump_response(SandboxDownloadResponse, result)
diff --git a/api/extensions/application_services/__init__.py b/api/extensions/application_services/__init__.py
new file mode 100644
index 00000000000..d6bebd8e108
--- /dev/null
+++ b/api/extensions/application_services/__init__.py
@@ -0,0 +1 @@
+"""Domain-specific dependency composition for application services."""
diff --git a/api/extensions/application_services/agent.py b/api/extensions/application_services/agent.py
new file mode 100644
index 00000000000..d7aa6b0f9b8
--- /dev/null
+++ b/api/extensions/application_services/agent.py
@@ -0,0 +1,37 @@
+"""Composition of the Agent App console use cases."""
+
+from dataclasses import dataclass
+
+from sqlalchemy.orm import Session, sessionmaker
+
+from configs import dify_config
+from repositories.app.agent_app_repository import AgentAppRepository
+from repositories.app.agent_sandbox_repository import AgentSandboxRepository
+from services.app.agent_app_feature_gateway import AgentAppFeatureValidator
+from services.app.agent_app_sandbox_service import AgentAppSandboxService
+from services.app.agent_app_service import AgentAppAccessService, AgentAppFeatureConfigService
+from services.app.agent_sandbox_file_gateway import AgentSandboxFileGateway, create_sandbox_client
+from services.file_request_service import FileRequestService
+
+
+@dataclass(frozen=True, slots=True)
+class AgentAppServices:
+ access: AgentAppAccessService
+ features: AgentAppFeatureConfigService
+ sandbox: AgentAppSandboxService
+
+
+def build_agent_app_services(*, database_client: sessionmaker[Session]) -> AgentAppServices:
+ apps = AgentAppRepository(session_factory=database_client)
+ return AgentAppServices(
+ access=AgentAppAccessService(references=apps),
+ features=AgentAppFeatureConfigService(features=apps, validator=AgentAppFeatureValidator()),
+ sandbox=AgentAppSandboxService(
+ bindings=AgentSandboxRepository(session_factory=database_client, apps=apps),
+ files=AgentSandboxFileGateway(
+ client_factory=create_sandbox_client,
+ file_requests=FileRequestService(),
+ files_url=dify_config.FILES_URL,
+ ),
+ ),
+ )
diff --git a/api/extensions/ext_application_services.py b/api/extensions/ext_application_services.py
index bc635a9c2f9..9695f44427b 100644
--- a/api/extensions/ext_application_services.py
+++ b/api/extensions/ext_application_services.py
@@ -22,6 +22,7 @@ from core.helper.ssrf_proxy import ssrf_proxy
from core.schemas.schema_manager import SchemaManager
from core.tools.tool_file_manager import ToolFileManager
from enums import DeploymentEdition, WebAppAccessMode
+from extensions.application_services.agent import AgentAppServices, build_agent_app_services
from extensions.ext_redis import RedisClientWrapper, redis_client
from extensions.ext_storage import storage
from libs.datetime_utils import naive_utc_now, utc_now
@@ -138,6 +139,7 @@ from services.account_oauth_service import AccountOAuthService, OAuthProviderGat
from services.account_password_hasher import DefaultAccountPasswordHasher
from services.account_password_service import AccountPasswordService
from services.account_profile_service import AccountProfileService
+from services.app.advanced_prompt_template_service import AdvancedPromptTemplateService
from services.app_audio_adapters import AppAudioRuntime
from services.app_audio_service import AppAudio
from services.app_definition_query_service import AppDefinitionQueryService
@@ -273,6 +275,8 @@ class AppScopedEndUserServices:
@dataclass(frozen=True, slots=True)
class ApplicationServices:
+ agent_apps: AgentAppServices
+ advanced_prompt_templates: AdvancedPromptTemplateService
accounts: AccountServices
account_activation: AccountActivationService
app_definitions: AppDefinitionQueryService
@@ -639,6 +643,8 @@ def build_application_services(
enabled=dify_config.RBAC_ENABLED,
),
),
+ agent_apps=build_agent_app_services(database_client=database_client),
+ advanced_prompt_templates=AdvancedPromptTemplateService(),
app_definitions=AppDefinitionQueryService(
definitions=app_definition_repository,
builtin_icon_url_prefix=(
diff --git a/api/repositories/app/__init__.py b/api/repositories/app/__init__.py
new file mode 100644
index 00000000000..97bad37e664
--- /dev/null
+++ b/api/repositories/app/__init__.py
@@ -0,0 +1 @@
+"""Persistence adapters for App services."""
diff --git a/api/repositories/app/agent_app_repository.py b/api/repositories/app/agent_app_repository.py
new file mode 100644
index 00000000000..78130f791ed
--- /dev/null
+++ b/api/repositories/app/agent_app_repository.py
@@ -0,0 +1,60 @@
+"""Agent App persistence, reusing the roster's canonical app and reference queries."""
+
+from typing import Any, cast
+
+from sqlalchemy import select
+from sqlalchemy.orm import Session, sessionmaker
+
+from events.app_event import app_model_config_was_updated
+from libs.datetime_utils import naive_utc_now
+from models.enums import AppStatus
+from models.model import App, AppMode, AppModelConfig, AppModelConfigDict
+from services.agent.errors import AgentNotFoundError
+from services.agent.roster_service import AgentRosterService
+from services.app.agent_app_contracts import AgentAppNotFoundError, AgentReferencingWorkflow
+
+
+class AgentAppRepository:
+ def __init__(self, *, session_factory: sessionmaker[Session]) -> None:
+ self._session_factory = session_factory
+
+ def resolve_runtime_app_id(self, *, tenant_id: str, agent_id: str) -> str:
+ with self._session_factory() as session:
+ try:
+ return (
+ AgentRosterService(session).get_agent_runtime_app_model(tenant_id=tenant_id, agent_id=agent_id).id
+ )
+ except AgentNotFoundError as exc:
+ raise AgentAppNotFoundError from exc
+
+ def list_referencing_workflows(self, *, tenant_id: str, agent_id: str) -> list[AgentReferencingWorkflow]:
+ with self._session_factory() as session:
+ roster = AgentRosterService(session)
+ try:
+ app = roster.get_agent_app_model(tenant_id=tenant_id, agent_id=agent_id)
+ except AgentNotFoundError as exc:
+ raise AgentAppNotFoundError from exc
+ return roster.list_workflows_referencing_app_agent(tenant_id=tenant_id, app_id=app.id)
+
+ def update_features(self, *, tenant_id: str, app_id: str, account_id: str, config: dict[str, Any]) -> None:
+ """Commit the feature version, app pointer and dataset joins together."""
+ with self._session_factory.begin() as session:
+ app = session.scalar(
+ select(App).where(
+ App.id == app_id,
+ App.tenant_id == tenant_id,
+ App.mode == AppMode.AGENT,
+ App.status == AppStatus.NORMAL,
+ )
+ )
+ if app is None:
+ raise AgentAppNotFoundError
+ new_config = AppModelConfig(
+ app_id=app.id, created_by=account_id, updated_by=account_id
+ ).from_model_config_dict(cast(AppModelConfigDict, config))
+ session.add(new_config)
+ session.flush()
+ app.app_model_config_id = new_config.id
+ app.updated_by = account_id
+ app.updated_at = naive_utc_now()
+ app_model_config_was_updated.send(app, app_model_config=new_config, session=session)
diff --git a/api/repositories/app/agent_sandbox_repository.py b/api/repositories/app/agent_sandbox_repository.py
new file mode 100644
index 00000000000..a1e5c892b79
--- /dev/null
+++ b/api/repositories/app/agent_sandbox_repository.py
@@ -0,0 +1,198 @@
+"""Short-lived database reads for Agent App and workflow sandbox bindings."""
+
+from typing import Literal
+
+from sqlalchemy import select
+from sqlalchemy.orm import Session, sessionmaker
+
+from core.workflow.nodes.agent_v2.session_store import resolve_workflow_agent_workspace_owner_scope
+from machinery.context import RequestContext
+from models.agent import Agent, AgentConfigDraft, AgentConfigDraftType, AgentWorkspaceBinding, AgentWorkspaceOwnerType
+from models.enums import AppStatus
+from models.model import App, AppMode, Conversation, Message
+from models.workflow import WorkflowNodeExecutionModel
+from repositories.app.agent_app_repository import AgentAppRepository
+from services.agent.roster_service import AgentRosterService
+from services.agent.workspace_service import AgentWorkspaceService, WorkspaceOwnerScope
+from services.app.agent_app_contracts import (
+ AgentSandboxBinding,
+ AgentSandboxBindingNotFoundError,
+ AgentSandboxCaller,
+ SandboxCaller,
+ WorkflowSandboxAppNotFoundError,
+)
+
+
+class AgentSandboxRepository:
+ def __init__(self, *, session_factory: sessionmaker[Session], apps: AgentAppRepository) -> None:
+ self._session_factory = session_factory
+ self._apps = apps
+
+ def resolve_binding(self, context: RequestContext, caller: SandboxCaller) -> AgentSandboxBinding:
+ if isinstance(caller, AgentSandboxCaller):
+ app_id = self._apps.resolve_runtime_app_id(tenant_id=context.active_workspace_id, agent_id=caller.agent_id)
+ return self._resolve_agent_binding(
+ tenant_id=context.active_workspace_id,
+ account_id=context.account_id,
+ app_id=app_id,
+ agent_id=caller.agent_id,
+ caller_type=caller.caller_type,
+ caller_id=caller.caller_id,
+ )
+ with self._session_factory() as session:
+ workflow_app_id = session.scalar(
+ select(App.id).where(
+ App.id == caller.app_id,
+ App.tenant_id == context.active_workspace_id,
+ App.status == AppStatus.NORMAL,
+ App.mode.in_((AppMode.ADVANCED_CHAT, AppMode.WORKFLOW)),
+ )
+ )
+ if workflow_app_id is None:
+ raise WorkflowSandboxAppNotFoundError
+ return self._resolve_workflow_binding(
+ tenant_id=context.active_workspace_id,
+ app_id=workflow_app_id,
+ workflow_run_id=caller.workflow_run_id,
+ node_id=caller.node_id,
+ node_execution_id=caller.node_execution_id,
+ session=session,
+ )
+
+ def _resolve_agent_binding(
+ self,
+ *,
+ tenant_id: str,
+ app_id: str,
+ agent_id: str,
+ caller_type: Literal["conversation", "build_draft"],
+ caller_id: str,
+ account_id: str,
+ ) -> AgentSandboxBinding:
+ with self._session_factory() as session:
+ caller: AgentConfigDraft | Conversation | None
+ if caller_type == "build_draft":
+ agent = session.scalar(
+ select(Agent).where(
+ Agent.id == agent_id,
+ Agent.tenant_id == tenant_id,
+ )
+ )
+ if agent is None or AgentRosterService.runtime_backing_app_id(agent) != app_id:
+ caller = None
+ else:
+ caller = session.scalar(
+ select(AgentConfigDraft).where(
+ AgentConfigDraft.id == caller_id,
+ AgentConfigDraft.tenant_id == tenant_id,
+ AgentConfigDraft.agent_id == agent_id,
+ AgentConfigDraft.account_id == account_id,
+ AgentConfigDraft.draft_type == AgentConfigDraftType.DEBUG_BUILD,
+ )
+ )
+ owner_scope = WorkspaceOwnerScope(
+ tenant_id=tenant_id,
+ app_id=app_id,
+ owner_type=AgentWorkspaceOwnerType.BUILD_DRAFT,
+ owner_id=caller_id,
+ )
+ else:
+ caller = session.scalar(
+ select(Conversation)
+ .join(App, App.id == Conversation.app_id)
+ .where(
+ App.tenant_id == tenant_id,
+ Conversation.app_id == app_id,
+ Conversation.id == caller_id,
+ Conversation.from_account_id == account_id,
+ Conversation.is_deleted.is_(False),
+ )
+ )
+ owner_scope = WorkspaceOwnerScope(
+ tenant_id=tenant_id,
+ app_id=app_id,
+ owner_type=AgentWorkspaceOwnerType.CONVERSATION,
+ owner_id=caller_id,
+ )
+ if caller is None or caller.agent_workspace_binding_id is None:
+ raise AgentSandboxBindingNotFoundError(
+ "this caller has no active Agent Workspace Binding",
+ )
+ binding = AgentWorkspaceService.get_active_binding(
+ session=session,
+ tenant_id=tenant_id,
+ binding_id=caller.agent_workspace_binding_id,
+ expected_owner_scope=owner_scope,
+ )
+ if binding is None or binding.app_id != app_id or binding.agent_id != agent_id:
+ raise AgentSandboxBindingNotFoundError(
+ "this caller has no active Agent Workspace Binding",
+ )
+ return _binding_value(binding)
+
+ @staticmethod
+ def _resolve_workflow_binding(
+ *,
+ tenant_id: str,
+ app_id: str,
+ workflow_run_id: str,
+ node_id: str,
+ node_execution_id: str,
+ session: Session,
+ ) -> AgentSandboxBinding:
+ execution = session.scalar(
+ select(WorkflowNodeExecutionModel).where(
+ WorkflowNodeExecutionModel.id == node_execution_id,
+ WorkflowNodeExecutionModel.tenant_id == tenant_id,
+ WorkflowNodeExecutionModel.app_id == app_id,
+ WorkflowNodeExecutionModel.workflow_run_id == workflow_run_id,
+ WorkflowNodeExecutionModel.node_id == node_id,
+ )
+ )
+ process_data = execution.process_data_dict if execution is not None else None
+ workflow_agent_binding_id = process_data.get("workflow_agent_binding_id") if process_data is not None else None
+ if (
+ execution is None
+ or execution.agent_workspace_binding_id is None
+ or not isinstance(workflow_agent_binding_id, str)
+ ):
+ raise AgentSandboxBindingNotFoundError(
+ "this Workflow Agent node execution has no active Workspace Binding",
+ )
+ conversation_id = session.scalar(
+ select(Message.conversation_id)
+ .where(
+ Message.app_id == app_id,
+ Message.workflow_run_id == workflow_run_id,
+ )
+ .limit(1)
+ )
+ binding = AgentWorkspaceService.get_active_binding(
+ session=session,
+ tenant_id=tenant_id,
+ binding_id=execution.agent_workspace_binding_id,
+ expected_owner_scope=resolve_workflow_agent_workspace_owner_scope(
+ tenant_id=tenant_id,
+ app_id=app_id,
+ conversation_id=conversation_id,
+ workflow_run_id=workflow_run_id,
+ node_id=node_id,
+ workflow_agent_binding_id=workflow_agent_binding_id,
+ node_execution_id=node_execution_id,
+ ),
+ )
+ if binding is None or binding.app_id != app_id:
+ raise AgentSandboxBindingNotFoundError(
+ "this Workflow Agent node execution has no active Workspace Binding",
+ )
+ return _binding_value(binding)
+
+
+def _binding_value(binding: AgentWorkspaceBinding) -> AgentSandboxBinding:
+ return AgentSandboxBinding(
+ app_id=binding.app_id,
+ backend_binding_ref=binding.backend_binding_ref,
+ agent_id=binding.agent_id,
+ agent_config_version_id=binding.agent_config_version_id,
+ agent_config_version_kind=binding.agent_config_version_kind.value,
+ )
diff --git a/api/services/agent/roster_service.py b/api/services/agent/roster_service.py
index 6ad45814668..1f53c5861d4 100644
--- a/api/services/agent/roster_service.py
+++ b/api/services/agent/roster_service.py
@@ -1,6 +1,6 @@
import logging
from collections.abc import Sequence
-from typing import Any, TypedDict
+from typing import Any
from uuid import UUID
from sqlalchemy import and_, func, or_, select
@@ -43,6 +43,7 @@ from services.agent.errors import (
AgentVersionNotFoundError,
)
from services.agent.workspace_service import AgentWorkspaceNotFoundError, AgentWorkspaceService, WorkspaceOwnerScope
+from services.app.agent_app_contracts import AgentReferencingWorkflow
from services.app_service import AppService, CreateAppParams
from services.enterprise.enterprise_service import EnterpriseService
from services.entities.agent_entities import RosterAgentCreatePayload, RosterAgentUpdatePayload
@@ -53,21 +54,6 @@ from tasks.collect_agent_resources_task import enqueue_agent_resource_collection
logger = logging.getLogger(__name__)
-class AgentReferencingWorkflow(TypedDict):
- """A workflow app that references a roster Agent via an Agent node."""
-
- app_id: str
- app_name: str
- app_icon_type: str | None
- app_icon: str | None
- app_icon_background: str | None
- app_mode: str
- app_updated_at: int | None
- workflow_id: str
- workflow_version: str
- node_ids: list[str]
-
-
class AgentRosterService:
_APP_MODEL_CONFIG_COPY_FIELDS = (
"opening_statement",
diff --git a/api/services/agent_app_sandbox_service.py b/api/services/agent_app_sandbox_service.py
deleted file mode 100644
index 02deb6f0023..00000000000
--- a/api/services/agent_app_sandbox_service.py
+++ /dev/null
@@ -1,500 +0,0 @@
-"""Resolve product locators to ACTIVE Workspace Bindings and proxy file access."""
-
-from __future__ import annotations
-
-import urllib.parse
-from collections.abc import Callable
-from dataclasses import dataclass
-from typing import Literal, cast
-
-from dify_agent.client import Client
-from dify_agent.layers.execution_context import (
- DifyExecutionContextAgentConfigVersionKind,
- DifyExecutionContextLayerConfig,
-)
-from dify_agent.protocol import (
- BindingFileDownloadRequest,
- BindingFileListResponse,
- BindingFileReadResponse,
-)
-from pydantic import BaseModel
-from sqlalchemy import select
-from sqlalchemy.orm import Session
-
-from clients.agent_backend.factory import create_agent_backend_client
-from configs import dify_config
-from core.db.session_factory import session_factory
-from core.tools.signature import bind_file_uri
-from core.workflow.nodes.agent_v2.session_store import resolve_workflow_agent_workspace_owner_scope
-from models.agent import (
- Agent,
- AgentConfigDraft,
- AgentConfigDraftType,
- AgentWorkspaceBinding,
- AgentWorkspaceOwnerType,
-)
-from models.model import App, AppMode, Conversation, Message
-from models.workflow import WorkflowNodeExecutionModel
-from services.agent.roster_service import AgentRosterService
-from services.agent.workspace_service import AgentWorkspaceService, WorkspaceOwnerScope
-from services.file_request_service import FileRequestService
-
-
-class AgentSandboxInspectorError(Exception):
- code: str
- message: str
- status_code: int
-
- def __init__(self, code: str, message: str, *, status_code: int = 400) -> None:
- super().__init__(message)
- self.code = code
- self.message = message
- self.status_code = status_code
-
-
-class AgentSandboxInfo(BaseModel):
- workspace_cwd: str
-
-
-class AgentSandboxDownload(BaseModel):
- url: str
-
-
-@dataclass(frozen=True, slots=True)
-class _ResolvedBinding:
- """Detached scalar Binding data safe to carry beyond its read transaction.
-
- Resolvers must end the transaction before Dify Agent network I/O; ORM and
- session-bound objects never cross that boundary.
- """
-
- backend_binding_ref: str
- agent_id: str
- agent_config_version_id: str
- agent_config_version_kind: str
-
-
-class AgentAppSandboxService:
- def __init__(self, *, client_factory: Callable[[], Client] | None = None) -> None:
- self._client_factory = client_factory or _default_client_factory
-
- @staticmethod
- def resolve_app_id(*, tenant_id: str, agent_id: str) -> str:
- with session_factory.create_session() as session:
- app = AgentRosterService(session).get_agent_runtime_app_model(
- tenant_id=tenant_id,
- agent_id=agent_id,
- )
- return app.id
-
- def get_info(
- self,
- *,
- tenant_id: str,
- app_id: str,
- agent_id: str,
- caller_type: Literal["conversation", "build_draft"],
- caller_id: str,
- account_id: str,
- ) -> AgentSandboxInfo:
- self._resolve_binding(
- tenant_id=tenant_id,
- app_id=app_id,
- agent_id=agent_id,
- caller_type=caller_type,
- caller_id=caller_id,
- account_id=account_id,
- )
- return AgentSandboxInfo(workspace_cwd=".")
-
- def list_files(
- self,
- *,
- tenant_id: str,
- app_id: str,
- agent_id: str,
- caller_type: Literal["conversation", "build_draft"],
- caller_id: str,
- account_id: str,
- path: str,
- ) -> BindingFileListResponse:
- binding = self._resolve_binding(
- tenant_id=tenant_id,
- app_id=app_id,
- agent_id=agent_id,
- caller_type=caller_type,
- caller_id=caller_id,
- account_id=account_id,
- )
- with self._client_factory() as client:
- return client.list_binding_files_sync(binding.backend_binding_ref, path)
-
- def read_file(
- self,
- *,
- tenant_id: str,
- app_id: str,
- agent_id: str,
- caller_type: Literal["conversation", "build_draft"],
- caller_id: str,
- account_id: str,
- path: str,
- ) -> BindingFileReadResponse:
- binding = self._resolve_binding(
- tenant_id=tenant_id,
- app_id=app_id,
- agent_id=agent_id,
- caller_type=caller_type,
- caller_id=caller_id,
- account_id=account_id,
- )
- with self._client_factory() as client:
- return client.read_binding_file_sync(binding.backend_binding_ref, path)
-
- def download_file(
- self,
- *,
- tenant_id: str,
- app_id: str,
- agent_id: str,
- caller_type: Literal["conversation", "build_draft"],
- caller_id: str,
- account_id: str,
- path: str,
- ) -> AgentSandboxDownload:
- binding = self._resolve_binding(
- tenant_id=tenant_id,
- app_id=app_id,
- agent_id=agent_id,
- caller_type=caller_type,
- caller_id=caller_id,
- account_id=account_id,
- )
- with self._client_factory() as client:
- downloaded = client.download_binding_file_sync(
- BindingFileDownloadRequest(
- backend_binding_ref=binding.backend_binding_ref,
- path=path,
- execution_context=DifyExecutionContextLayerConfig(
- tenant_id=tenant_id,
- user_id=account_id,
- user_from="account",
- app_id=app_id,
- conversation_id=caller_id if caller_type == "conversation" else None,
- agent_id=agent_id,
- agent_config_version_id=binding.agent_config_version_id,
- agent_config_version_kind=cast(
- DifyExecutionContextAgentConfigVersionKind,
- binding.agent_config_version_kind,
- ),
- agent_mode="agent_app",
- invoke_from="debugger",
- ),
- )
- )
- return _download_response(tenant_id=tenant_id, account_id=account_id, reference=downloaded.reference)
-
- @staticmethod
- def _resolve_binding(
- *,
- tenant_id: str,
- app_id: str,
- agent_id: str,
- caller_type: Literal["conversation", "build_draft"],
- caller_id: str,
- account_id: str,
- ) -> _ResolvedBinding:
- with session_factory.create_session() as session:
- caller: AgentConfigDraft | Conversation | None
- if caller_type == "build_draft":
- agent = session.scalar(
- select(Agent).where(
- Agent.id == agent_id,
- Agent.tenant_id == tenant_id,
- )
- )
- if agent is None or AgentRosterService.runtime_backing_app_id(agent) != app_id:
- caller = None
- else:
- caller = session.scalar(
- select(AgentConfigDraft).where(
- AgentConfigDraft.id == caller_id,
- AgentConfigDraft.tenant_id == tenant_id,
- AgentConfigDraft.agent_id == agent_id,
- AgentConfigDraft.account_id == account_id,
- AgentConfigDraft.draft_type == AgentConfigDraftType.DEBUG_BUILD,
- )
- )
- owner_scope = WorkspaceOwnerScope(
- tenant_id=tenant_id,
- app_id=app_id,
- owner_type=AgentWorkspaceOwnerType.BUILD_DRAFT,
- owner_id=caller_id,
- )
- else:
- caller = session.scalar(
- select(Conversation)
- .join(App, App.id == Conversation.app_id)
- .where(
- App.tenant_id == tenant_id,
- Conversation.app_id == app_id,
- Conversation.id == caller_id,
- Conversation.from_account_id == account_id,
- Conversation.is_deleted.is_(False),
- )
- )
- owner_scope = WorkspaceOwnerScope(
- tenant_id=tenant_id,
- app_id=app_id,
- owner_type=AgentWorkspaceOwnerType.CONVERSATION,
- owner_id=caller_id,
- )
- if caller is None or caller.agent_workspace_binding_id is None:
- raise AgentSandboxInspectorError(
- "no_active_binding",
- "this caller has no active Agent Workspace Binding",
- status_code=404,
- )
- binding = AgentWorkspaceService.get_active_binding(
- session=session,
- tenant_id=tenant_id,
- binding_id=caller.agent_workspace_binding_id,
- expected_owner_scope=owner_scope,
- )
- if binding is None or binding.agent_id != agent_id:
- raise AgentSandboxInspectorError(
- "no_active_binding",
- "this caller has no active Agent Workspace Binding",
- status_code=404,
- )
- return _binding_value(binding)
-
-
-class WorkflowAgentSandboxService:
- def __init__(self, *, client_factory: Callable[[], Client] | None = None) -> None:
- self._client_factory = client_factory or _default_client_factory
-
- @staticmethod
- def resolve_app_id(*, tenant_id: str, app_id: str) -> str | None:
- with session_factory.create_session() as session:
- return session.scalar(
- select(App.id).where(
- App.id == app_id,
- App.tenant_id == tenant_id,
- App.status == "normal",
- App.mode.in_((AppMode.ADVANCED_CHAT.value, AppMode.WORKFLOW.value)),
- )
- )
-
- def list_files(
- self,
- *,
- tenant_id: str,
- app_id: str,
- workflow_run_id: str,
- node_id: str,
- node_execution_id: str,
- path: str,
- session: Session,
- ) -> BindingFileListResponse:
- binding = self._resolve_binding(
- tenant_id=tenant_id,
- app_id=app_id,
- workflow_run_id=workflow_run_id,
- node_id=node_id,
- node_execution_id=node_execution_id,
- session=session,
- )
- with self._client_factory() as client:
- return client.list_binding_files_sync(binding.backend_binding_ref, path)
-
- def read_file(
- self,
- *,
- tenant_id: str,
- app_id: str,
- workflow_run_id: str,
- node_id: str,
- node_execution_id: str,
- path: str,
- session: Session,
- ) -> BindingFileReadResponse:
- binding = self._resolve_binding(
- tenant_id=tenant_id,
- app_id=app_id,
- workflow_run_id=workflow_run_id,
- node_id=node_id,
- node_execution_id=node_execution_id,
- session=session,
- )
- with self._client_factory() as client:
- return client.read_binding_file_sync(binding.backend_binding_ref, path)
-
- def download_file(
- self,
- *,
- tenant_id: str,
- app_id: str,
- workflow_run_id: str,
- node_id: str,
- node_execution_id: str,
- account_id: str,
- path: str,
- ) -> AgentSandboxDownload:
- with session_factory.create_session() as session:
- binding = self._resolve_binding(
- tenant_id=tenant_id,
- app_id=app_id,
- workflow_run_id=workflow_run_id,
- node_id=node_id,
- node_execution_id=node_execution_id,
- session=session,
- )
- with self._client_factory() as client:
- downloaded = client.download_binding_file_sync(
- BindingFileDownloadRequest(
- backend_binding_ref=binding.backend_binding_ref,
- path=path,
- execution_context=DifyExecutionContextLayerConfig(
- tenant_id=tenant_id,
- user_id=account_id,
- user_from="account",
- app_id=app_id,
- workflow_run_id=workflow_run_id,
- node_id=node_id,
- node_execution_id=node_execution_id,
- agent_id=binding.agent_id,
- agent_config_version_id=binding.agent_config_version_id,
- agent_config_version_kind=cast(
- DifyExecutionContextAgentConfigVersionKind,
- binding.agent_config_version_kind,
- ),
- agent_mode="workflow_run",
- invoke_from="debugger",
- ),
- )
- )
- return _download_response(tenant_id=tenant_id, account_id=account_id, reference=downloaded.reference)
-
- @staticmethod
- def _resolve_binding(
- *,
- tenant_id: str,
- app_id: str,
- workflow_run_id: str,
- node_id: str,
- node_execution_id: str,
- session: Session,
- ) -> _ResolvedBinding:
- execution = session.scalar(
- select(WorkflowNodeExecutionModel).where(
- WorkflowNodeExecutionModel.id == node_execution_id,
- WorkflowNodeExecutionModel.tenant_id == tenant_id,
- WorkflowNodeExecutionModel.app_id == app_id,
- WorkflowNodeExecutionModel.workflow_run_id == workflow_run_id,
- WorkflowNodeExecutionModel.node_id == node_id,
- )
- )
- process_data = execution.process_data_dict if execution is not None else None
- workflow_agent_binding_id = process_data.get("workflow_agent_binding_id") if process_data is not None else None
- if (
- execution is None
- or execution.agent_workspace_binding_id is None
- or not isinstance(workflow_agent_binding_id, str)
- ):
- raise AgentSandboxInspectorError(
- "no_active_binding",
- "this Workflow Agent node execution has no active Workspace Binding",
- status_code=404,
- )
- conversation_id = session.scalar(
- select(Message.conversation_id)
- .where(
- Message.app_id == app_id,
- Message.workflow_run_id == workflow_run_id,
- )
- .limit(1)
- )
- binding = AgentWorkspaceService.get_active_binding(
- session=session,
- tenant_id=tenant_id,
- binding_id=execution.agent_workspace_binding_id,
- expected_owner_scope=resolve_workflow_agent_workspace_owner_scope(
- tenant_id=tenant_id,
- app_id=app_id,
- conversation_id=conversation_id,
- workflow_run_id=workflow_run_id,
- node_id=node_id,
- workflow_agent_binding_id=workflow_agent_binding_id,
- node_execution_id=node_execution_id,
- ),
- )
- if binding is None:
- raise AgentSandboxInspectorError(
- "no_active_binding",
- "this Workflow Agent node execution has no active Workspace Binding",
- status_code=404,
- )
- resolved = _binding_value(binding)
- # Deliberately end the read transaction before the caller performs Dify Agent I/O.
- session.rollback()
- return resolved
-
-
-def _binding_value(binding: AgentWorkspaceBinding) -> _ResolvedBinding:
- return _ResolvedBinding(
- backend_binding_ref=binding.backend_binding_ref,
- agent_id=binding.agent_id,
- agent_config_version_id=binding.agent_config_version_id,
- agent_config_version_kind=binding.agent_config_version_kind.value,
- )
-
-
-def _download_response(*, tenant_id: str, account_id: str, reference: str) -> AgentSandboxDownload:
- try:
- result = FileRequestService().request_download(
- tenant_id=tenant_id,
- user_id=account_id,
- user_from="account",
- invoke_from="debugger",
- file_mapping={"transfer_method": "tool_file", "reference": reference},
- )
- url = bind_file_uri(result.download_uri, dify_config.FILES_URL)
- except ValueError as exc:
- raise AgentSandboxInspectorError(
- "binding_file_download_unavailable",
- "Binding file could not be converted to a download URL",
- status_code=502,
- ) from exc
- return AgentSandboxDownload(url=_with_as_attachment(url))
-
-
-def _with_as_attachment(url: str) -> str:
- parsed = urllib.parse.urlsplit(url)
- query = urllib.parse.parse_qsl(parsed.query, keep_blank_values=True)
- query.append(("as_attachment", "true"))
- return urllib.parse.urlunsplit(parsed._replace(query=urllib.parse.urlencode(query)))
-
-
-def _default_client_factory() -> Client:
- base_url = dify_config.AGENT_BACKEND_BASE_URL
- if not base_url:
- raise AgentSandboxInspectorError(
- "inspector_unavailable",
- "the Binding file inspector is not available (Agent backend not configured)",
- status_code=503,
- )
- return create_agent_backend_client(
- base_url=base_url,
- api_token=dify_config.AGENT_BACKEND_API_TOKEN,
- binding_file_download_timeout=dify_config.AGENT_BACKEND_BINDING_FILE_DOWNLOAD_TIMEOUT_SECONDS,
- )
-
-
-__all__ = [
- "AgentAppSandboxService",
- "AgentSandboxDownload",
- "AgentSandboxInfo",
- "AgentSandboxInspectorError",
- "WorkflowAgentSandboxService",
-]
diff --git a/api/services/app/__init__.py b/api/services/app/__init__.py
new file mode 100644
index 00000000000..357df5c774c
--- /dev/null
+++ b/api/services/app/__init__.py
@@ -0,0 +1 @@
+"""Application services owned by the App domain."""
diff --git a/api/services/advanced_prompt_template_service.py b/api/services/app/advanced_prompt_template_service.py
similarity index 90%
rename from api/services/advanced_prompt_template_service.py
rename to api/services/app/advanced_prompt_template_service.py
index 5d136e73930..cf6990938c2 100644
--- a/api/services/advanced_prompt_template_service.py
+++ b/api/services/app/advanced_prompt_template_service.py
@@ -1,5 +1,5 @@
import copy
-from typing import Any, TypedDict
+from typing import Any
from core.prompt.prompt_templates.advanced_prompt_templates import (
BAICHUAN_CHAT_APP_CHAT_PROMPT_CONFIG,
@@ -16,23 +16,9 @@ from core.prompt.prompt_templates.advanced_prompt_templates import (
from models.model import AppMode
-class AdvancedPromptTemplateArgs(TypedDict):
- """Expected shape of the args dict passed to AdvancedPromptTemplateService.get_prompt."""
-
- app_mode: str
- model_mode: str
- model_name: str
- has_context: str
-
-
class AdvancedPromptTemplateService:
@classmethod
- def get_prompt(cls, args: AdvancedPromptTemplateArgs) -> dict[str, Any]:
- app_mode = args["app_mode"]
- model_mode = args["model_mode"]
- model_name = args["model_name"]
- has_context = args["has_context"]
-
+ def get_prompt(cls, *, app_mode: str, model_mode: str, model_name: str, has_context: str) -> dict[str, Any]:
if "baichuan" in model_name.lower():
return cls.get_baichuan_prompt(app_mode, model_mode, has_context)
else:
diff --git a/api/services/app/agent_app_contracts.py b/api/services/app/agent_app_contracts.py
new file mode 100644
index 00000000000..ce0e6d5f2c4
--- /dev/null
+++ b/api/services/app/agent_app_contracts.py
@@ -0,0 +1,79 @@
+"""Framework-independent contracts for Agent App console use cases."""
+
+from dataclasses import dataclass
+from typing import Literal, TypedDict
+
+from dify_agent.layers.execution_context import DifyExecutionContextAgentConfigVersionKind
+from pydantic import BaseModel
+
+
+class AgentReferencingWorkflow(TypedDict):
+ """A published workflow app that references a roster Agent."""
+
+ app_id: str
+ app_name: str
+ app_icon_type: str | None
+ app_icon: str | None
+ app_icon_background: str | None
+ app_mode: str
+ app_updated_at: int | None
+ workflow_id: str
+ workflow_version: str
+ node_ids: list[str]
+
+
+@dataclass(frozen=True, slots=True)
+class AgentSandboxCaller:
+ agent_id: str
+ caller_type: Literal["conversation", "build_draft"]
+ caller_id: str
+
+
+@dataclass(frozen=True, slots=True)
+class WorkflowSandboxCaller:
+ app_id: str
+ workflow_run_id: str
+ node_id: str
+ node_execution_id: str
+
+
+type SandboxCaller = AgentSandboxCaller | WorkflowSandboxCaller
+
+
+@dataclass(frozen=True, slots=True)
+class AgentSandboxBinding:
+ """Detached binding values safe to use after the repository closes its session."""
+
+ app_id: str
+ backend_binding_ref: str
+ agent_id: str
+ agent_config_version_id: str
+ agent_config_version_kind: DifyExecutionContextAgentConfigVersionKind
+
+
+class AgentSandboxInfo(BaseModel):
+ workspace_cwd: str
+
+
+class AgentSandboxDownload(BaseModel):
+ url: str
+
+
+class AgentAppNotFoundError(Exception):
+ pass
+
+
+class WorkflowSandboxAppNotFoundError(Exception):
+ pass
+
+
+class AgentSandboxBindingNotFoundError(Exception):
+ pass
+
+
+class AgentSandboxUnavailableError(Exception):
+ pass
+
+
+class AgentSandboxDownloadUnavailableError(Exception):
+ pass
diff --git a/api/services/agent_app_feature_service.py b/api/services/app/agent_app_feature_gateway.py
similarity index 50%
rename from api/services/agent_app_feature_service.py
rename to api/services/app/agent_app_feature_gateway.py
index d336cdf29de..8783a710f54 100644
--- a/api/services/agent_app_feature_service.py
+++ b/api/services/app/agent_app_feature_gateway.py
@@ -1,19 +1,8 @@
-"""Validate and persist the app-level presentation features of an Agent App.
-
-An Agent App keeps its model / prompt / tools in the bound Agent Soul; only the
-PRD "Misc Legacy" presentation features — conversation opener, follow-up
-suggestions, citations, content moderation and speech — live on
-``app_model_config``. This service validates that feature subset and writes a
-new ``app_model_config`` version, mirroring the legacy model-config save flow
-but deliberately never touching model, prompt, tools, datasets or agent_mode
-(those are owned by the Soul and must not be settable through this endpoint).
-"""
+"""Adapter to the shared app feature configuration validators."""
from __future__ import annotations
-from typing import Any, cast
-
-from sqlalchemy.orm import Session
+from typing import Any
from core.app.app_config.common.sensitive_word_avoidance.manager import SensitiveWordAvoidanceConfigManager
from core.app.app_config.features.opening_statement.manager import OpeningStatementConfigManager
@@ -23,13 +12,10 @@ from core.app.app_config.features.suggested_questions_after_answer.manager impor
SuggestedQuestionsAfterAnswerConfigManager,
)
from core.app.app_config.features.text_to_speech.manager import TextToSpeechConfigManager
-from libs.datetime_utils import naive_utc_now
-from models.account import Account
-from models.model import App, AppModelConfig, AppModelConfigDict
-class AgentAppFeatureConfigService:
- """Service for the Agent App presentation-feature config surface."""
+class AgentAppFeatureValidator:
+ """Normalize presentation features with the existing config managers."""
# The only keys this surface accepts. Anything else (model, pre_prompt,
# agent_mode, tools, datasets, user_input_form, ...) is dropped so a caller
@@ -45,7 +31,7 @@ class AgentAppFeatureConfigService:
)
@classmethod
- def validate_features(cls, tenant_id: str, config: dict[str, Any]) -> AppModelConfigDict:
+ def validate_features(cls, tenant_id: str, config: dict[str, Any]) -> dict[str, Any]:
"""Validate and normalize the feature subset, filling defaults."""
working = {key: config[key] for key in cls.ALLOWED_KEYS if key in config}
@@ -65,40 +51,4 @@ class AgentAppFeatureConfigService:
related_keys.extend(keys)
filtered = {key: working.get(key) for key in set(related_keys)}
- return cast(AppModelConfigDict, filtered)
-
- @classmethod
- def update_features(
- cls,
- *,
- app_model: App,
- account: Account,
- config: dict[str, Any],
- session: Session,
- ) -> AppModelConfig:
- """Persist the presentation features as a new app_model_config version.
-
- Returns the new ``AppModelConfig`` row (now referenced by the app); the
- row carries only feature flags, with model / prompt / agent_mode left
- ``NULL`` so the Agent Soul remains the single source of truth for those.
- """
- validated = cls.validate_features(app_model.tenant_id, config)
-
- new_config = AppModelConfig(
- app_id=app_model.id,
- created_by=account.id,
- updated_by=account.id,
- ).from_model_config_dict(validated)
-
- session.add(new_config)
- session.flush()
-
- app_model.app_model_config_id = new_config.id
- app_model.updated_by = account.id
- app_model.updated_at = naive_utc_now()
- session.commit()
-
- return new_config
-
-
-__all__ = ["AgentAppFeatureConfigService"]
+ return filtered
diff --git a/api/services/app/agent_app_sandbox_service.py b/api/services/app/agent_app_sandbox_service.py
new file mode 100644
index 00000000000..d0db1dc6043
--- /dev/null
+++ b/api/services/app/agent_app_sandbox_service.py
@@ -0,0 +1,49 @@
+"""Resolve an admitted sandbox caller before invoking the file gateway."""
+
+from typing import Protocol
+
+from dify_agent.protocol import BindingFileListResponse, BindingFileReadResponse
+
+from machinery.context import RequestContext
+from services.app.agent_app_contracts import (
+ AgentSandboxBinding,
+ AgentSandboxDownload,
+ AgentSandboxInfo,
+ SandboxCaller,
+)
+
+
+class AgentSandboxBindings(Protocol):
+ def resolve_binding(self, context: RequestContext, caller: SandboxCaller) -> AgentSandboxBinding: ...
+
+
+class AgentSandboxFiles(Protocol):
+ def list_files(self, binding: AgentSandboxBinding, path: str) -> BindingFileListResponse: ...
+
+ def read_file(self, binding: AgentSandboxBinding, path: str) -> BindingFileReadResponse: ...
+
+ def download_file(
+ self, context: RequestContext, caller: SandboxCaller, binding: AgentSandboxBinding, path: str
+ ) -> AgentSandboxDownload: ...
+
+
+class AgentAppSandboxService:
+ def __init__(self, *, bindings: AgentSandboxBindings, files: AgentSandboxFiles) -> None:
+ self._bindings = bindings
+ self._files = files
+
+ def get_info(self, context: RequestContext, caller: SandboxCaller) -> AgentSandboxInfo:
+ self._bindings.resolve_binding(context, caller)
+ return AgentSandboxInfo(workspace_cwd=".")
+
+ def list_files(self, context: RequestContext, caller: SandboxCaller, path: str) -> BindingFileListResponse:
+ binding = self._bindings.resolve_binding(context, caller)
+ return self._files.list_files(binding, path)
+
+ def read_file(self, context: RequestContext, caller: SandboxCaller, path: str) -> BindingFileReadResponse:
+ binding = self._bindings.resolve_binding(context, caller)
+ return self._files.read_file(binding, path)
+
+ def download_file(self, context: RequestContext, caller: SandboxCaller, path: str) -> AgentSandboxDownload:
+ binding = self._bindings.resolve_binding(context, caller)
+ return self._files.download_file(context, caller, binding, path)
diff --git a/api/services/app/agent_app_service.py b/api/services/app/agent_app_service.py
new file mode 100644
index 00000000000..b0164585998
--- /dev/null
+++ b/api/services/app/agent_app_service.py
@@ -0,0 +1,44 @@
+"""Application services for Agent App workflow references and presentation features."""
+
+from typing import Any, Protocol
+
+from machinery.context import RequestContext
+from services.app.agent_app_contracts import AgentReferencingWorkflow
+
+
+class AgentAppReferences(Protocol):
+ def list_referencing_workflows(self, *, tenant_id: str, agent_id: str) -> list[AgentReferencingWorkflow]: ...
+
+
+class AgentAppFeatures(Protocol):
+ def resolve_runtime_app_id(self, *, tenant_id: str, agent_id: str) -> str: ...
+
+ def update_features(self, *, tenant_id: str, app_id: str, account_id: str, config: dict[str, Any]) -> None: ...
+
+
+class AgentFeatureValidator(Protocol):
+ def validate_features(self, tenant_id: str, config: dict[str, Any]) -> dict[str, Any]: ...
+
+
+class AgentAppAccessService:
+ def __init__(self, *, references: AgentAppReferences) -> None:
+ self._references = references
+
+ def list_referencing_workflows(self, context: RequestContext, agent_id: str) -> list[AgentReferencingWorkflow]:
+ return self._references.list_referencing_workflows(tenant_id=context.active_workspace_id, agent_id=agent_id)
+
+
+class AgentAppFeatureConfigService:
+ def __init__(self, *, features: AgentAppFeatures, validator: AgentFeatureValidator) -> None:
+ self._features = features
+ self._validator = validator
+
+ def update_features(self, context: RequestContext, agent_id: str, config: dict[str, Any]) -> None:
+ app_id = self._features.resolve_runtime_app_id(tenant_id=context.active_workspace_id, agent_id=agent_id)
+ validated = self._validator.validate_features(context.active_workspace_id, config)
+ self._features.update_features(
+ tenant_id=context.active_workspace_id,
+ app_id=app_id,
+ account_id=context.account_id,
+ config=validated,
+ )
diff --git a/api/services/app/agent_sandbox_file_gateway.py b/api/services/app/agent_sandbox_file_gateway.py
new file mode 100644
index 00000000000..72eb21f00b3
--- /dev/null
+++ b/api/services/app/agent_sandbox_file_gateway.py
@@ -0,0 +1,98 @@
+"""Agent backend and ToolFile adapters for sandbox file access."""
+
+import urllib.parse
+from collections.abc import Callable
+from contextlib import AbstractContextManager
+
+from dify_agent.client import Client
+from dify_agent.layers.execution_context import DifyExecutionContextLayerConfig
+from dify_agent.protocol import BindingFileDownloadRequest, BindingFileListResponse, BindingFileReadResponse
+
+from clients.agent_backend.factory import create_agent_backend_client
+from configs import dify_config
+from core.tools.signature import bind_file_uri
+from machinery.context import RequestContext
+from services.app.agent_app_contracts import (
+ AgentSandboxBinding,
+ AgentSandboxCaller,
+ AgentSandboxDownload,
+ AgentSandboxDownloadUnavailableError,
+ AgentSandboxUnavailableError,
+ SandboxCaller,
+)
+from services.file_request_service import FileRequestService
+
+
+class AgentSandboxFileGateway:
+ def __init__(
+ self,
+ *,
+ client_factory: Callable[[], AbstractContextManager[Client]],
+ file_requests: FileRequestService,
+ files_url: str,
+ ) -> None:
+ self._client_factory = client_factory
+ self._file_requests = file_requests
+ self._files_url = files_url
+
+ def list_files(self, binding: AgentSandboxBinding, path: str) -> BindingFileListResponse:
+ with self._client_factory() as client:
+ return client.list_binding_files_sync(binding.backend_binding_ref, path)
+
+ def read_file(self, binding: AgentSandboxBinding, path: str) -> BindingFileReadResponse:
+ with self._client_factory() as client:
+ return client.read_binding_file_sync(binding.backend_binding_ref, path)
+
+ def download_file(
+ self, context: RequestContext, caller: SandboxCaller, binding: AgentSandboxBinding, path: str
+ ) -> AgentSandboxDownload:
+ execution_context = DifyExecutionContextLayerConfig(
+ tenant_id=context.active_workspace_id,
+ user_id=context.account_id,
+ user_from="account",
+ app_id=binding.app_id,
+ agent_id=binding.agent_id,
+ agent_config_version_id=binding.agent_config_version_id,
+ agent_config_version_kind=binding.agent_config_version_kind,
+ agent_mode="agent_app" if isinstance(caller, AgentSandboxCaller) else "workflow_run",
+ invoke_from="debugger",
+ )
+ if isinstance(caller, AgentSandboxCaller):
+ execution_context.conversation_id = caller.caller_id if caller.caller_type == "conversation" else None
+ else:
+ execution_context.workflow_run_id = caller.workflow_run_id
+ execution_context.node_id = caller.node_id
+ execution_context.node_execution_id = caller.node_execution_id
+ with self._client_factory() as client:
+ downloaded = client.download_binding_file_sync(
+ BindingFileDownloadRequest(
+ backend_binding_ref=binding.backend_binding_ref,
+ path=path,
+ execution_context=execution_context,
+ )
+ )
+ try:
+ result = self._file_requests.request_download(
+ tenant_id=context.active_workspace_id,
+ user_id=context.account_id,
+ user_from="account",
+ invoke_from="debugger",
+ file_mapping={"transfer_method": "tool_file", "reference": downloaded.reference},
+ )
+ url = bind_file_uri(result.download_uri, self._files_url)
+ except ValueError as exc:
+ raise AgentSandboxDownloadUnavailableError("Binding file could not be converted to a download URL") from exc
+ parsed = urllib.parse.urlsplit(url)
+ query = urllib.parse.parse_qsl(parsed.query, keep_blank_values=True)
+ query.append(("as_attachment", "true"))
+ return AgentSandboxDownload(url=urllib.parse.urlunsplit(parsed._replace(query=urllib.parse.urlencode(query))))
+
+
+def create_sandbox_client() -> Client:
+ if not dify_config.AGENT_BACKEND_BASE_URL:
+ raise AgentSandboxUnavailableError("the Binding file inspector is not available (Agent backend not configured)")
+ return create_agent_backend_client(
+ base_url=dify_config.AGENT_BACKEND_BASE_URL,
+ api_token=dify_config.AGENT_BACKEND_API_TOKEN,
+ binding_file_download_timeout=dify_config.AGENT_BACKEND_BINDING_FILE_DOWNLOAD_TIMEOUT_SECONDS,
+ )
diff --git a/api/tests/test_containers_integration_tests/services/test_advanced_prompt_template_service.py b/api/tests/test_containers_integration_tests/services/test_advanced_prompt_template_service.py
index f78037e5033..5ea3c06e77d 100644
--- a/api/tests/test_containers_integration_tests/services/test_advanced_prompt_template_service.py
+++ b/api/tests/test_containers_integration_tests/services/test_advanced_prompt_template_service.py
@@ -17,7 +17,7 @@ from core.prompt.prompt_templates.advanced_prompt_templates import (
CONTEXT,
)
from models.model import AppMode
-from services.advanced_prompt_template_service import AdvancedPromptTemplateService
+from services.app.advanced_prompt_template_service import AdvancedPromptTemplateService
class TestAdvancedPromptTemplateService:
@@ -52,7 +52,7 @@ class TestAdvancedPromptTemplateService:
}
# Act: Execute the method under test
- result = AdvancedPromptTemplateService.get_prompt(args)
+ result = AdvancedPromptTemplateService.get_prompt(**args)
# Assert: Verify the expected outcomes
assert result is not None
@@ -89,7 +89,7 @@ class TestAdvancedPromptTemplateService:
}
# Act: Execute the method under test
- result = AdvancedPromptTemplateService.get_prompt(args)
+ result = AdvancedPromptTemplateService.get_prompt(**args)
# Assert: Verify the expected outcomes
assert result is not None
@@ -128,7 +128,7 @@ class TestAdvancedPromptTemplateService:
}
# Act: Execute the method under test
- result = AdvancedPromptTemplateService.get_prompt(args)
+ result = AdvancedPromptTemplateService.get_prompt(**args)
# Assert: Verify Baichuan template is used
assert result is not None
@@ -651,7 +651,7 @@ class TestAdvancedPromptTemplateService:
}
# Act: Execute the method under test
- result = AdvancedPromptTemplateService.get_prompt(args)
+ result = AdvancedPromptTemplateService.get_prompt(**args)
# Assert: Verify result is not empty
assert result is not None
@@ -683,7 +683,7 @@ class TestAdvancedPromptTemplateService:
}
# Act: Execute the method under test
- result = AdvancedPromptTemplateService.get_prompt(args)
+ result = AdvancedPromptTemplateService.get_prompt(**args)
# Assert: Verify result is not empty
assert result is not None
@@ -715,7 +715,7 @@ class TestAdvancedPromptTemplateService:
for args in edge_cases:
# Act: Execute the method under test
- result = AdvancedPromptTemplateService.get_prompt(args)
+ result = AdvancedPromptTemplateService.get_prompt(**args)
# Assert: Verify method handles edge cases gracefully
# Should either return a valid result or empty dict, but not crash
@@ -747,7 +747,7 @@ class TestAdvancedPromptTemplateService:
}
# Act: Execute the method under test
- result = AdvancedPromptTemplateService.get_prompt(args)
+ result = AdvancedPromptTemplateService.get_prompt(**args)
# Assert: Verify original templates are unchanged
assert original_chat_completion == CHAT_APP_COMPLETION_PROMPT_CONFIG
@@ -783,7 +783,7 @@ class TestAdvancedPromptTemplateService:
}
# Act: Execute the method under test
- result = AdvancedPromptTemplateService.get_prompt(args)
+ result = AdvancedPromptTemplateService.get_prompt(**args)
# Assert: Verify original templates are unchanged
assert original_baichuan_chat_completion == BAICHUAN_CHAT_APP_COMPLETION_PROMPT_CONFIG
@@ -834,7 +834,7 @@ class TestAdvancedPromptTemplateService:
for args in test_scenarios:
# Act: Execute the method under test
- result = AdvancedPromptTemplateService.get_prompt(args)
+ result = AdvancedPromptTemplateService.get_prompt(**args)
# Assert: Verify context integration is consistent
assert result is not None
@@ -891,7 +891,7 @@ class TestAdvancedPromptTemplateService:
for args in test_scenarios:
# Act: Execute the method under test
- result = AdvancedPromptTemplateService.get_prompt(args)
+ result = AdvancedPromptTemplateService.get_prompt(**args)
# Assert: Verify context integration is consistent
assert result is not None
diff --git a/api/tests/unit_tests/clients/agent_backend/test_factory.py b/api/tests/unit_tests/clients/agent_backend/test_factory.py
index 490c1bc6360..4d0ae631a89 100644
--- a/api/tests/unit_tests/clients/agent_backend/test_factory.py
+++ b/api/tests/unit_tests/clients/agent_backend/test_factory.py
@@ -7,8 +7,8 @@ from dify_agent.client import Client
from clients.agent_backend.factory import create_agent_backend_client, create_agent_backend_run_client
from configs import dify_config
-from services import agent_app_sandbox_service
from services.agent import home_snapshot_service, workspace_service
+from services.app import agent_sandbox_file_gateway
from tests.unit_tests.config_override import apply_config_overrides
@@ -67,8 +67,8 @@ def test_create_agent_backend_run_client_forwards_stream_read_timeout(create_cli
{"timeout": dify_config.AGENT_BACKEND_HOME_SNAPSHOT_TIMEOUT_SECONDS},
),
(
- agent_app_sandbox_service._default_client_factory,
- agent_app_sandbox_service,
+ agent_sandbox_file_gateway.create_sandbox_client,
+ agent_sandbox_file_gateway,
{"binding_file_download_timeout": 123.5},
),
],
diff --git a/api/tests/unit_tests/controllers/console/agent/test_app_helpers.py b/api/tests/unit_tests/controllers/console/agent/test_app_helpers.py
index 8ad20b6b84c..0c7eb73889b 100644
--- a/api/tests/unit_tests/controllers/console/agent/test_app_helpers.py
+++ b/api/tests/unit_tests/controllers/console/agent/test_app_helpers.py
@@ -13,30 +13,6 @@ def _app() -> App:
return make_app(name="Agent App", mode=AppMode.AGENT, icon_type=None)
-def test_resolve_agent_app_model_reuses_caller_session(
- monkeypatch: pytest.MonkeyPatch, unbound_session: Session
-) -> None:
- session = unbound_session
- app = _app()
- service = MagicMock()
- service.get_agent_app_model.return_value = app
- service_factory = MagicMock(return_value=service)
- monkeypatch.setattr(app_helpers, "AgentRosterService", service_factory)
-
- result = app_helpers.resolve_agent_app_model(
- session=session,
- tenant_id="tenant-1",
- agent_id=UUID("00000000-0000-0000-0000-000000000001"),
- )
-
- assert result is app
- service_factory.assert_called_once_with(session)
- service.get_agent_app_model.assert_called_once_with(
- tenant_id="tenant-1",
- agent_id="00000000-0000-0000-0000-000000000001",
- )
-
-
def test_resolve_agent_runtime_app_model_reuses_caller_session(
monkeypatch: pytest.MonkeyPatch, unbound_session: Session
) -> None:
diff --git a/api/tests/unit_tests/controllers/console/app/test_agent_app_boundaries.py b/api/tests/unit_tests/controllers/console/app/test_agent_app_boundaries.py
new file mode 100644
index 00000000000..e72706a9d99
--- /dev/null
+++ b/api/tests/unit_tests/controllers/console/app/test_agent_app_boundaries.py
@@ -0,0 +1,140 @@
+"""Console admission and transport contracts for Agent App features and references."""
+
+from dataclasses import dataclass, field
+from inspect import unwrap
+from uuid import UUID
+
+import pytest
+from flask import Flask
+from werkzeug.exceptions import Forbidden
+
+from controllers.console import flask_admission
+from controllers.console.app import advanced_prompt_template, agent_app_access, agent_app_feature
+from libs.login import AccountWithTenant
+from machinery.context import RequestContext
+from models.account import TenantAccountRole
+from services.agent.errors import AgentNotFoundError
+from services.app.advanced_prompt_template_service import AdvancedPromptTemplateService
+from services.app.agent_app_contracts import AgentAppNotFoundError, AgentReferencingWorkflow
+from tests.unit_tests.config_override import apply_config_overrides
+from tests.unit_tests.controllers.rbac_introspection import rbac_checks
+from tests.unit_tests.model_factories import make_account
+
+CONTEXT = RequestContext("request", None, "actor", "tenant")
+AGENT_ID = UUID("11111111-1111-1111-1111-111111111111")
+
+
+@dataclass
+class FeatureService:
+ calls: list[tuple[RequestContext, str, dict[str, object]]] = field(default_factory=list)
+
+ def update_features(self, context: RequestContext, agent_id: str, config: dict[str, object]) -> None:
+ self.calls.append((context, agent_id, config))
+
+
+@dataclass
+class AccessService:
+ calls: list[tuple[RequestContext, str]] = field(default_factory=list)
+ missing: bool = False
+
+ def list_referencing_workflows(self, context: RequestContext, agent_id: str) -> list[AgentReferencingWorkflow]:
+ self.calls.append((context, agent_id))
+ if self.missing:
+ raise AgentAppNotFoundError
+ return [
+ AgentReferencingWorkflow(
+ app_id="workflow-app",
+ app_name="Workflow",
+ app_mode="workflow",
+ app_icon_type=None,
+ app_icon=None,
+ app_icon_background=None,
+ app_updated_at=123,
+ workflow_id="workflow",
+ workflow_version="published",
+ node_ids=["node"],
+ )
+ ]
+
+
+@dataclass
+class AgentServices:
+ features: FeatureService = field(default_factory=FeatureService)
+ access: AccessService = field(default_factory=AccessService)
+
+
+@dataclass
+class Services:
+ agent_apps: AgentServices = field(default_factory=AgentServices)
+ advanced_prompt_templates: AdvancedPromptTemplateService = field(default_factory=AdvancedPromptTemplateService)
+
+
+def services(monkeypatch: pytest.MonkeyPatch) -> Services:
+ services = Services()
+ for module in (agent_app_feature, agent_app_access, advanced_prompt_template):
+ monkeypatch.setattr(module, "application_services", lambda: services)
+ return services
+
+
+def test_features_parse_full_state_and_drop_soul_fields(app: Flask, services: Services) -> None:
+ with app.test_request_context(
+ "/", method="POST", json={"opening_statement": "Hi", "speech_to_text": None, "model": {"name": "x"}}
+ ):
+ result = unwrap(agent_app_feature.AgentAppFeatureConfigResource.post)(object(), CONTEXT, AGENT_ID)
+ assert result == {"result": "success"}
+ assert services.agent_apps.features.calls == [(CONTEXT, str(AGENT_ID), {"opening_statement": "Hi"})]
+
+
[email protected]("role", list(TenantAccountRole))
+def test_feature_admission_enforces_editing_roles(
+ app: Flask, services: Services, monkeypatch: pytest.MonkeyPatch, role: TenantAccountRole
+) -> None:
+ apply_config_overrides(monkeypatch, RBAC_ENABLED=False)
+ account = make_account(account_id="actor", name="Editor", email="[email protected]", role=role)
+ monkeypatch.setattr(flask_admission, "current_account_with_tenant", lambda: AccountWithTenant(account, "tenant"))
+ monkeypatch.setattr(flask_admission, "get_request_id", lambda: "request")
+ monkeypatch.setattr(flask_admission, "get_trace_id", lambda: None)
+ # Exercise the declared admission policy after setup/login/initialization.
+ view = agent_app_feature.AgentAppFeatureConfigResource.post
+ while hasattr(view.__wrapped__, "__wrapped__"):
+ view = view.__wrapped__
+ with app.test_request_context("/", method="POST", json={}):
+ if role in (TenantAccountRole.OWNER, TenantAccountRole.ADMIN, TenantAccountRole.EDITOR):
+ assert view(object(), agent_id=AGENT_ID) == {"result": "success"}
+ assert services.agent_apps.features.calls == [(CONTEXT, str(AGENT_ID), {})]
+ else:
+ with pytest.raises(Forbidden):
+ view(object(), agent_id=AGENT_ID)
+ assert services.agent_apps.features.calls == []
+
+
+def test_agent_endpoints_keep_rbac_scenes() -> None:
+ for view, scene in (
+ (agent_app_feature.AgentAppFeatureConfigResource.post, agent_app_feature.RBACPermission.AGENT_EDIT),
+ (agent_app_access.AgentAppReferencingWorkflowsResource.get, agent_app_access.RBACPermission.AGENT_PREVIEW),
+ ):
+ [check] = rbac_checks(view)
+ assert isinstance(check.locator, agent_app_access.AgentId)
+ assert check.scene == scene
+
+
+def test_access_serializes_workflow_metadata(services: Services) -> None:
+ result = unwrap(agent_app_access.AgentAppReferencingWorkflowsResource.get)(object(), CONTEXT, AGENT_ID)
+ assert services.agent_apps.access.calls == [(CONTEXT, str(AGENT_ID))]
+ assert result["data"][0]["node_ids"] == ["node"]
+ assert result["data"][0]["app_updated_at"] == 123
+ services.agent_apps.access.missing = True
+ with pytest.raises(AgentNotFoundError):
+ unwrap(agent_app_access.AgentAppReferencingWorkflowsResource.get)(object(), CONTEXT, AGENT_ID)
+
+
[email protected]("app_mode", ["chat", "completion", "invalid"])
[email protected]("services")
+def test_prompt_response_preserves_omitted_fields(app: Flask, app_mode: str) -> None:
+ with app.test_request_context("/", query_string={"app_mode": app_mode, "model_mode": "chat", "model_name": "gpt"}):
+ result = unwrap(advanced_prompt_template.AdvancedPromptTemplateList.get)(object(), CONTEXT)
+ if app_mode == "invalid":
+ assert result == {}
+ else:
+ assert set(result) == {"chat_prompt_config"}
diff --git a/api/tests/unit_tests/controllers/console/app/test_agent_app_sandbox.py b/api/tests/unit_tests/controllers/console/app/test_agent_app_sandbox.py
index 077b166917f..6b95d61976e 100644
--- a/api/tests/unit_tests/controllers/console/app/test_agent_app_sandbox.py
+++ b/api/tests/unit_tests/controllers/console/app/test_agent_app_sandbox.py
@@ -1,278 +1,181 @@
-from __future__ import annotations
+"""Transport parsing, permission declarations and sandbox error serialization."""
+from collections.abc import Callable
+from dataclasses import dataclass
from inspect import unwrap
-from types import FunctionType, SimpleNamespace
+from uuid import UUID
import pytest
from dify_agent.client import DifyAgentClientError, DifyAgentHTTPError, DifyAgentTimeoutError
from dify_agent.protocol import BindingFileListResponse, BindingFileReadResponse
+from flask import Flask
+from flask_restx import Resource
from controllers.console import agent_app_sandbox as module
-from models.account import Account
-from models.model import App, AppMode, IconType
-from services.agent_app_sandbox_service import AgentSandboxDownload, AgentSandboxInfo, AgentSandboxInspectorError
+from machinery.context import RequestContext
+from services.agent.errors import AgentNotFoundError
+from services.app.agent_app_contracts import (
+ AgentAppNotFoundError,
+ AgentSandboxBindingNotFoundError,
+ AgentSandboxCaller,
+ AgentSandboxDownload,
+ AgentSandboxDownloadUnavailableError,
+ AgentSandboxInfo,
+ AgentSandboxUnavailableError,
+ SandboxCaller,
+ WorkflowSandboxAppNotFoundError,
+ WorkflowSandboxCaller,
+)
from tests.unit_tests.controllers.rbac_introspection import rbac_checks
-from tests.unit_tests.model_factories import make_account
+
+CONTEXT = RequestContext("request", "trace", "actor", "workspace")
+RESOURCE_ID = UUID("11111111-1111-1111-1111-111111111111")
-class _AgentAppService:
+class SandboxService:
def __init__(self) -> None:
- self.calls: list[tuple[str, str, str, str, str, str, str, str]] = []
+ self.calls: list[tuple[str, RequestContext, SandboxCaller, str]] = []
+ self.error: Exception | None = None
- def resolve_app_id(self, *, tenant_id: str, agent_id: str) -> str:
- return "app-1"
+ def record(self, operation: str, context: RequestContext, caller: SandboxCaller, path: str = "") -> None:
+ self.calls.append((operation, context, caller, path))
+ if self.error:
+ raise self.error
- def get_info(
- self,
- *,
- tenant_id: str,
- app_id: str,
- agent_id: str,
- caller_type: str,
- caller_id: str,
- account_id: str,
- ) -> AgentSandboxInfo:
- self.calls.append(("info", tenant_id, app_id, agent_id, caller_type, caller_id, account_id, ""))
+ def get_info(self, context: RequestContext, caller: SandboxCaller) -> AgentSandboxInfo:
+ self.record("info", context, caller)
return AgentSandboxInfo(workspace_cwd=".")
- def list_files(
- self,
- *,
- tenant_id: str,
- app_id: str,
- agent_id: str,
- caller_type: str,
- caller_id: str,
- account_id: str,
- path: str,
- ) -> BindingFileListResponse:
- self.calls.append(("list", tenant_id, app_id, agent_id, caller_type, caller_id, account_id, path))
+ def list_files(self, context: RequestContext, caller: SandboxCaller, path: str) -> BindingFileListResponse:
+ self.record("list", context, caller, path)
return BindingFileListResponse(path=path, entries=[], truncated=False)
- def read_file(
- self,
- *,
- tenant_id: str,
- app_id: str,
- agent_id: str,
- caller_type: str,
- caller_id: str,
- account_id: str,
- path: str,
- ) -> BindingFileReadResponse:
- self.calls.append(("read", tenant_id, app_id, agent_id, caller_type, caller_id, account_id, path))
+ def read_file(self, context: RequestContext, caller: SandboxCaller, path: str) -> BindingFileReadResponse:
+ self.record("read", context, caller, path)
return BindingFileReadResponse(path=path, size=5, truncated=False, binary=False, text="hello")
- def download_file(
- self,
- *,
- tenant_id: str,
- app_id: str,
- agent_id: str,
- caller_type: str,
- caller_id: str,
- account_id: str,
- path: str,
- ) -> AgentSandboxDownload:
- self.calls.append(("download", tenant_id, app_id, agent_id, caller_type, caller_id, account_id, path))
+ def download_file(self, context: RequestContext, caller: SandboxCaller, path: str) -> AgentSandboxDownload:
+ self.record("download", context, caller, path)
return AgentSandboxDownload(url="https://files.example/report.txt")
-class _WorkflowService:
- def __init__(self) -> None:
- self.calls: list[tuple[str, ...]] = []
-
- def resolve_app_id(self, *, tenant_id: str, app_id: str) -> str:
- return app_id
-
- def list_files(
- self,
- *,
- tenant_id: str,
- app_id: str,
- workflow_run_id: str,
- node_id: str,
- node_execution_id: str,
- path: str,
- session,
- ) -> BindingFileListResponse:
- self.calls.append(("list", tenant_id, app_id, workflow_run_id, node_id, path))
- return BindingFileListResponse(path=path, entries=[], truncated=False)
-
- def read_file(
- self,
- *,
- tenant_id: str,
- app_id: str,
- workflow_run_id: str,
- node_id: str,
- node_execution_id: str,
- path: str,
- session,
- ) -> BindingFileReadResponse:
- self.calls.append(("read", tenant_id, app_id, workflow_run_id, node_id, path))
- return BindingFileReadResponse(path=path, size=5, truncated=False, binary=False, text="hello")
-
- def download_file(
- self,
- *,
- tenant_id: str,
- app_id: str,
- workflow_run_id: str,
- node_id: str,
- node_execution_id: str,
- account_id: str,
- path: str,
- ) -> AgentSandboxDownload:
- self.calls.append(("download", tenant_id, app_id, workflow_run_id, node_id, account_id, path))
- return AgentSandboxDownload(url="https://files.example/download.txt")
+@dataclass
+class AgentServices:
+ sandbox: SandboxService
-def _app_model(app_id: str = "app-1") -> App:
- return App(
- id=app_id,
- tenant_id="tenant-1",
- name="App",
- mode=AppMode.AGENT,
- icon_type=IconType.EMOJI,
- icon="bot",
- icon_background="#fff",
- enable_site=False,
- enable_api=False,
- )
+@dataclass
+class Services:
+ agent_apps: AgentServices
-def _account() -> Account:
- return make_account(name="Sandbox Tester", email="[email protected]")
+def service(monkeypatch: pytest.MonkeyPatch) -> SandboxService:
+ service = SandboxService()
+ monkeypatch.setattr(module, "application_services", lambda: Services(AgentServices(service)))
+ return service
@pytest.mark.parametrize(
- "method",
+ ("resource", "method", "verb", "operation", "workflow"),
[
- module.WorkflowAgentSandboxListResource.get,
- module.WorkflowAgentSandboxReadResource.get,
- module.WorkflowAgentSandboxDownloadResource.post,
+ (module.AgentAppSandboxInfoResource, module.AgentAppSandboxInfoResource.get, "get", "info", False),
+ (module.AgentAppSandboxListResource, module.AgentAppSandboxListResource.get, "get", "list", False),
+ (module.AgentAppSandboxReadResource, module.AgentAppSandboxReadResource.get, "get", "read", False),
+ (
+ module.AgentAppSandboxDownloadResource,
+ module.AgentAppSandboxDownloadResource.post,
+ "post",
+ "download",
+ False,
+ ),
+ (module.WorkflowAgentSandboxListResource, module.WorkflowAgentSandboxListResource.get, "get", "list", True),
+ (module.WorkflowAgentSandboxReadResource, module.WorkflowAgentSandboxReadResource.get, "get", "read", True),
+ (
+ module.WorkflowAgentSandboxDownloadResource,
+ module.WorkflowAgentSandboxDownloadResource.post,
+ "post",
+ "download",
+ True,
+ ),
],
)
-def test_sandbox_resources_require_app_view_layout(method: FunctionType) -> None:
- [check] = rbac_checks(method)
-
- assert isinstance(check.locator, module.PlainApp)
- assert check.scene == module.RBACPermission.APP_VIEW_LAYOUT
-
-
-def test_handle_maps_sandbox_and_agent_backend_errors() -> None:
- assert module._handle(AgentSandboxInspectorError("no_sandbox", "no sandbox", status_code=404)) == (
- {"code": "no_sandbox", "message": "no sandbox"},
- 404,
- )
- assert module._handle(DifyAgentHTTPError(404, {"code": "sandbox_path_not_found", "message": "missing"})) == (
- {"code": "sandbox_path_not_found", "message": "missing"},
- 404,
- )
- assert module._handle(DifyAgentHTTPError(500, "backend exploded")) == (
- {"code": "agent_backend_error", "message": "backend exploded"},
- 500,
- )
- assert module._handle(DifyAgentTimeoutError("connection refused")) == (
- {"code": "agent_backend_unreachable", "message": "connection refused"},
- 502,
- )
- assert module._handle(DifyAgentClientError("transport failed")) == (
- {"code": "agent_backend_unreachable", "message": "transport failed"},
- 502,
- )
- with pytest.raises(RuntimeError):
- module._handle(RuntimeError("boom"))
-
-
-def test_agent_app_sandbox_resources_proxy_service(monkeypatch: pytest.MonkeyPatch) -> None:
- service = _AgentAppService()
- account = _account()
- monkeypatch.setattr(module, "AgentAppSandboxService", lambda: service)
- monkeypatch.setattr(
- module,
- "query_params_from_request",
- lambda model: SimpleNamespace(caller_type="build_draft", caller_id="build-1", path="sub/report.txt"),
- )
- info = unwrap(module.AgentAppSandboxInfoResource.get)(object(), account, "tenant-1", "agent-1")
- listing = unwrap(module.AgentAppSandboxListResource.get)(object(), account, "tenant-1", "agent-1")
- preview = unwrap(module.AgentAppSandboxReadResource.get)(object(), account, "tenant-1", "agent-1")
- req_data = module.AgentSandboxDownloadPayload.model_validate(
- {"caller_type": "build_draft", "caller_id": "build-1", "path": "report.txt"}
- )
- download = unwrap(module.AgentAppSandboxDownloadResource.post)(object(), req_data, account, "tenant-1", "agent-1")
+def test_controller_parses_and_serializes(
+ app: Flask,
+ service: SandboxService,
+ resource: type[Resource],
+ method: Callable[..., object],
+ verb: str,
+ operation: str,
+ workflow: bool,
+) -> None:
+ payload = {"node_execution_id": "execution"} if workflow else {"caller_type": "build_draft", "caller_id": "draft"}
+ if operation != "info":
+ payload["path"] = "~/report.txt"
+ kwargs = {"json": payload} if verb == "post" else {"query_string": payload}
+ params = (RESOURCE_ID, RESOURCE_ID, "node") if workflow else (RESOURCE_ID,)
+ with app.test_request_context("/", method=verb.upper(), **kwargs):
+ result = unwrap(method)(resource(), CONTEXT, *params)
+ caller = (
+ WorkflowSandboxCaller(str(RESOURCE_ID), str(RESOURCE_ID), "node", "execution")
+ if workflow
+ else (AgentSandboxCaller(str(RESOURCE_ID), "build_draft", "draft"))
+ )
+ assert service.calls == [(operation, CONTEXT, caller, "" if operation == "info" else "~/report.txt")]
+ if operation == "info":
+ assert result == {"workspace_cwd": "."}
+ elif operation == "download":
+ assert result == {"url": "https://files.example/report.txt"}
+ elif operation == "read":
+ assert result == {"path": "~/report.txt", "size": 5, "truncated": False, "binary": False, "text": "hello"}
+ else:
+ assert result == {"path": "~/report.txt", "entries": [], "truncated": False}
- assert info == {"workspace_cwd": "."}
- assert listing["path"] == "sub/report.txt"
- assert preview["text"] == "hello"
- assert download == {"url": "https://files.example/report.txt"}
- assert service.calls == [
- ("info", "tenant-1", "app-1", "agent-1", "build_draft", "build-1", "account-1", ""),
- ("list", "tenant-1", "app-1", "agent-1", "build_draft", "build-1", "account-1", "sub/report.txt"),
- ("read", "tenant-1", "app-1", "agent-1", "build_draft", "build-1", "account-1", "sub/report.txt"),
- ("download", "tenant-1", "app-1", "agent-1", "build_draft", "build-1", "account-1", "report.txt"),
- ]
-
-
-def test_agent_app_sandbox_resource_returns_normalized_errors(monkeypatch: pytest.MonkeyPatch) -> None:
- class FailingService:
- def resolve_app_id(self, **kwargs):
- return "app-1"
-
- def get_info(self, **kwargs):
- raise AgentSandboxInspectorError("no_active_binding", "no active binding", status_code=404)
-
- def list_files(self, **kwargs):
- raise AgentSandboxInspectorError("no_active_binding", "no active binding", status_code=404)
-
- monkeypatch.setattr(module, "AgentAppSandboxService", FailingService)
- account = _account()
- monkeypatch.setattr(
- module,
- "query_params_from_request",
- lambda model: SimpleNamespace(caller_type="conversation", caller_id="conv-1", path="."),
- )
-
- assert unwrap(module.AgentAppSandboxInfoResource.get)(object(), account, "tenant-1", "agent-1") == (
- {"code": "no_active_binding", "message": "no active binding"},
- 404,
- )
- assert unwrap(module.AgentAppSandboxListResource.get)(object(), account, "tenant-1", "agent-1") == (
- {"code": "no_active_binding", "message": "no active binding"},
- 404,
- )
+ [check] = rbac_checks(method)
+ if workflow:
+ assert isinstance(check.locator, module.PlainApp)
+ assert check.scene == module.RBACPermission.APP_VIEW_LAYOUT
+ else:
+ assert isinstance(check.locator, module.AgentId)
+ assert check.scene == (
+ module.RBACPermission.AGENT_EDIT if operation == "download" else module.RBACPermission.AGENT_PREVIEW
+ )
-def test_workflow_agent_sandbox_resources_proxy_service(monkeypatch: pytest.MonkeyPatch) -> None:
- service = _WorkflowService()
- monkeypatch.setattr(module, "WorkflowAgentSandboxService", lambda: service)
- monkeypatch.setattr(
- module,
- "query_params_from_request",
- lambda model: SimpleNamespace(node_execution_id="execution-1", path="out.txt"),
- )
- app_model = _app_model()
+ ("error", "code", "message", "status"),
+ [
+ (AgentSandboxBindingNotFoundError("no active binding"), "no_active_binding", "no active binding", 404),
+ (AgentSandboxUnavailableError("unavailable"), "inspector_unavailable", "unavailable", 503),
+ (
+ AgentSandboxDownloadUnavailableError("cannot download"),
+ "binding_file_download_unavailable",
+ "cannot download",
+ 502,
+ ),
+ (DifyAgentHTTPError(409, {"code": "conflict", "message": "busy"}), "conflict", "busy", 409),
+ (DifyAgentHTTPError(500, "backend exploded"), "agent_backend_error", "backend exploded", 500),
+ (DifyAgentTimeoutError("connection refused"), "agent_backend_unreachable", "connection refused", 502),
+ (DifyAgentClientError("transport failed"), "agent_backend_unreachable", "transport failed", 502),
+ ],
+)
+def test_sandbox_error_responses(
+ app: Flask, service: SandboxService, error: Exception, code: str, message: str, status: int
+) -> None:
+ service.error = error
+ with app.test_request_context("/?caller_type=conversation&caller_id=conversation"):
+ result = unwrap(module.AgentAppSandboxInfoResource.get)(object(), CONTEXT, RESOURCE_ID)
+ assert result == ({"code": code, "message": message}, status)
- listing = unwrap(module.WorkflowAgentSandboxListResource.get)(
- object(), "tenant-1", app_model, "run-1", "agent-node"
- )
- preview = unwrap(module.WorkflowAgentSandboxReadResource.get)(
- object(), "tenant-1", app_model, "run-1", "agent-node"
- )
- req_data = module.WorkflowAgentSandboxDownloadPayload.model_validate(
- {"node_execution_id": "execution-1", "path": "download.txt"}
- )
- account = _account()
- download = unwrap(module.WorkflowAgentSandboxDownloadResource.post)(
- object(), req_data, "tenant-1", account, "app-1", "run-1", "agent-node"
- )
- assert listing["path"] == "out.txt"
- assert preview["text"] == "hello"
- assert download == {"url": "https://files.example/download.txt"}
- assert service.calls == [
- ("list", "tenant-1", "app-1", "run-1", "agent-node", "out.txt"),
- ("read", "tenant-1", "app-1", "run-1", "agent-node", "out.txt"),
- ("download", "tenant-1", "app-1", "run-1", "agent-node", "account-1", "download.txt"),
- ]
+ ("error", "expected"),
+ [
+ (AgentAppNotFoundError(), AgentNotFoundError),
+ (WorkflowSandboxAppNotFoundError(), module.AppNotFoundError),
+ (RuntimeError("unexpected"), RuntimeError),
+ ],
+)
+def test_resource_errors_keep_existing_http_contract(error: Exception, expected: type[Exception]) -> None:
+ with pytest.raises(expected):
+ module._handle(error)
diff --git a/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_session_store.py b/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_session_store.py
index 7f88c8eccad..e18e36a2adb 100644
--- a/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_session_store.py
+++ b/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_session_store.py
@@ -28,7 +28,6 @@ from models.agent import (
from models.enums import CreatorUserRole
from models.workflow import WorkflowNodeExecutionModel, WorkflowNodeExecutionTriggeredFrom
from services.agent.workspace_service import AgentWorkspaceNotFoundError, AgentWorkspaceService
-from services.agent_app_sandbox_service import WorkflowAgentSandboxService
def _scope() -> WorkflowAgentSessionScope:
@@ -342,20 +341,6 @@ def test_load_or_create_persists_binding_on_node_execution(
assert persisted_binding is not None
assert persisted_binding.base_home_snapshot_id == home_snapshot_id
- resolved = WorkflowAgentSandboxService._resolve_binding(
- tenant_id="tenant-1",
- app_id="app-1",
- workflow_run_id="run-1",
- node_id="node-1",
- node_execution_id="execution-1",
- session=sqlite_session,
- )
-
- assert resolved.backend_binding_ref == "backend-binding-1"
- assert resolved.agent_id == "agent-1"
- assert resolved.agent_config_version_id == "config-1"
- assert resolved.agent_config_version_kind == "snapshot"
-
def test_load_existing_pointer_rejects_missing_workflow_identity(sqlite_session: Session) -> None:
execution = _execution_row(binding_id="binding-1", process_data={"existing": "value"})
diff --git a/api/tests/unit_tests/pyrefly.toml b/api/tests/unit_tests/pyrefly.toml
index 85b3860cd9a..01f5847d4db 100644
--- a/api/tests/unit_tests/pyrefly.toml
+++ b/api/tests/unit_tests/pyrefly.toml
@@ -790,8 +790,6 @@ project-excludes = [
"services/retention/workflow_run/test_bundle_archive_maintenance.py",
"services/retention/workflow_run/test_clear_free_plan_expired_workflow_run_logs.py",
"services/retention/workflow_run/test_restore_archived_workflow_run.py",
- "services/test_agent_app_feature_service.py",
- "services/test_agent_app_sandbox_service.py",
"services/test_agent_config_service.py",
"services/test_annotation_service.py",
"services/test_api_token_service.py",
diff --git a/api/tests/unit_tests/repositories/app/__init__.py b/api/tests/unit_tests/repositories/app/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/api/tests/unit_tests/repositories/app/test_agent_app_repository.py b/api/tests/unit_tests/repositories/app/test_agent_app_repository.py
new file mode 100644
index 00000000000..f123e8a54c6
--- /dev/null
+++ b/api/tests/unit_tests/repositories/app/test_agent_app_repository.py
@@ -0,0 +1,127 @@
+"""Runtime App materialization must persist or roll back as one transaction."""
+
+from collections.abc import Iterator
+from typing import Literal
+
+import pytest
+from sqlalchemy import event, select
+from sqlalchemy.orm import Session, sessionmaker
+
+from models.agent import Agent, AgentKind, AgentScope, AgentSource, AgentStatus
+from models.model import App, AppModelConfig
+from repositories.app.agent_app_repository import AgentAppRepository
+from services.agent.roster_service import AgentRosterService
+
+type Resolver = Literal["repository", "roster"]
+
+
+def _inline_agent(sqlite_session_factory: sessionmaker[Session]) -> None:
+ with sqlite_session_factory.begin() as session:
+ session.add(
+ Agent(
+ id="inline-agent",
+ tenant_id="tenant-1",
+ app_id="workflow-app",
+ workflow_id="workflow-1",
+ workflow_node_id="node-1",
+ name="Inline Agent",
+ description="Internal runtime",
+ agent_kind=AgentKind.DIFY_AGENT,
+ scope=AgentScope.WORKFLOW_ONLY,
+ source=AgentSource.WORKFLOW,
+ status=AgentStatus.ACTIVE,
+ created_by="account-1",
+ updated_by="account-1",
+ )
+ )
+
+
[email protected](params=["repository", "roster"])
+def resolver(request: pytest.FixtureRequest) -> Resolver:
+ return "repository" if request.param == "repository" else "roster"
+
+
+def resolve_runtime_app(factory: sessionmaker[Session], resolver: Resolver) -> str:
+ if resolver == "repository":
+ return AgentAppRepository(session_factory=factory).resolve_runtime_app_id(
+ tenant_id="tenant-1", agent_id="inline-agent"
+ )
+ with factory() as session:
+ return AgentRosterService(session).get_agent_runtime_app_model(tenant_id="tenant-1", agent_id="inline-agent").id
+
+
[email protected]("_inline_agent")
+def test_runtime_app_creation_commits_all_records_and_reuses_them(
+ sqlite_session_factory: sessionmaker[Session], resolver: Resolver
+) -> None:
+ app_id = resolve_runtime_app(sqlite_session_factory, resolver)
+ assert resolve_runtime_app(sqlite_session_factory, resolver) == app_id
+
+ with sqlite_session_factory() as session:
+ [agent] = session.scalars(select(Agent)).all()
+ [app] = session.scalars(select(App)).all()
+ [config] = session.scalars(select(AppModelConfig)).all()
+ assert agent.backing_app_id == app.id == config.app_id == app_id
+ assert app.app_model_config_id == config.id
+ assert app.tenant_id == agent.tenant_id == "tenant-1"
+ assert app.created_by == app.updated_by == config.created_by == "account-1"
+ assert app.name == "Inline Agent"
+ assert not app.enable_api
+ assert not app.enable_site
+ assert agent.scope == AgentScope.WORKFLOW_ONLY
+
+
[email protected](params=["config-insert", "commit"])
+def failed_materialization(
+ request: pytest.FixtureRequest, sqlite_session_factory: sessionmaker[Session], _inline_agent: None
+) -> Iterator[None]:
+ def fail(*_args: object) -> None:
+ raise RuntimeError("materialization failed")
+
+ target, event_name = (
+ (AppModelConfig, "before_insert")
+ if request.param == "config-insert"
+ else (sqlite_session_factory, "before_commit")
+ )
+ event.listen(target, event_name, fail)
+ try:
+ yield
+ finally:
+ event.remove(target, event_name, fail)
+
+
[email protected]("failed_materialization")
+def test_runtime_app_creation_failure_rolls_back_all_records(
+ sqlite_session_factory: sessionmaker[Session], resolver: Resolver
+) -> None:
+ with pytest.raises(RuntimeError, match="materialization failed"):
+ resolve_runtime_app(sqlite_session_factory, resolver)
+
+ with sqlite_session_factory() as session:
+ agent = session.get(Agent, "inline-agent")
+ assert agent is not None
+ assert agent.backing_app_id is None
+ assert session.scalar(select(App)) is None
+ assert session.scalar(select(AppModelConfig)) is None
+
+
[email protected]("_inline_agent")
+def test_existing_runtime_app_resolution_does_not_commit_the_callers_transaction(
+ sqlite_session_factory: sessionmaker[Session], resolver: Resolver
+) -> None:
+ app_id = resolve_runtime_app(sqlite_session_factory, resolver)
+ with sqlite_session_factory() as session:
+ app = session.get(App, app_id)
+ assert app is not None
+ app.name = "Uncommitted change"
+ resolved = AgentRosterService(session).get_agent_runtime_app_model(
+ tenant_id="tenant-1", agent_id="inline-agent"
+ )
+ assert resolved is app
+ session.rollback()
+
+ with sqlite_session_factory() as session:
+ app = session.get(App, app_id)
+ assert app is not None
+ assert app.name == "Inline Agent"
diff --git a/api/tests/unit_tests/services/app/__init__.py b/api/tests/unit_tests/services/app/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/api/tests/unit_tests/services/app/test_agent_app_access_service.py b/api/tests/unit_tests/services/app/test_agent_app_access_service.py
new file mode 100644
index 00000000000..49167ca07cd
--- /dev/null
+++ b/api/tests/unit_tests/services/app/test_agent_app_access_service.py
@@ -0,0 +1,102 @@
+"""Published Agent App references use the canonical roster query."""
+
+import pytest
+from sqlalchemy.orm import Session, sessionmaker
+
+from extensions.application_services.agent import build_agent_app_services
+from machinery.context import RequestContext
+from models.agent import (
+ Agent,
+ AgentKind,
+ AgentScope,
+ AgentSource,
+ AgentStatus,
+ WorkflowAgentBindingType,
+ WorkflowAgentNodeBinding,
+)
+from models.agent_config_entities import WorkflowNodeJobConfig
+from models.model import AppMode
+from services.app.agent_app_contracts import AgentAppNotFoundError
+from tests.unit_tests.model_factories import make_app
+
+
+def test_access_only_lists_current_published_workflow_references(
+ sqlite_session: Session, sqlite_session_factory: sessionmaker[Session]
+) -> None:
+ sqlite_session.add_all(
+ [
+ make_app(app_id="agent-app", mode=AppMode.AGENT),
+ make_app(app_id="workflow-app", mode=AppMode.WORKFLOW, workflow_id="published"),
+ make_app(app_id="foreign-app", tenant_id="foreign", mode=AppMode.WORKFLOW, workflow_id="foreign-workflow"),
+ Agent(
+ id="agent",
+ tenant_id="tenant-1",
+ name="Agent",
+ description="",
+ app_id="agent-app",
+ agent_kind=AgentKind.DIFY_AGENT,
+ scope=AgentScope.ROSTER,
+ source=AgentSource.AGENT_APP,
+ status=AgentStatus.ACTIVE,
+ ),
+ ]
+ )
+ for node_id, app_id, workflow_id, version, tenant_id in (
+ ("node-b", "workflow-app", "published", "v1", "tenant-1"),
+ ("node-a", "workflow-app", "published", "v1", "tenant-1"),
+ ("draft-node", "workflow-app", "draft", "draft", "tenant-1"),
+ ("old-node", "workflow-app", "old", "v0", "tenant-1"),
+ ("foreign-node", "foreign-app", "foreign-workflow", "v1", "foreign"),
+ ):
+ sqlite_session.add(
+ WorkflowAgentNodeBinding(
+ tenant_id=tenant_id,
+ agent_id="agent",
+ app_id=app_id,
+ workflow_id=workflow_id,
+ workflow_version=version,
+ node_id=node_id,
+ binding_type=WorkflowAgentBindingType.ROSTER_AGENT,
+ current_snapshot_id="snapshot",
+ node_job_config=WorkflowNodeJobConfig(),
+ )
+ )
+ sqlite_session.commit()
+ service = build_agent_app_services(database_client=sqlite_session_factory).access
+ context = RequestContext("request", None, "account", "tenant-1")
+ [reference] = service.list_referencing_workflows(context, "agent")
+ assert reference["app_id"] == "workflow-app"
+ assert reference["workflow_id"] == "published"
+ assert reference["node_ids"] == ["node-a", "node-b"]
+ with pytest.raises(AgentAppNotFoundError):
+ service.list_referencing_workflows(context._replace(active_workspace_id="foreign"), "agent")
+
+
[email protected]("invalid", ["archived", "standalone", "workflow-only", "missing-app"])
+def test_access_requires_public_agent_app(
+ sqlite_session: Session, sqlite_session_factory: sessionmaker[Session], invalid: str
+) -> None:
+ agent = Agent(
+ id="agent",
+ tenant_id="tenant-1",
+ name="Agent",
+ description="",
+ app_id="agent-app",
+ agent_kind=AgentKind.DIFY_AGENT,
+ scope=AgentScope.ROSTER,
+ source=AgentSource.AGENT_APP,
+ status=AgentStatus.ACTIVE,
+ )
+ if invalid == "archived":
+ agent.status = AgentStatus.ARCHIVED
+ elif invalid == "standalone":
+ agent.source = AgentSource.ROSTER
+ elif invalid == "workflow-only":
+ agent.scope = AgentScope.WORKFLOW_ONLY
+ else:
+ agent.app_id = "missing"
+ sqlite_session.add_all([make_app(app_id="agent-app", mode=AppMode.AGENT), agent])
+ sqlite_session.commit()
+ service = build_agent_app_services(database_client=sqlite_session_factory).access
+ with pytest.raises(AgentAppNotFoundError):
+ service.list_referencing_workflows(RequestContext("request", None, "account", "tenant-1"), "agent")
diff --git a/api/tests/unit_tests/services/app/test_agent_app_feature_service.py b/api/tests/unit_tests/services/app/test_agent_app_feature_service.py
new file mode 100644
index 00000000000..76d66264042
--- /dev/null
+++ b/api/tests/unit_tests/services/app/test_agent_app_feature_service.py
@@ -0,0 +1,176 @@
+"""Unit tests for AgentAppFeatureConfigService.
+
+validate_features is the security boundary of the Agent App feature endpoint: it
+must (a) drop any Soul-owned keys a caller tries to smuggle in and (b) fill
+sane disabled/empty defaults for the presentation features the PRD requires.
+update_features persists those flags as a new app_model_config version without
+touching model / prompt / agent_mode.
+"""
+
+import pytest
+from sqlalchemy import select
+from sqlalchemy.orm import Session, sessionmaker
+
+from events.app_event import app_model_config_was_updated
+from extensions.application_services.agent import build_agent_app_services
+from machinery.context import RequestContext
+from models.agent import Agent, AgentKind, AgentScope, AgentSource, AgentStatus
+from models.model import App, AppMode, AppModelConfig
+from services.app.agent_app_contracts import AgentAppNotFoundError
+from services.app.agent_app_feature_gateway import AgentAppFeatureValidator
+
+TENANT_ID = "11111111-1111-1111-1111-111111111111"
+APP_ID = "22222222-2222-2222-2222-222222222222"
+ACCOUNT_ID = "33333333-3333-3333-3333-333333333333"
+
+
+class TestValidateFeatures:
+ def test_empty_config_fills_disabled_defaults(self) -> None:
+ result = AgentAppFeatureValidator.validate_features(TENANT_ID, {})
+
+ assert result["opening_statement"] == ""
+ assert result["suggested_questions"] == []
+ assert result["suggested_questions_after_answer"] == {"enabled": False}
+ assert result["retriever_resource"] == {"enabled": False}
+ assert result["speech_to_text"] == {"enabled": False}
+ assert result["text_to_speech"]["enabled"] is False
+
+ def test_opener_and_follow_up_round_trip(self) -> None:
+ result = AgentAppFeatureValidator.validate_features(
+ TENANT_ID,
+ {
+ "opening_statement": "Hi, I'm Iris.",
+ "suggested_questions": ["What can you do?"],
+ "suggested_questions_after_answer": {"enabled": True},
+ "retriever_resource": {"enabled": True},
+ },
+ )
+
+ assert result["opening_statement"] == "Hi, I'm Iris."
+ assert result["suggested_questions"] == ["What can you do?"]
+ assert result["suggested_questions_after_answer"]["enabled"] is True
+ assert result["retriever_resource"]["enabled"] is True
+
+ def test_soul_owned_keys_are_dropped(self) -> None:
+ # model / pre_prompt / agent_mode / tools / user_input_form belong to the
+ # Agent Soul and must never be settable through the feature endpoint.
+ result = AgentAppFeatureValidator.validate_features(
+ TENANT_ID,
+ {
+ "opening_statement": "hello",
+ "model": {"provider": "x", "name": "y"},
+ "pre_prompt": "system override",
+ "agent_mode": {"enabled": True, "strategy": "react"},
+ "tools": [{"a": 1}],
+ "user_input_form": [{"text-input": {}}],
+ },
+ )
+
+ for forbidden in ("model", "pre_prompt", "agent_mode", "tools", "user_input_form"):
+ assert forbidden not in result
+
+ def test_invalid_opening_statement_type_raises(self) -> None:
+ with pytest.raises(ValueError, match="opening_statement must be of string type"):
+ AgentAppFeatureValidator.validate_features(TENANT_ID, {"opening_statement": 123})
+
+ def test_invalid_suggested_questions_type_raises(self) -> None:
+ with pytest.raises(ValueError, match="suggested_questions must be of list type"):
+ AgentAppFeatureValidator.validate_features(TENANT_ID, {"suggested_questions": "nope"})
+
+
+def agent_app(sqlite_session: Session) -> App:
+ app = App(
+ id=APP_ID,
+ tenant_id=TENANT_ID,
+ name="Agent App",
+ mode=AppMode.AGENT,
+ status="normal",
+ enable_site=False,
+ enable_api=False,
+ max_active_requests=0,
+ )
+ agent = Agent(
+ id="agent",
+ tenant_id=TENANT_ID,
+ app_id=APP_ID,
+ name="Agent",
+ description="",
+ agent_kind=AgentKind.DIFY_AGENT,
+ scope=AgentScope.ROSTER,
+ source=AgentSource.AGENT_APP,
+ status=AgentStatus.ACTIVE,
+ )
+ sqlite_session.add_all([app, agent])
+ sqlite_session.commit()
+ return app
+
+
+def test_feature_save_is_atomic(
+ agent_app: App, sqlite_session: Session, sqlite_session_factory: sessionmaker[Session]
+) -> None:
+ service = build_agent_app_services(database_client=sqlite_session_factory).features
+ context = RequestContext("request", None, ACCOUNT_ID, TENANT_ID)
+ calls: list[str] = []
+
+ def observe(sender: App, *, app_model_config: AppModelConfig, session: Session) -> None:
+ assert session.in_transaction()
+ assert sender.app_model_config_id == app_model_config.id
+ assert app_model_config.created_by == ACCOUNT_ID
+ calls.append(app_model_config.id)
+
+ with app_model_config_was_updated.connected_to(observe):
+ service.update_features(context, "agent", {"opening_statement": "Hi!", "model": {"name": "ignore"}})
+ sqlite_session.expire_all()
+ assert agent_app.app_model_config_id == calls[0]
+ config = sqlite_session.get(AppModelConfig, calls[0])
+ assert config is not None
+ assert config.opening_statement == "Hi!"
+ assert config.model is config.agent_mode is config.pre_prompt is None
+ assert agent_app.updated_by == ACCOUNT_ID
+ sqlite_session.rollback()
+
+ def fail(_sender: App, **_kwargs: object) -> None:
+ raise RuntimeError("event failed")
+
+ with app_model_config_was_updated.connected_to(fail), pytest.raises(RuntimeError, match="event failed"):
+ service.update_features(context, "agent", {"opening_statement": "Must roll back"})
+ sqlite_session.expire_all()
+ assert agent_app.app_model_config_id == calls[0]
+ assert len(sqlite_session.scalars(select(AppModelConfig)).all()) == 1
+
+
+def test_feature_validation_failure_does_not_write(
+ agent_app: App, sqlite_session: Session, sqlite_session_factory: sessionmaker[Session]
+) -> None:
+ service = build_agent_app_services(database_client=sqlite_session_factory).features
+ with pytest.raises(ValueError, match="opening_statement"):
+ service.update_features(
+ RequestContext("request", None, ACCOUNT_ID, TENANT_ID), "agent", {"opening_statement": 123}
+ )
+ sqlite_session.expire_all()
+ assert agent_app.app_model_config_id is None
+ assert sqlite_session.scalar(select(AppModelConfig)) is None
+
+
[email protected]("invalid", ["agent-tenant", "app-tenant", "app-mode", "missing-app", "agent-status"])
+def test_features_require_owned_active_agent_app(
+ agent_app: App, sqlite_session: Session, sqlite_session_factory: sessionmaker[Session], invalid: str
+) -> None:
+ agent = sqlite_session.get(Agent, "agent")
+ assert agent is not None
+ if invalid == "agent-tenant":
+ agent.tenant_id = "foreign"
+ elif invalid == "app-tenant":
+ agent_app.tenant_id = "foreign"
+ elif invalid == "app-mode":
+ agent_app.mode = AppMode.CHAT
+ elif invalid == "missing-app":
+ sqlite_session.delete(agent_app)
+ else:
+ agent.status = AgentStatus.ARCHIVED
+ sqlite_session.commit()
+ service = build_agent_app_services(database_client=sqlite_session_factory).features
+ with pytest.raises(AgentAppNotFoundError):
+ service.update_features(RequestContext("request", None, ACCOUNT_ID, TENANT_ID), "agent", {})
+ assert sqlite_session.scalar(select(AppModelConfig)) is None
diff --git a/api/tests/unit_tests/services/app/test_agent_app_sandbox_service.py b/api/tests/unit_tests/services/app/test_agent_app_sandbox_service.py
new file mode 100644
index 00000000000..2e52410db80
--- /dev/null
+++ b/api/tests/unit_tests/services/app/test_agent_app_sandbox_service.py
@@ -0,0 +1,442 @@
+"""Sandbox ownership and network boundaries exercised with real short-lived SQLite sessions."""
+
+import json
+from collections.abc import Callable, Generator
+from contextlib import contextmanager
+from dataclasses import dataclass
+from datetime import datetime
+from decimal import Decimal
+from typing import Self, cast, override
+
+import pytest
+from dify_agent.client import Client
+from dify_agent.protocol import (
+ BindingFileDownloadRequest,
+ BindingFileDownloadResponse,
+ BindingFileListResponse,
+ BindingFileReadResponse,
+)
+from sqlalchemy.orm import Session, sessionmaker
+
+from graphon.enums import WorkflowNodeExecutionStatus
+from machinery.context import RequestContext
+from models.agent import (
+ Agent,
+ AgentConfigDraft,
+ AgentConfigDraftType,
+ AgentConfigVersionKind,
+ AgentKind,
+ AgentScope,
+ AgentSource,
+ AgentStatus,
+ AgentWorkingResourceStatus,
+ AgentWorkspace,
+ AgentWorkspaceBinding,
+ AgentWorkspaceOwnerType,
+)
+from models.agent_config_entities import AgentSoulConfig
+from models.enums import ConversationFromSource, CreatorUserRole
+from models.model import App, AppMode, Conversation
+from models.workflow import WorkflowNodeExecutionModel, WorkflowNodeExecutionTriggeredFrom
+from repositories.app.agent_app_repository import AgentAppRepository
+from repositories.app.agent_sandbox_repository import AgentSandboxRepository
+from services.app.agent_app_contracts import (
+ AgentAppNotFoundError,
+ AgentSandboxBindingNotFoundError,
+ AgentSandboxCaller,
+ AgentSandboxDownloadUnavailableError,
+ AgentSandboxUnavailableError,
+ SandboxCaller,
+ WorkflowSandboxAppNotFoundError,
+ WorkflowSandboxCaller,
+)
+from services.app.agent_app_sandbox_service import AgentAppSandboxService
+from services.app.agent_sandbox_file_gateway import AgentSandboxFileGateway, create_sandbox_client
+from services.file_request_service import DownloadFileRequestResult, FileRequestService
+from tests.unit_tests.config_override import apply_config_overrides
+from tests.unit_tests.model_factories import make_message
+
+CONTEXT = RequestContext("request-1", "trace-1", "account-1", "tenant-1")
+
+
+class RecordingClient:
+ def __init__(self) -> None:
+ self.calls: list[tuple[str, str, str]] = []
+ self.downloads: list[BindingFileDownloadRequest] = []
+
+ def list_binding_files_sync(self, binding: str, path: str) -> BindingFileListResponse:
+ self.calls.append(("list", binding, path))
+ return BindingFileListResponse(path=path, entries=[], truncated=False)
+
+ def read_binding_file_sync(self, binding: str, path: str) -> BindingFileReadResponse:
+ self.calls.append(("read", binding, path))
+ return BindingFileReadResponse(path=path, size=5, truncated=False, binary=False, text="hello")
+
+ def download_binding_file_sync(self, request: BindingFileDownloadRequest) -> BindingFileDownloadResponse:
+ self.downloads.append(request)
+ return BindingFileDownloadResponse(reference="dify-file-ref:canonical")
+
+
+class RecordingFileRequests:
+ def __init__(self) -> None:
+ self.calls: list[dict[str, object]] = []
+ self.error: ValueError | None = None
+
+ def request_download(self, **kwargs: object) -> DownloadFileRequestResult:
+ self.calls.append(kwargs)
+ if self.error:
+ raise self.error
+ return DownloadFileRequestResult(
+ filename="report.txt",
+ mime_type="text/plain",
+ size=5,
+ download_uri="/files/tools/report.txt?timestamp=1&sign=2",
+ )
+
+
+@dataclass
+class Sandbox:
+ service: AgentAppSandboxService
+ caller: SandboxCaller
+ client: RecordingClient
+ file_requests: RecordingFileRequests
+
+
[email protected](params=["conversation", "build_draft", "inline_build", "workflow", "advanced_chat"])
+def sandbox(
+ request: pytest.FixtureRequest, sqlite_session: Session, sqlite_session_factory: sessionmaker[Session]
+) -> Sandbox:
+ kind = request.param
+ workflow = kind in ("workflow", "advanced_chat")
+ app = App(
+ id="app-1",
+ tenant_id="tenant-1",
+ name="Sandbox",
+ mode=AppMode.ADVANCED_CHAT if kind == "advanced_chat" else AppMode.WORKFLOW if workflow else AppMode.AGENT,
+ status="normal",
+ enable_site=False,
+ enable_api=False,
+ max_active_requests=0,
+ )
+ sqlite_session.add(app)
+ agent = Agent(
+ id="agent-1",
+ tenant_id="tenant-1",
+ name="Agent",
+ description="",
+ agent_kind=AgentKind.DIFY_AGENT,
+ scope=AgentScope.WORKFLOW_ONLY if kind == "inline_build" else AgentScope.ROSTER,
+ source=AgentSource.WORKFLOW if kind == "inline_build" else AgentSource.AGENT_APP,
+ app_id="parent-app" if kind == "inline_build" else "app-1",
+ backing_app_id="app-1" if kind == "inline_build" else None,
+ workflow_id="workflow-1" if kind == "inline_build" else None,
+ workflow_node_id="node-1" if kind == "inline_build" else None,
+ status=AgentStatus.ACTIVE,
+ )
+ sqlite_session.add(agent)
+ owner_type = (
+ AgentWorkspaceOwnerType.WORKFLOW_RUN
+ if workflow
+ else (AgentWorkspaceOwnerType.CONVERSATION if kind == "conversation" else AgentWorkspaceOwnerType.BUILD_DRAFT)
+ )
+ owner_id = "run-1" if workflow else "caller-1"
+ owner_scope = "node-1:workflow-binding-1" if workflow else "root"
+ if kind == "advanced_chat":
+ owner_type = AgentWorkspaceOwnerType.CONVERSATION
+ owner_id = "caller-1"
+ sqlite_session.add(
+ make_message(
+ message_id="message-1",
+ app_id="app-1",
+ conversation_id="caller-1",
+ workflow_run_id="run-1",
+ inputs={},
+ query="query",
+ answer="",
+ message={},
+ message_unit_price=Decimal(0),
+ answer_unit_price=Decimal(0),
+ currency="USD",
+ from_source=ConversationFromSource.CONSOLE,
+ )
+ )
+ workspace = AgentWorkspace(
+ id="workspace-1",
+ tenant_id="tenant-1",
+ app_id="app-1",
+ owner_type=owner_type,
+ owner_id=owner_id,
+ owner_scope_key=owner_scope,
+ backend_workspace_ref="workspace-ref",
+ status=AgentWorkingResourceStatus.ACTIVE,
+ active_guard=1,
+ )
+ binding = AgentWorkspaceBinding(
+ id="binding-1",
+ tenant_id="tenant-1",
+ app_id="app-1",
+ workspace_id="workspace-1",
+ agent_id="agent-1",
+ agent_config_version_id="config-1",
+ agent_config_version_kind=AgentConfigVersionKind.SNAPSHOT
+ if workflow or kind == "conversation"
+ else AgentConfigVersionKind.DRAFT,
+ backend_binding_ref="binding-ref",
+ status=AgentWorkingResourceStatus.ACTIVE,
+ updated_at=datetime(2026, 8, 1),
+ )
+ # A newer binding must never replace the caller's explicit pointer.
+ newer_binding = AgentWorkspaceBinding(
+ id="binding-newer",
+ tenant_id="tenant-1",
+ app_id="app-1",
+ workspace_id="workspace-1",
+ agent_id="agent-1",
+ agent_config_version_id="config-newer",
+ agent_config_version_kind=AgentConfigVersionKind.SNAPSHOT,
+ backend_binding_ref="binding-newer-ref",
+ status=AgentWorkingResourceStatus.ACTIVE,
+ updated_at=datetime(2026, 8, 2),
+ )
+ sqlite_session.add_all([workspace, binding, newer_binding])
+ if workflow:
+ sqlite_session.add(
+ WorkflowNodeExecutionModel(
+ id="execution-1",
+ tenant_id="tenant-1",
+ app_id="app-1",
+ workflow_id="workflow-1",
+ workflow_run_id="run-1",
+ node_id="node-1",
+ node_type="agent",
+ title="Agent",
+ index=1,
+ triggered_from=WorkflowNodeExecutionTriggeredFrom.WORKFLOW_RUN,
+ agent_workspace_binding_id="binding-1",
+ process_data=json.dumps({"workflow_agent_binding_id": "workflow-binding-1"}),
+ status=WorkflowNodeExecutionStatus.SUCCEEDED,
+ created_by_role=CreatorUserRole.ACCOUNT,
+ created_by="historical-account",
+ )
+ )
+ caller: SandboxCaller = WorkflowSandboxCaller("app-1", "run-1", "node-1", "execution-1")
+ elif kind == "conversation":
+ conversation = Conversation(
+ id="caller-1",
+ app_id="app-1",
+ mode=AppMode.AGENT,
+ name="Conversation",
+ from_source=ConversationFromSource.CONSOLE,
+ from_account_id="account-1",
+ is_deleted=False,
+ agent_workspace_binding_id="binding-1",
+ )
+ conversation._inputs = {}
+ sqlite_session.add(conversation)
+ caller = AgentSandboxCaller("agent-1", "conversation", "caller-1")
+ else:
+ sqlite_session.add(
+ AgentConfigDraft(
+ id="caller-1",
+ tenant_id="tenant-1",
+ agent_id="agent-1",
+ draft_type=AgentConfigDraftType.DEBUG_BUILD,
+ account_id="account-1",
+ draft_owner_key="account-1",
+ agent_workspace_binding_id="binding-1",
+ config_snapshot=AgentSoulConfig(),
+ )
+ )
+ caller = AgentSandboxCaller("agent-1", "build_draft", "caller-1")
+ sqlite_session.commit()
+
+ sessions: list[Session] = []
+ closed_sessions: set[Session] = set()
+
+ class TrackingSession(Session):
+ @override
+ def __enter__(self) -> Self:
+ sessions.append(self)
+ return super().__enter__()
+
+ @override
+ def close(self) -> None:
+ super().close()
+ closed_sessions.add(self)
+
+ factory = sessionmaker[Session](bind=sqlite_session_factory.kw["bind"], class_=TrackingSession)
+ client = RecordingClient()
+ files = RecordingFileRequests()
+
+ @contextmanager
+ def client_factory() -> Generator[Client, None, None]:
+ assert sessions
+ assert all(session in closed_sessions and not session.in_transaction() for session in sessions)
+ yield cast(Client, client)
+
+ apps = AgentAppRepository(session_factory=factory)
+ service = AgentAppSandboxService(
+ bindings=AgentSandboxRepository(session_factory=factory, apps=apps),
+ files=AgentSandboxFileGateway(
+ client_factory=client_factory,
+ file_requests=cast(FileRequestService, files),
+ files_url="https://files.example",
+ ),
+ )
+ return Sandbox(service, caller, client, files)
+
+
+def test_sandbox_network_uses_detached_binding_and_authenticated_actor(sandbox: Sandbox) -> None:
+ service, caller = sandbox.service, sandbox.caller
+ assert service.get_info(CONTEXT, caller).workspace_cwd == "."
+ assert sandbox.client.calls == []
+ assert service.list_files(CONTEXT, caller, "~/reports").path == "~/reports"
+ assert service.read_file(CONTEXT, caller, "../report.txt").text == "hello"
+ result = service.download_file(CONTEXT, caller, "/tmp/report.txt")
+ assert sandbox.client.calls == [("list", "binding-ref", "~/reports"), ("read", "binding-ref", "../report.txt")]
+ assert result.url == "https://files.example/files/tools/report.txt?timestamp=1&sign=2&as_attachment=true"
+ [download] = sandbox.client.downloads
+ assert download.backend_binding_ref == "binding-ref"
+ assert download.path == "/tmp/report.txt"
+ execution = download.execution_context
+ assert execution.tenant_id == CONTEXT.active_workspace_id
+ assert execution.user_id == CONTEXT.account_id
+ assert execution.user_from == "account"
+ assert execution.invoke_from == "debugger"
+ assert execution.app_id == "app-1"
+ assert execution.agent_id == "agent-1"
+ assert execution.agent_config_version_id == "config-1"
+ if isinstance(caller, AgentSandboxCaller):
+ assert execution.agent_mode == "agent_app"
+ assert execution.conversation_id == ("caller-1" if caller.caller_type == "conversation" else None)
+ assert execution.agent_config_version_kind == ("snapshot" if caller.caller_type == "conversation" else "draft")
+ else:
+ assert execution.agent_mode == "workflow_run"
+ assert execution.workflow_run_id == "run-1"
+ assert execution.node_id == "node-1"
+ assert execution.node_execution_id == "execution-1"
+ assert sandbox.file_requests.calls == [
+ {
+ "tenant_id": "tenant-1",
+ "user_id": "account-1",
+ "user_from": "account",
+ "invoke_from": "debugger",
+ "file_mapping": {"transfer_method": "tool_file", "reference": "dify-file-ref:canonical"},
+ }
+ ]
+
+
+ ("model", "attribute", "value"),
+ [
+ (AgentWorkspaceBinding, "tenant_id", "foreign"),
+ (AgentWorkspaceBinding, "app_id", "foreign"),
+ (AgentWorkspaceBinding, "status", AgentWorkingResourceStatus.RETIRED),
+ (AgentWorkspaceBinding, "workspace_id", "missing"),
+ (AgentWorkspace, "tenant_id", "foreign"),
+ (AgentWorkspace, "app_id", "foreign"),
+ (AgentWorkspace, "owner_id", "foreign"),
+ (AgentWorkspace, "owner_scope_key", "foreign"),
+ (AgentWorkspace, "status", AgentWorkingResourceStatus.RETIRED),
+ ],
+)
+def test_sandbox_rejects_wrong_owner_or_inactive_binding(
+ sandbox: Sandbox,
+ sqlite_session: Session,
+ model: type[AgentWorkspace] | type[AgentWorkspaceBinding],
+ attribute: str,
+ value: str,
+) -> None:
+ row = sqlite_session.get(model, "binding-1" if model is AgentWorkspaceBinding else "workspace-1")
+ assert row is not None
+ setattr(row, attribute, value)
+ sqlite_session.commit()
+ with pytest.raises(AgentSandboxBindingNotFoundError):
+ sandbox.service.download_file(CONTEXT, sandbox.caller, "file")
+ assert sandbox.client.downloads == []
+ assert sandbox.file_requests.calls == []
+
+
+ ("operation", "needs_path"),
+ [
+ (AgentAppSandboxService.get_info, False),
+ (AgentAppSandboxService.list_files, True),
+ (AgentAppSandboxService.read_file, True),
+ (AgentAppSandboxService.download_file, True),
+ ],
+)
+def test_sandbox_rejects_foreign_tenant_before_network(
+ sandbox: Sandbox, operation: Callable[..., object], needs_path: bool
+) -> None:
+ context = CONTEXT._replace(active_workspace_id="foreign")
+ args = (".",) if needs_path else ()
+ with pytest.raises((AgentAppNotFoundError, WorkflowSandboxAppNotFoundError)):
+ operation(sandbox.service, context, sandbox.caller, *args)
+ assert sandbox.client.calls == sandbox.client.downloads == []
+
+
+def test_sandbox_rejects_invalid_caller_metadata(sandbox: Sandbox, sqlite_session: Session) -> None:
+ if isinstance(sandbox.caller, WorkflowSandboxCaller):
+ row = sqlite_session.get(WorkflowNodeExecutionModel, "execution-1")
+ assert row is not None
+ row.process_data = "{}"
+ elif sandbox.caller.caller_type == "conversation":
+ row = sqlite_session.get(Conversation, "caller-1")
+ assert row is not None
+ row.is_deleted = True
+ else:
+ row = sqlite_session.get(AgentConfigDraft, "caller-1")
+ assert row is not None
+ row.draft_type = AgentConfigDraftType.DRAFT
+ sqlite_session.commit()
+ with pytest.raises(AgentSandboxBindingNotFoundError):
+ sandbox.service.list_files(CONTEXT, sandbox.caller, ".")
+ assert sandbox.client.calls == []
+
+
[email protected]("sandbox", ["conversation", "build_draft", "inline_build"], indirect=True)
[email protected]("invalid", ["account", "pointer", "agent"])
+def test_agent_caller_is_account_scoped(sandbox: Sandbox, sqlite_session: Session, invalid: str) -> None:
+ assert isinstance(sandbox.caller, AgentSandboxCaller)
+ model = Conversation if sandbox.caller.caller_type == "conversation" else AgentConfigDraft
+ row = sqlite_session.get(model, "caller-1")
+ assert row is not None
+ context = CONTEXT
+ if invalid == "account":
+ context = CONTEXT._replace(account_id="other")
+ elif invalid == "pointer":
+ row.agent_workspace_binding_id = None
+ else:
+ binding = sqlite_session.get(AgentWorkspaceBinding, "binding-1")
+ assert binding is not None
+ binding.agent_id = "other"
+ sqlite_session.commit()
+ with pytest.raises(AgentSandboxBindingNotFoundError):
+ sandbox.service.download_file(context, sandbox.caller, "file")
+ assert sandbox.client.downloads == []
+
+
[email protected]("sandbox", ["workflow", "advanced_chat"], indirect=True)
[email protected]("field", ["tenant_id", "app_id", "workflow_run_id", "node_id"])
+def test_workflow_execution_owner_chain(sandbox: Sandbox, sqlite_session: Session, field: str) -> None:
+ assert isinstance(sandbox.caller, WorkflowSandboxCaller)
+ row = sqlite_session.get(WorkflowNodeExecutionModel, "execution-1")
+ assert row is not None
+ setattr(row, field, "foreign")
+ sqlite_session.commit()
+ with pytest.raises(AgentSandboxBindingNotFoundError):
+ sandbox.service.read_file(CONTEXT, sandbox.caller, "file")
+ assert sandbox.client.calls == []
+
+
+def test_download_rejects_untrusted_tool_file_reference(sandbox: Sandbox) -> None:
+ sandbox.file_requests.error = ValueError("not authorized")
+ with pytest.raises(AgentSandboxDownloadUnavailableError):
+ sandbox.service.download_file(CONTEXT, sandbox.caller, "file")
+
+
+def test_missing_backend_configuration(monkeypatch: pytest.MonkeyPatch) -> None:
+ apply_config_overrides(monkeypatch, AGENT_BACKEND_BASE_URL="")
+ with pytest.raises(AgentSandboxUnavailableError):
+ create_sandbox_client()
diff --git a/api/tests/unit_tests/services/test_agent_app_feature_service.py b/api/tests/unit_tests/services/test_agent_app_feature_service.py
deleted file mode 100644
index c638aa2efaa..00000000000
--- a/api/tests/unit_tests/services/test_agent_app_feature_service.py
+++ /dev/null
@@ -1,119 +0,0 @@
-"""Unit tests for AgentAppFeatureConfigService.
-
-validate_features is the security boundary of the Agent App feature endpoint: it
-must (a) drop any Soul-owned keys a caller tries to smuggle in and (b) fill
-sane disabled/empty defaults for the presentation features the PRD requires.
-update_features persists those flags as a new app_model_config version without
-touching model / prompt / agent_mode.
-"""
-
-import pytest
-from sqlalchemy.orm import Session
-
-from models.account import Account
-from models.model import App, AppMode, AppModelConfig
-from services.agent_app_feature_service import AgentAppFeatureConfigService
-
-TENANT_ID = "11111111-1111-1111-1111-111111111111"
-APP_ID = "22222222-2222-2222-2222-222222222222"
-ACCOUNT_ID = "33333333-3333-3333-3333-333333333333"
-
-
-class TestValidateFeatures:
- def test_empty_config_fills_disabled_defaults(self):
- result = AgentAppFeatureConfigService.validate_features(TENANT_ID, {})
-
- assert result["opening_statement"] == ""
- assert result["suggested_questions"] == []
- assert result["suggested_questions_after_answer"] == {"enabled": False}
- assert result["retriever_resource"] == {"enabled": False}
- assert result["speech_to_text"] == {"enabled": False}
- assert result["text_to_speech"]["enabled"] is False
-
- def test_opener_and_follow_up_round_trip(self):
- result = AgentAppFeatureConfigService.validate_features(
- TENANT_ID,
- {
- "opening_statement": "Hi, I'm Iris.",
- "suggested_questions": ["What can you do?"],
- "suggested_questions_after_answer": {"enabled": True},
- "retriever_resource": {"enabled": True},
- },
- )
-
- assert result["opening_statement"] == "Hi, I'm Iris."
- assert result["suggested_questions"] == ["What can you do?"]
- assert result["suggested_questions_after_answer"]["enabled"] is True
- assert result["retriever_resource"]["enabled"] is True
-
- def test_soul_owned_keys_are_dropped(self):
- # model / pre_prompt / agent_mode / tools / user_input_form belong to the
- # Agent Soul and must never be settable through the feature endpoint.
- result = AgentAppFeatureConfigService.validate_features(
- TENANT_ID,
- {
- "opening_statement": "hello",
- "model": {"provider": "x", "name": "y"},
- "pre_prompt": "system override",
- "agent_mode": {"enabled": True, "strategy": "react"},
- "tools": [{"a": 1}],
- "user_input_form": [{"text-input": {}}],
- },
- )
-
- for forbidden in ("model", "pre_prompt", "agent_mode", "tools", "user_input_form"):
- assert forbidden not in result
-
- def test_invalid_opening_statement_type_raises(self):
- with pytest.raises(ValueError, match="opening_statement must be of string type"):
- AgentAppFeatureConfigService.validate_features(TENANT_ID, {"opening_statement": 123})
-
- def test_invalid_suggested_questions_type_raises(self):
- with pytest.raises(ValueError, match="suggested_questions must be of list type"):
- AgentAppFeatureConfigService.validate_features(TENANT_ID, {"suggested_questions": "nope"})
-
-
-class TestUpdateFeatures:
- @pytest.mark.parametrize("sqlite_session", [(Account, App, AppModelConfig)], indirect=True)
- def test_persists_new_app_model_config_version(self, sqlite_session: Session):
- app_model = App(
- id=APP_ID,
- tenant_id=TENANT_ID,
- name="Agent App",
- description="",
- mode=AppMode.AGENT,
- enable_site=True,
- enable_api=True,
- max_active_requests=0,
- )
- account = Account(name="Test User", email="[email protected]")
- account.id = ACCOUNT_ID
- sqlite_session.add_all([account, app_model])
- sqlite_session.commit()
-
- new_config = AgentAppFeatureConfigService.update_features(
- app_model=app_model,
- account=account,
- config={"opening_statement": "Hi!", "suggested_questions_after_answer": {"enabled": True}},
- session=sqlite_session,
- )
- assert not sqlite_session.in_transaction()
-
- # New row carries the features but no Soul-owned model/prompt/agent_mode.
- assert new_config.app_id == APP_ID
- assert new_config.opening_statement == "Hi!"
- assert new_config.model is None
- assert new_config.agent_mode is None
- # App is repointed at the new version and the write is committed.
- assert app_model.app_model_config_id == new_config.id
- assert app_model.updated_by == ACCOUNT_ID
- sqlite_session.expunge_all()
- persisted_config = sqlite_session.get(AppModelConfig, new_config.id)
- persisted_app = sqlite_session.get(App, APP_ID)
- assert persisted_config is not None
- assert persisted_config.opening_statement == "Hi!"
- assert persisted_config.model is None
- assert persisted_config.agent_mode is None
- assert persisted_app is not None
- assert persisted_app.app_model_config_id == new_config.id
- assert persisted_app.updated_by == ACCOUNT_ID
diff --git a/api/tests/unit_tests/services/test_agent_app_sandbox_service.py b/api/tests/unit_tests/services/test_agent_app_sandbox_service.py
deleted file mode 100644
index 5a8fea8f4aa..00000000000
--- a/api/tests/unit_tests/services/test_agent_app_sandbox_service.py
+++ /dev/null
@@ -1,1032 +0,0 @@
-import json
-from contextlib import contextmanager, nullcontext
-from datetime import datetime
-from types import SimpleNamespace
-from typing import cast
-from unittest.mock import MagicMock
-
-import pytest
-from dify_agent.client import Client
-from dify_agent.protocol import BindingFileDownloadResponse, BindingFileListResponse, BindingFileReadResponse
-from sqlalchemy.orm import Session, sessionmaker
-
-from graphon.enums import WorkflowNodeExecutionStatus
-from models.agent import (
- Agent,
- AgentConfigDraft,
- AgentConfigDraftType,
- AgentConfigVersionKind,
- AgentKind,
- AgentScope,
- AgentSource,
- AgentStatus,
- AgentWorkingResourceStatus,
- AgentWorkspace,
- AgentWorkspaceBinding,
- AgentWorkspaceOwnerType,
-)
-from models.agent_config_entities import AgentSoulConfig
-from models.enums import ConversationFromSource, CreatorUserRole
-from models.model import App, AppMode, Conversation, IconType
-from models.workflow import WorkflowNodeExecutionModel, WorkflowNodeExecutionTriggeredFrom
-from services import agent_app_sandbox_service as sandbox_module
-from services.agent_app_sandbox_service import (
- AgentAppSandboxService,
- AgentSandboxDownload,
- AgentSandboxInspectorError,
- WorkflowAgentSandboxService,
-)
-from tests.unit_tests.config_override import apply_config_overrides
-
-
-def _add_normal_conversation(session: Session, *, binding_id: str) -> Conversation:
- session.add(
- App(
- id="app-1",
- tenant_id="tenant-1",
- name="Agent App",
- description="",
- mode=AppMode.AGENT,
- icon_type=IconType.EMOJI,
- icon="robot",
- icon_background="#FFFFFF",
- enable_site=False,
- enable_api=False,
- max_active_requests=0,
- )
- )
- conversation = Conversation(
- id="conversation-1",
- app_id="app-1",
- mode=AppMode.AGENT,
- name="Conversation",
- from_source=ConversationFromSource.CONSOLE,
- from_account_id="account-1",
- is_deleted=False,
- agent_workspace_binding_id=binding_id,
- )
- conversation._inputs = {}
- session.add(conversation)
- return conversation
-
-
-def _add_conversation_bindings(session: Session) -> tuple[AgentWorkspaceBinding, AgentWorkspaceBinding]:
- workspace = AgentWorkspace(
- id="workspace-1",
- tenant_id="tenant-1",
- app_id="app-1",
- owner_type=AgentWorkspaceOwnerType.CONVERSATION,
- owner_id="conversation-1",
- owner_scope_key="root",
- backend_workspace_ref="workspace-ref",
- status=AgentWorkingResourceStatus.ACTIVE,
- active_guard=1,
- )
- expected = AgentWorkspaceBinding(
- id="binding-expected",
- tenant_id="tenant-1",
- app_id="app-1",
- workspace_id=workspace.id,
- agent_id="agent-1",
- base_home_snapshot_id="home-1",
- agent_config_version_id="config-1",
- agent_config_version_kind=AgentConfigVersionKind.SNAPSHOT,
- backend_binding_ref="binding-expected-ref",
- status=AgentWorkingResourceStatus.ACTIVE,
- updated_at=datetime(2026, 7, 23, 10),
- )
- other = AgentWorkspaceBinding(
- id="binding-other",
- tenant_id="tenant-1",
- app_id="app-1",
- workspace_id=workspace.id,
- agent_id="agent-1",
- base_home_snapshot_id="home-1",
- agent_config_version_id="config-1",
- agent_config_version_kind=AgentConfigVersionKind.SNAPSHOT,
- backend_binding_ref="binding-other-ref",
- status=AgentWorkingResourceStatus.ACTIVE,
- updated_at=datetime(2026, 7, 23, 11),
- )
- session.add_all([workspace, expected, other])
- return expected, other
-
-
-def _use_session(monkeypatch: pytest.MonkeyPatch, session: Session) -> None:
- monkeypatch.setattr(
- "services.agent_app_sandbox_service.session_factory.create_session",
- lambda: nullcontext(session),
- )
-
-
-def _add_app(session: Session, *, app_id: str, tenant_id: str) -> None:
- session.add(
- App(
- id=app_id,
- tenant_id=tenant_id,
- name=f"App {app_id}",
- description="",
- mode=AppMode.AGENT,
- icon_type=IconType.EMOJI,
- icon="robot",
- icon_background="#FFFFFF",
- enable_site=False,
- enable_api=False,
- max_active_requests=0,
- )
- )
-
-
-def _add_binding(
- session: Session,
- *,
- binding_id: str,
- workspace_id: str,
- tenant_id: str = "tenant-1",
- app_id: str = "app-1",
- agent_id: str = "agent-1",
- owner_type: AgentWorkspaceOwnerType,
- owner_id: str,
- owner_scope_key: str = "root",
- status: AgentWorkingResourceStatus = AgentWorkingResourceStatus.ACTIVE,
- agent_config_version_id: str | None = None,
- agent_config_version_kind: AgentConfigVersionKind = AgentConfigVersionKind.SNAPSHOT,
-) -> AgentWorkspaceBinding:
- active_guard = 1 if status is AgentWorkingResourceStatus.ACTIVE else None
- workspace = AgentWorkspace(
- id=workspace_id,
- tenant_id=tenant_id,
- app_id=app_id,
- owner_type=owner_type,
- owner_id=owner_id,
- owner_scope_key=owner_scope_key,
- backend_workspace_ref=f"{workspace_id}-ref",
- status=status,
- active_guard=active_guard,
- )
- binding = AgentWorkspaceBinding(
- id=binding_id,
- tenant_id=tenant_id,
- app_id=app_id,
- workspace_id=workspace_id,
- agent_id=agent_id,
- base_home_snapshot_id=None,
- agent_config_version_id=agent_config_version_id or f"{binding_id}-config",
- agent_config_version_kind=agent_config_version_kind,
- backend_binding_ref=f"{binding_id}-ref",
- status=status,
- )
- session.add_all([workspace, binding])
- return binding
-
-
-def _add_build_draft_caller(
- session: Session,
- *,
- parent_app_id: str = "app-1",
- backing_app_id: str | None = None,
- runtime_app_id: str = "app-1",
-) -> AgentWorkspaceBinding:
- session.add(
- Agent(
- id="agent-1",
- tenant_id="tenant-1",
- name="Agent",
- description="",
- agent_kind=AgentKind.DIFY_AGENT,
- scope=AgentScope.WORKFLOW_ONLY if backing_app_id else AgentScope.ROSTER,
- source=AgentSource.WORKFLOW if backing_app_id else AgentSource.AGENT_APP,
- app_id=parent_app_id,
- backing_app_id=backing_app_id,
- status=AgentStatus.ACTIVE,
- )
- )
- binding = _add_binding(
- session,
- binding_id="binding-build",
- workspace_id="workspace-build",
- app_id=runtime_app_id,
- owner_type=AgentWorkspaceOwnerType.BUILD_DRAFT,
- owner_id="build-1",
- agent_config_version_id="config-1",
- agent_config_version_kind=AgentConfigVersionKind.DRAFT,
- )
- session.add(
- AgentConfigDraft(
- id="build-1",
- tenant_id="tenant-1",
- agent_id="agent-1",
- draft_type=AgentConfigDraftType.DEBUG_BUILD,
- account_id="account-1",
- draft_owner_key="account-1",
- agent_workspace_binding_id=binding.id,
- config_snapshot=AgentSoulConfig(),
- )
- )
- return binding
-
-
-def _download_client() -> MagicMock:
- client = MagicMock()
- client.download_binding_file_sync.return_value = BindingFileDownloadResponse(reference="dify-file-ref:canonical")
- return client
-
-
-def _stub_download_response(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(
- sandbox_module,
- "_download_response",
- lambda **_kwargs: AgentSandboxDownload(url="https://files.example/report.txt"),
- )
-
-
- "sqlite_session",
- [(AgentWorkspace, AgentWorkspaceBinding, App, Conversation)],
- indirect=True,
-)
-def test_agent_app_file_browsing_uses_conversation_pointer(
- monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
-) -> None:
- expected, _ = _add_conversation_bindings(sqlite_session)
- _add_normal_conversation(sqlite_session, binding_id=expected.id)
- sqlite_session.commit()
- _use_session(monkeypatch, sqlite_session)
- client = MagicMock()
- response = BindingFileListResponse(path=".", entries=[], truncated=False)
- client.list_binding_files_sync.return_value = response
-
- result = AgentAppSandboxService(client_factory=lambda: nullcontext(client)).list_files(
- tenant_id="tenant-1",
- app_id="app-1",
- agent_id="agent-1",
- caller_type="conversation",
- caller_id="conversation-1",
- account_id="account-1",
- path=".",
- )
-
- assert result is response
- client.list_binding_files_sync.assert_called_once_with(expected.backend_binding_ref, ".")
-
-
- "sqlite_session",
- [(AgentWorkspace, AgentWorkspaceBinding, App, Conversation)],
- indirect=True,
-)
-def test_agent_app_file_browsing_rejects_other_account(
- monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
-) -> None:
- expected, _ = _add_conversation_bindings(sqlite_session)
- _add_normal_conversation(sqlite_session, binding_id=expected.id)
- sqlite_session.commit()
- _use_session(monkeypatch, sqlite_session)
- client = MagicMock()
-
- with pytest.raises(AgentSandboxInspectorError) as exc_info:
- AgentAppSandboxService(client_factory=lambda: nullcontext(client)).list_files(
- tenant_id="tenant-1",
- app_id="app-1",
- agent_id="agent-1",
- caller_type="conversation",
- caller_id="conversation-1",
- account_id="account-2",
- path=".",
- )
-
- assert exc_info.value.code == "no_active_binding"
- client.list_binding_files_sync.assert_not_called()
-
-
- "sqlite_session",
- [(AgentWorkspace, AgentWorkspaceBinding, App, Conversation)],
- indirect=True,
-)
-def test_agent_conversation_download_resolves_only_exact_active_owner_chain(
- monkeypatch: pytest.MonkeyPatch,
- sqlite_session: Session,
-) -> None:
- _add_app(sqlite_session, app_id="app-1", tenant_id="tenant-1")
- _add_app(sqlite_session, app_id="app-other", tenant_id="tenant-other")
- valid = _add_binding(
- sqlite_session,
- binding_id="binding-valid",
- workspace_id="workspace-valid",
- owner_type=AgentWorkspaceOwnerType.CONVERSATION,
- owner_id="conversation-valid",
- )
- wrong_owner = _add_binding(
- sqlite_session,
- binding_id="binding-wrong-owner",
- workspace_id="workspace-wrong-owner",
- owner_type=AgentWorkspaceOwnerType.CONVERSATION,
- owner_id="conversation-not-the-caller",
- )
- retired = _add_binding(
- sqlite_session,
- binding_id="binding-retired",
- workspace_id="workspace-retired",
- owner_type=AgentWorkspaceOwnerType.CONVERSATION,
- owner_id="conversation-retired",
- status=AgentWorkingResourceStatus.RETIRED,
- )
- cross_tenant = _add_binding(
- sqlite_session,
- binding_id="binding-cross-tenant",
- workspace_id="workspace-cross-tenant",
- tenant_id="tenant-other",
- app_id="app-other",
- owner_type=AgentWorkspaceOwnerType.CONVERSATION,
- owner_id="conversation-cross-tenant",
- )
- conversations = [
- Conversation(
- id="conversation-valid",
- app_id="app-1",
- mode=AppMode.AGENT,
- name="Valid",
- from_source=ConversationFromSource.CONSOLE,
- from_account_id="account-1",
- is_deleted=False,
- agent_workspace_binding_id=valid.id,
- ),
- Conversation(
- id="conversation-wrong-owner",
- app_id="app-1",
- mode=AppMode.AGENT,
- name="Wrong owner",
- from_source=ConversationFromSource.CONSOLE,
- from_account_id="account-1",
- is_deleted=False,
- agent_workspace_binding_id=wrong_owner.id,
- ),
- Conversation(
- id="conversation-retired",
- app_id="app-1",
- mode=AppMode.AGENT,
- name="Retired",
- from_source=ConversationFromSource.CONSOLE,
- from_account_id="account-1",
- is_deleted=False,
- agent_workspace_binding_id=retired.id,
- ),
- Conversation(
- id="conversation-cross-tenant",
- app_id="app-other",
- mode=AppMode.AGENT,
- name="Cross tenant",
- from_source=ConversationFromSource.CONSOLE,
- from_account_id="account-other",
- is_deleted=False,
- agent_workspace_binding_id=cross_tenant.id,
- ),
- ]
- for conversation in conversations:
- conversation._inputs = {}
- sqlite_session.add_all(conversations)
- sqlite_session.commit()
- _use_session(monkeypatch, sqlite_session)
- _stub_download_response(monkeypatch)
- client = _download_client()
- service = AgentAppSandboxService(client_factory=lambda: nullcontext(cast(Client, client)))
-
- result = service.download_file(
- tenant_id="tenant-1",
- app_id="app-1",
- agent_id="agent-1",
- caller_type="conversation",
- caller_id="conversation-valid",
- account_id="account-1",
- path="report.txt",
- )
-
- assert result.url == "https://files.example/report.txt"
- request = client.download_binding_file_sync.call_args.args[0]
- assert request.backend_binding_ref == "binding-valid-ref"
- client.download_binding_file_sync.reset_mock()
-
- rejected_locators = [
- {"account_id": "account-other"},
- {"app_id": "app-other"},
- {"caller_id": "conversation-wrong-owner"},
- {"caller_id": "conversation-retired"},
- {
- "tenant_id": "tenant-1",
- "app_id": "app-other",
- "caller_id": "conversation-cross-tenant",
- "account_id": "account-other",
- },
- ]
- for override in rejected_locators:
- locator = {
- "tenant_id": "tenant-1",
- "app_id": "app-1",
- "agent_id": "agent-1",
- "caller_type": "conversation",
- "caller_id": "conversation-valid",
- "account_id": "account-1",
- "path": "report.txt",
- }
- locator.update(override)
- with pytest.raises(AgentSandboxInspectorError, match="active Agent Workspace Binding"):
- service.download_file(**locator) # type: ignore[arg-type]
-
- client.download_binding_file_sync.assert_not_called()
-
-
- "sqlite_session",
- [(Agent, AgentConfigDraft, AgentWorkspace, AgentWorkspaceBinding)],
- indirect=True,
-)
-def test_agent_build_draft_download_resolves_only_exact_active_owner_chain(
- monkeypatch: pytest.MonkeyPatch,
- sqlite_session: Session,
-) -> None:
- sqlite_session.add_all(
- [
- Agent(
- id="agent-1",
- tenant_id="tenant-1",
- name="Agent",
- description="",
- agent_kind=AgentKind.DIFY_AGENT,
- scope=AgentScope.ROSTER,
- source=AgentSource.AGENT_APP,
- app_id="app-1",
- status=AgentStatus.ACTIVE,
- ),
- Agent(
- id="agent-cross-tenant",
- tenant_id="tenant-other",
- name="Other tenant Agent",
- description="",
- agent_kind=AgentKind.DIFY_AGENT,
- scope=AgentScope.ROSTER,
- source=AgentSource.AGENT_APP,
- app_id="app-other",
- status=AgentStatus.ACTIVE,
- ),
- ]
- )
- valid = _add_binding(
- sqlite_session,
- binding_id="binding-build-valid",
- workspace_id="workspace-build-valid",
- owner_type=AgentWorkspaceOwnerType.BUILD_DRAFT,
- owner_id="draft-valid",
- )
- wrong_owner = _add_binding(
- sqlite_session,
- binding_id="binding-build-wrong-owner",
- workspace_id="workspace-build-wrong-owner",
- owner_type=AgentWorkspaceOwnerType.BUILD_DRAFT,
- owner_id="draft-not-the-caller",
- )
- retired = _add_binding(
- sqlite_session,
- binding_id="binding-build-retired",
- workspace_id="workspace-build-retired",
- owner_type=AgentWorkspaceOwnerType.BUILD_DRAFT,
- owner_id="draft-retired",
- status=AgentWorkingResourceStatus.RETIRED,
- )
- drafts = [
- AgentConfigDraft(
- id="draft-valid",
- tenant_id="tenant-1",
- agent_id="agent-1",
- draft_type=AgentConfigDraftType.DEBUG_BUILD,
- account_id="account-1",
- draft_owner_key="account-1",
- agent_workspace_binding_id=valid.id,
- config_snapshot=AgentSoulConfig(),
- ),
- AgentConfigDraft(
- id="draft-wrong-owner",
- tenant_id="tenant-1",
- agent_id="agent-1",
- draft_type=AgentConfigDraftType.DEBUG_BUILD,
- account_id="account-2",
- draft_owner_key="account-2",
- agent_workspace_binding_id=wrong_owner.id,
- config_snapshot=AgentSoulConfig(),
- ),
- AgentConfigDraft(
- id="draft-retired",
- tenant_id="tenant-1",
- agent_id="agent-1",
- draft_type=AgentConfigDraftType.DEBUG_BUILD,
- account_id="account-3",
- draft_owner_key="account-3",
- agent_workspace_binding_id=retired.id,
- config_snapshot=AgentSoulConfig(),
- ),
- AgentConfigDraft(
- id="draft-cross-tenant",
- tenant_id="tenant-other",
- agent_id="agent-cross-tenant",
- draft_type=AgentConfigDraftType.DEBUG_BUILD,
- account_id="account-other",
- draft_owner_key="account-other",
- agent_workspace_binding_id=None,
- config_snapshot=AgentSoulConfig(),
- ),
- ]
- sqlite_session.add_all(drafts)
- sqlite_session.commit()
- _use_session(monkeypatch, sqlite_session)
- _stub_download_response(monkeypatch)
- client = _download_client()
- service = AgentAppSandboxService(client_factory=lambda: nullcontext(cast(Client, client)))
-
- result = service.download_file(
- tenant_id="tenant-1",
- app_id="app-1",
- agent_id="agent-1",
- caller_type="build_draft",
- caller_id="draft-valid",
- account_id="account-1",
- path="report.txt",
- )
-
- assert result.url == "https://files.example/report.txt"
- assert client.download_binding_file_sync.call_args.args[0].backend_binding_ref == "binding-build-valid-ref"
- client.download_binding_file_sync.reset_mock()
-
- rejected_locators = [
- {"account_id": "account-other"},
- {"app_id": "app-other"},
- {"caller_id": "draft-wrong-owner", "account_id": "account-2"},
- {"caller_id": "draft-retired", "account_id": "account-3"},
- {
- "tenant_id": "tenant-1",
- "app_id": "app-other",
- "agent_id": "agent-cross-tenant",
- "caller_id": "draft-cross-tenant",
- "account_id": "account-other",
- },
- ]
- for override in rejected_locators:
- locator = {
- "tenant_id": "tenant-1",
- "app_id": "app-1",
- "agent_id": "agent-1",
- "caller_type": "build_draft",
- "caller_id": "draft-valid",
- "account_id": "account-1",
- "path": "report.txt",
- }
- locator.update(override)
- with pytest.raises(AgentSandboxInspectorError, match="active Agent Workspace Binding"):
- service.download_file(**locator) # type: ignore[arg-type]
-
- client.download_binding_file_sync.assert_not_called()
-
-
-def _workflow_execution(
- *,
- execution_id: str,
- tenant_id: str = "tenant-1",
- app_id: str = "app-1",
- workflow_run_id: str = "run-1",
- node_id: str = "node-1",
- binding_id: str | None,
- workflow_agent_binding_id: str | None = "workflow-binding-1",
- created_by: str = "historical-account",
-) -> WorkflowNodeExecutionModel:
- return WorkflowNodeExecutionModel(
- id=execution_id,
- tenant_id=tenant_id,
- app_id=app_id,
- workflow_id="workflow-1",
- triggered_from=WorkflowNodeExecutionTriggeredFrom.WORKFLOW_RUN,
- workflow_run_id=workflow_run_id,
- index=1,
- node_id=node_id,
- node_type="agent",
- title=node_id,
- agent_workspace_binding_id=binding_id,
- inputs=None,
- process_data=json.dumps(
- {"workflow_agent_binding_id": workflow_agent_binding_id} if workflow_agent_binding_id is not None else {}
- ),
- outputs=None,
- status=WorkflowNodeExecutionStatus.SUCCEEDED,
- error=None,
- created_by_role=CreatorUserRole.ACCOUNT,
- created_by=created_by,
- )
-
-
- "sqlite_session",
- [(WorkflowNodeExecutionModel, AgentWorkspace, AgentWorkspaceBinding)],
- indirect=True,
-)
-def test_workflow_download_resolves_only_exact_active_owner_chain(
- monkeypatch: pytest.MonkeyPatch,
- sqlite_session: Session,
-) -> None:
- valid = _add_binding(
- sqlite_session,
- binding_id="binding-workflow-valid",
- workspace_id="workspace-workflow-valid",
- owner_type=AgentWorkspaceOwnerType.WORKFLOW_RUN,
- owner_id="run-1",
- owner_scope_key="node-1:workflow-binding-1",
- )
- wrong_owner = _add_binding(
- sqlite_session,
- binding_id="binding-workflow-wrong-owner",
- workspace_id="workspace-workflow-wrong-owner",
- owner_type=AgentWorkspaceOwnerType.WORKFLOW_RUN,
- owner_id="run-not-the-caller",
- owner_scope_key="node-1:workflow-binding-1",
- )
- retired = AgentWorkspaceBinding(
- id="binding-workflow-retired",
- tenant_id="tenant-1",
- app_id="app-1",
- workspace_id=valid.workspace_id,
- agent_id="agent-1",
- base_home_snapshot_id=None,
- agent_config_version_id="binding-workflow-retired-config",
- agent_config_version_kind=AgentConfigVersionKind.SNAPSHOT,
- backend_binding_ref="binding-workflow-retired-ref",
- status=AgentWorkingResourceStatus.RETIRED,
- )
- sqlite_session.add(retired)
- sqlite_session.add_all(
- [
- _workflow_execution(execution_id="execution-valid", binding_id=valid.id),
- _workflow_execution(
- execution_id="execution-cross-tenant",
- tenant_id="tenant-other",
- binding_id=valid.id,
- ),
- _workflow_execution(execution_id="execution-wrong-app", app_id="app-other", binding_id=valid.id),
- _workflow_execution(execution_id="execution-wrong-run", workflow_run_id="run-other", binding_id=valid.id),
- _workflow_execution(execution_id="execution-wrong-node", node_id="node-other", binding_id=valid.id),
- _workflow_execution(execution_id="execution-wrong-owner", binding_id=wrong_owner.id),
- _workflow_execution(execution_id="execution-retired", binding_id=retired.id),
- ]
- )
- sqlite_session.commit()
- persisted_execution = sqlite_session.get(WorkflowNodeExecutionModel, "execution-valid")
- assert persisted_execution is not None
- assert persisted_execution.created_by == "historical-account"
- _use_session(monkeypatch, sqlite_session)
- client = _download_client()
- request_download = MagicMock(
- return_value=SimpleNamespace(download_uri="/files/tools/report.txt?timestamp=1&sign=2")
- )
- monkeypatch.setattr(
- sandbox_module,
- "FileRequestService",
- lambda: SimpleNamespace(request_download=request_download),
- )
- apply_config_overrides(monkeypatch, FILES_URL="https://files.example")
- service = WorkflowAgentSandboxService(client_factory=lambda: nullcontext(cast(Client, client)))
-
- result = service.download_file(
- tenant_id="tenant-1",
- app_id="app-1",
- workflow_run_id="run-1",
- node_id="node-1",
- node_execution_id="execution-valid",
- account_id="authenticated-account",
- path="report.txt",
- )
-
- assert result.url == "https://files.example/files/tools/report.txt?timestamp=1&sign=2&as_attachment=true"
- request = client.download_binding_file_sync.call_args.args[0]
- assert request.backend_binding_ref == "binding-workflow-valid-ref"
- assert request.execution_context.user_id == "authenticated-account"
- assert request.execution_context.user_from == "account"
- request_download.assert_called_once_with(
- tenant_id="tenant-1",
- user_id="authenticated-account",
- user_from="account",
- invoke_from="debugger",
- file_mapping={"transfer_method": "tool_file", "reference": "dify-file-ref:canonical"},
- )
- client.download_binding_file_sync.reset_mock()
-
- for node_execution_id in (
- "execution-cross-tenant",
- "execution-wrong-app",
- "execution-wrong-run",
- "execution-wrong-node",
- "execution-wrong-owner",
- "execution-retired",
- ):
- with pytest.raises(AgentSandboxInspectorError, match="active Workspace Binding"):
- service.download_file(
- tenant_id="tenant-1",
- app_id="app-1",
- workflow_run_id="run-1",
- node_id="node-1",
- node_execution_id=node_execution_id,
- account_id="authenticated-account",
- path="report.txt",
- )
-
- client.download_binding_file_sync.assert_not_called()
- assert request_download.call_count == 1
-
-
- ("parent_app_id", "backing_app_id", "runtime_app_id"),
- [
- ("app-1", None, "app-1"),
- ("workflow-app-1", "runtime-app-1", "runtime-app-1"),
- ],
-)
-def test_agent_app_file_browsing_uses_build_draft_caller(
- monkeypatch: pytest.MonkeyPatch,
- sqlite_session: Session,
- parent_app_id: str,
- backing_app_id: str | None,
- runtime_app_id: str,
-) -> None:
- _add_build_draft_caller(
- sqlite_session,
- parent_app_id=parent_app_id,
- backing_app_id=backing_app_id,
- runtime_app_id=runtime_app_id,
- )
- sqlite_session.commit()
- _use_session(monkeypatch, sqlite_session)
- client = MagicMock()
- response = BindingFileListResponse(path=".", entries=[], truncated=False)
- client.list_binding_files_sync.return_value = response
-
- result = AgentAppSandboxService(client_factory=lambda: nullcontext(client)).list_files(
- tenant_id="tenant-1",
- app_id=runtime_app_id,
- agent_id="agent-1",
- caller_type="build_draft",
- caller_id="build-1",
- account_id="account-1",
- path=".",
- )
-
- assert result is response
- client.list_binding_files_sync.assert_called_once_with("binding-build-ref", ".")
-
-
-def test_workflow_file_access_uses_node_execution_pointer(
- sqlite_session: Session,
-) -> None:
- binding = _add_binding(
- sqlite_session,
- binding_id="binding-workflow",
- workspace_id="workspace-workflow",
- owner_type=AgentWorkspaceOwnerType.WORKFLOW_RUN,
- owner_id="run-1",
- owner_scope_key="node-1:workflow-binding-1",
- )
- sqlite_session.add(_workflow_execution(execution_id="execution-1", binding_id=binding.id))
- sqlite_session.commit()
- client = MagicMock()
- response = BindingFileReadResponse(path="report.txt", size=2, truncated=False, binary=False, text="ok")
- client.read_binding_file_sync.return_value = response
-
- result = WorkflowAgentSandboxService(client_factory=lambda: nullcontext(client)).read_file(
- tenant_id="tenant-1",
- app_id="app-1",
- workflow_run_id="run-1",
- node_id="node-1",
- node_execution_id="execution-1",
- path="report.txt",
- session=sqlite_session,
- )
-
- assert result is response
- client.read_binding_file_sync.assert_called_once_with("binding-workflow-ref", "report.txt")
- assert not sqlite_session.in_transaction()
-
-
-def test_workflow_download_uses_authenticated_account_and_trusted_file_request(
- monkeypatch: pytest.MonkeyPatch,
- sqlite_session: Session,
- sqlite_session_factory: sessionmaker[Session],
-) -> None:
- binding = _add_binding(
- sqlite_session,
- binding_id="binding-workflow",
- workspace_id="workspace-workflow",
- owner_type=AgentWorkspaceOwnerType.WORKFLOW_RUN,
- owner_id="run-1",
- owner_scope_key="node-1:workflow-binding-1",
- )
- sqlite_session.add(_workflow_execution(execution_id="execution-1", binding_id=binding.id))
- sqlite_session.commit()
- events: list[str] = []
-
- @contextmanager
- def session_scope():
- with sqlite_session_factory() as service_session:
- yield service_session
- assert not service_session.in_transaction()
- events.append("session-exit")
-
- monkeypatch.setattr(sandbox_module.session_factory, "create_session", session_scope)
- client = MagicMock()
- client.download_binding_file_sync.side_effect = lambda _request: (
- events.append("client-download") or BindingFileDownloadResponse(reference="dify-file-ref:canonical")
- )
- request_download = MagicMock(
- side_effect=lambda **_kwargs: (
- events.append("file-request") or SimpleNamespace(download_uri="/files/tools/report.txt?timestamp=1&sign=2")
- )
- )
- monkeypatch.setattr(
- "services.agent_app_sandbox_service.FileRequestService",
- lambda: SimpleNamespace(request_download=request_download),
- )
- apply_config_overrides(monkeypatch, FILES_URL="https://files.example")
-
- result = WorkflowAgentSandboxService(client_factory=lambda: nullcontext(client)).download_file(
- tenant_id="tenant-1",
- app_id="app-1",
- workflow_run_id="run-1",
- node_id="node-1",
- node_execution_id="execution-1",
- account_id="account-1",
- path="report.txt",
- )
-
- request = client.download_binding_file_sync.call_args.args[0]
- assert request.execution_context.user_id == "account-1"
- assert request.execution_context.user_from == "account"
- assert request.execution_context.node_execution_id == "execution-1"
- assert events == ["session-exit", "client-download", "file-request"]
- request_download.assert_called_once_with(
- tenant_id="tenant-1",
- user_id="account-1",
- user_from="account",
- invoke_from="debugger",
- file_mapping={"transfer_method": "tool_file", "reference": "dify-file-ref:canonical"},
- )
- assert result.url == "https://files.example/files/tools/report.txt?timestamp=1&sign=2&as_attachment=true"
-
-
-def test_agent_app_download_uses_complete_account_context_after_session_exit(
- monkeypatch: pytest.MonkeyPatch,
- sqlite_session: Session,
- sqlite_session_factory: sessionmaker[Session],
-) -> None:
- events: list[str] = []
- _add_build_draft_caller(sqlite_session)
- sqlite_session.commit()
-
- @contextmanager
- def session_scope():
- with sqlite_session_factory() as service_session:
- yield service_session
- events.append("session-exit")
-
- monkeypatch.setattr(sandbox_module.session_factory, "create_session", session_scope)
- client = MagicMock()
- client.download_binding_file_sync.side_effect = lambda _request: (
- events.append("client-download") or BindingFileDownloadResponse(reference="dify-file-ref:canonical")
- )
- request_download = MagicMock(
- side_effect=lambda **_kwargs: (
- events.append("file-request") or SimpleNamespace(download_uri="/files/tools/report.txt?timestamp=1&sign=2")
- )
- )
- monkeypatch.setattr(
- sandbox_module,
- "FileRequestService",
- lambda: SimpleNamespace(request_download=request_download),
- )
- apply_config_overrides(monkeypatch, FILES_URL="https://files.example")
-
- result = AgentAppSandboxService(client_factory=lambda: nullcontext(client)).download_file(
- tenant_id="tenant-1",
- app_id="app-1",
- agent_id="agent-1",
- caller_type="build_draft",
- caller_id="build-1",
- account_id="account-1",
- path="report.txt",
- )
-
- request = client.download_binding_file_sync.call_args.args[0]
- assert request.backend_binding_ref == "binding-build-ref"
- assert request.path == "report.txt"
- assert request.execution_context.model_dump(exclude_none=True) == {
- "tenant_id": "tenant-1",
- "user_id": "account-1",
- "user_from": "account",
- "app_id": "app-1",
- "agent_id": "agent-1",
- "agent_config_version_id": "config-1",
- "agent_config_version_kind": "draft",
- "agent_mode": "agent_app",
- "invoke_from": "debugger",
- }
- assert events == ["session-exit", "client-download", "file-request"]
- request_download.assert_called_once_with(
- tenant_id="tenant-1",
- user_id="account-1",
- user_from="account",
- invoke_from="debugger",
- file_mapping={"transfer_method": "tool_file", "reference": "dify-file-ref:canonical"},
- )
- assert result.url == "https://files.example/files/tools/report.txt?timestamp=1&sign=2&as_attachment=true"
-
-
-def test_file_request_rejection_maps_to_download_unavailable(monkeypatch: pytest.MonkeyPatch) -> None:
- request_download = MagicMock(side_effect=ValueError("reference is not accessible"))
- monkeypatch.setattr(
- sandbox_module,
- "FileRequestService",
- lambda: SimpleNamespace(request_download=request_download),
- )
-
- with pytest.raises(AgentSandboxInspectorError) as exc_info:
- sandbox_module._download_response(
- tenant_id="tenant-1",
- account_id="account-1",
- reference="dify-file-ref:untrusted",
- )
-
- assert exc_info.value.code == "binding_file_download_unavailable"
- assert exc_info.value.status_code == 502
-
-
- ("binding_id", "workflow_agent_binding_id"),
- [
- pytest.param(None, "workflow-binding-1", id="missing-binding-pointer"),
- pytest.param("binding-workflow", None, id="missing-process-data"),
- ],
-)
-def test_workflow_download_rejects_missing_binding_metadata_before_network(
- monkeypatch: pytest.MonkeyPatch,
- sqlite_session: Session,
- binding_id: str | None,
- workflow_agent_binding_id: str | None,
-) -> None:
- sqlite_session.add(
- _workflow_execution(
- execution_id="execution-1",
- binding_id=binding_id,
- workflow_agent_binding_id=workflow_agent_binding_id,
- )
- )
- sqlite_session.commit()
- _use_session(monkeypatch, sqlite_session)
- client = MagicMock()
-
- with pytest.raises(AgentSandboxInspectorError) as exc_info:
- WorkflowAgentSandboxService(client_factory=lambda: nullcontext(client)).download_file(
- tenant_id="tenant-1",
- app_id="app-1",
- workflow_run_id="run-1",
- node_id="node-1",
- node_execution_id="execution-1",
- account_id="account-1",
- path="report.txt",
- )
-
- assert exc_info.value.code == "no_active_binding"
- client.download_binding_file_sync.assert_not_called()
-
-
-def test_workflow_download_rejects_non_active_or_mismatched_binding_before_network(
- monkeypatch: pytest.MonkeyPatch,
- sqlite_session: Session,
-) -> None:
- binding = _add_binding(
- sqlite_session,
- binding_id="binding-workflow",
- workspace_id="workspace-workflow",
- owner_type=AgentWorkspaceOwnerType.WORKFLOW_RUN,
- owner_id="run-other",
- owner_scope_key="node-1:workflow-binding-1",
- )
- sqlite_session.add(_workflow_execution(execution_id="execution-1", binding_id=binding.id))
- sqlite_session.commit()
- _use_session(monkeypatch, sqlite_session)
- client = MagicMock()
-
- with pytest.raises(AgentSandboxInspectorError) as exc_info:
- WorkflowAgentSandboxService(client_factory=lambda: nullcontext(client)).download_file(
- tenant_id="tenant-1",
- app_id="app-1",
- workflow_run_id="run-1",
- node_id="node-1",
- node_execution_id="execution-1",
- account_id="account-1",
- path="report.txt",
- )
-
- assert exc_info.value.code == "no_active_binding"
- client.download_binding_file_sync.assert_not_called()