Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
refactor(api): consolidate app queries and clarify session ownership (#43288)
Byron.wangb71c5f867160
diff --git a/api/controllers/common/errors.py b/api/controllers/common/errors.pyindex 05a3fd22389..2e3fb830cb8 100644--- a/api/controllers/common/errors.py+++ b/api/controllers/common/errors.py@@ -87,6 +87,12 @@ class NoFileUploadedError(BaseHTTPException):code = 400+class ForbiddenError(BaseHTTPException):+ error_code = "forbidden"+ code = 403+ description = "Forbidden"++class NotFoundError(BaseHTTPException):error_code = "not_found"code = 404diff --git a/api/controllers/inner_api/app/dsl.py b/api/controllers/inner_api/app/dsl.pyindex 5f3d50f4750..e411ef07c5e 100644--- a/api/controllers/inner_api/app/dsl.py+++ b/api/controllers/inner_api/app/dsl.py@@ -12,18 +12,19 @@ from flask import requestfrom flask_restx import Resourcefrom pydantic import BaseModel, Field, ValidationError, field_validator+from controllers.common.fields import SimpleMessageResponsefrom controllers.common.schema import query_params_from_model, register_schema_model-from controllers.console.wraps import model_validate, setup_required+from controllers.console.wraps import setup_required, validate_requestfrom controllers.inner_api import inner_api_nsfrom controllers.inner_api.wraps import enterprise_inner_api_onlyfrom core.logging.context import get_request_id, get_trace_idfrom extensions.ext_application_services import application_services-from extensions.ext_database import db+from fields.app_export_fields import AppExportResponse+from fields.base import ResponseModelfrom libs.helper import dump_response-from models import App-from services.app_dsl_service import AppDslService+from services.entities.app_entities import AppExportOptionsfrom services.entities.dsl_entities import AppImportParams, Import, ImportMode, ImportStatus-from services.errors.app import IsDraftWorkflowError, WorkflowNotFoundError+from services.errors.app import AppDiscoveryNotFoundError, IsDraftWorkflowError, WorkflowNotFoundErrorclass InnerAppDSLImportPayload(BaseModel):@@ -45,6 +46,12 @@ class EnterpriseAppDSLExportQuery(BaseModel):return bool(value)+class EnterpriseAppDSLWorkflowErrorResponse(ResponseModel):+ code: str+ message: str+ status: int++register_schema_model(inner_api_ns, InnerAppDSLImportPayload)@@ -62,10 +69,9 @@ class EnterpriseAppDSLImport(Resource):HTTPStatus.NOT_FOUND: "Creator account not found or inactive",})- @model_validate(InnerAppDSLImportPayload)- def post(self, args: InnerAppDSLImportPayload, workspace_id: str):+ def post(self, workspace_id: str):"""Import a DSL into a workspace on behalf of a specified creator."""-+ args = validate_request(InnerAppDSLImportPayload)result = application_services().apps.imports.import_as_creator(workspace_id=workspace_id,creator_email=args.creator_email,@@ -79,7 +85,9 @@ class EnterpriseAppDSLImport(Resource):trace_id=get_trace_id(),)if result is None:- return {"message": f"account '{args.creator_email}' not found or inactive"}, HTTPStatus.NOT_FOUND+ return dump_response(+ SimpleMessageResponse, {"message": f"account '{args.creator_email}' not found or inactive"}+ ), HTTPStatus.NOT_FOUNDif result.status == ImportStatus.FAILED:return dump_response(Import, result), HTTPStatus.BAD_REQUEST@@ -106,35 +114,36 @@ class EnterpriseAppDSLExport(Resource):try:query = EnterpriseAppDSLExportQuery.model_validate(request.args.to_dict(flat=True))except ValidationError:- return {- "code": "invalid_workflow_id",- "message": "workflow_id must be a valid UUID",- "status": 400,- }, 400+ return dump_response(+ EnterpriseAppDSLWorkflowErrorResponse,+ {+ "code": "invalid_workflow_id",+ "message": "workflow_id must be a valid UUID",+ "status": HTTPStatus.BAD_REQUEST,+ },+ ), HTTPStatus.BAD_REQUESTworkflow_id = str(query.workflow_id) if query.workflow_id else None- app_model = db.session.get(App, app_id)- if not app_model:- return {"message": "app not found"}, 404-- if not workflow_id:- data = AppDslService.export_dsl(- app_model=app_model,- session=db.session(),- include_secret=query.include_secret,+ try:+ data = application_services().apps.exports.export_for_inner(+ app_id, AppExportOptions(include_secret=query.include_secret, workflow_id=workflow_id))- else:- try:- data = AppDslService.export_dsl(- app_model=app_model,- session=db.session(),- include_secret=query.include_secret,- workflow_id=workflow_id,- )- except WorkflowNotFoundError as exc:- return {"code": "workflow_version_not_found", "message": str(exc), "status": 404}, 404- except IsDraftWorkflowError as exc:- return {"code": "workflow_version_not_published", "message": str(exc), "status": 400}, 400-- return {"data": data}, 200+ except AppDiscoveryNotFoundError:+ return dump_response(SimpleMessageResponse, {"message": "app not found"}), HTTPStatus.NOT_FOUND+ except WorkflowNotFoundError as exc:+ if not workflow_id:+ raise+ return dump_response(+ EnterpriseAppDSLWorkflowErrorResponse,+ {"code": "workflow_version_not_found", "message": str(exc), "status": HTTPStatus.NOT_FOUND},+ ), HTTPStatus.NOT_FOUND+ except IsDraftWorkflowError as exc:+ if not workflow_id:+ raise+ return dump_response(+ EnterpriseAppDSLWorkflowErrorResponse,+ {"code": "workflow_version_not_published", "message": str(exc), "status": HTTPStatus.BAD_REQUEST},+ ), HTTPStatus.BAD_REQUEST++ return dump_response(AppExportResponse, {"data": data}), HTTPStatus.OKdiff --git a/api/controllers/openapi/_app_response.py b/api/controllers/openapi/_app_response.pynew file mode 100644index 00000000000..d8031dd7a55--- /dev/null+++ b/api/controllers/openapi/_app_response.py@@ -0,0 +1,78 @@+"""Pure response projections for app discovery; no ORM access."""++from typing import Any++from controllers.common.fields import Parameters+from controllers.openapi._input_schema import EMPTY_INPUT_SCHEMA, build_input_schema+from controllers.openapi._models import AppDescribeInfo, AppDescribeResponse, AppListRow+from core.app.app_config.common.parameters_mapping import get_parameters_from_feature_dict+from libs.helper import dump_response+from models.model import AppMode+from services.app.query_service import AppDescription, AppDiscoveryEntry+from services.app_definition_query_service import AppParameterConfig++_EMPTY_PARAMETERS: dict[str, Any] = {+ "opening_statement": None,+ "suggested_questions": [],+ "user_input_form": [],+ "file_upload": None,+ "system_parameters": {},+}+++def parameters_payload(config: AppParameterConfig) -> dict:+ """Mirrors service_api/app/app.py::AppParameterApi response body."""+ parameters = get_parameters_from_feature_dict(+ features_dict=config.features_dict, user_input_form=config.user_input_form+ )+ return dump_response(Parameters, parameters)+++def build_app_describe_response(description: AppDescription, fields: set[str] | None) -> AppDescribeResponse:+ """Public projection of an app (name / params / input schema) — never internal config."""+ app = description.app+ want_info = fields is None or "info" in fields+ want_params = fields is None or "parameters" in fields+ want_schema = fields is None or "input_schema" in fields++ info = (+ AppDescribeInfo(+ id=str(app.id),+ name=app.name,+ mode=app.mode,+ description=app.description,+ updated_at=app.updated_at.isoformat() if app.updated_at else None,+ service_api_enabled=description.service_api_enabled,+ is_agent=app.mode in (AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT),+ )+ if want_info+ else None+ )++ parameters: dict[str, Any] | None = None+ input_schema: dict[str, Any] | None = None+ if want_params:+ parameters = (+ parameters_payload(description.config) if description.config is not None else dict(_EMPTY_PARAMETERS)+ )+ if want_schema:+ input_schema = (+ build_input_schema(app.mode, description.config.user_input_form)+ if description.config is not None+ else dict(EMPTY_INPUT_SCHEMA)+ )++ return AppDescribeResponse(info=info, parameters=parameters, input_schema=input_schema)+++def app_list_row(entry: AppDiscoveryEntry) -> AppListRow:+ app = entry.app+ return AppListRow(+ id=app.id,+ name=app.name,+ description=app.description,+ mode=app.mode,+ updated_at=app.updated_at.isoformat() if app.updated_at else None,+ workspace_id=app.tenant_id,+ workspace_name=entry.workspace_name,+ )diff --git a/api/controllers/openapi/_contract.py b/api/controllers/openapi/_contract.pyindex bcd16c046fb..76d6386e77b 100644--- a/api/controllers/openapi/_contract.py+++ b/api/controllers/openapi/_contract.py@@ -32,7 +32,7 @@ from controllers.openapi._multipart import body_from_requestfrom controllers.openapi._upload import file_fieldsfrom controllers.openapi.auth.requirements import Requirementfrom controllers.openapi.auth.router import subject_router-from controllers.openapi.auth.spec import CatalogMeta, EndpointSpec, Example, Kind+from controllers.openapi.auth.spec import AdmissionContext, CatalogMeta, EndpointSpec, Example, Kindfrom enums import DeploymentEdition__all__ = ["Example", "Kind", "accepts", "endpoint", "op_of", "paginated", "returns"]@@ -154,7 +154,7 @@ def endpoint(body: type[BaseModel] | None = None,returns: ReturnSpec | Sequence[ReturnSpec] | None = None,edition: frozenset[DeploymentEdition] | None = None,- account_context: bool = False,+ context: AdmissionContext | None = "orm",internal: bool = False,deprecated: bool = False,examples: Sequence[Example] = (),@@ -164,10 +164,16 @@ def endpoint(``view.__handler__`` (the bare handler) and ``view.__spec__`` (the exact`EndpointSpec` instance the router runs).- ``account_context=True`` supplies a framework-neutral ``RequestContext`` after- account/workspace admission and releases the authentication session before- the handler. It is for account endpoints whose application services own- persistence; other endpoints retain the lazy ORM-backed ``Context``.+ ``context`` selects the handler's ``ctx`` argument and admission Session lifetime:++ - ``"orm"`` (default): the authentication Context with ORM objects and an open Session.+ - ``"workspace"``: a RequestContext with account and workspace identity.+ - ``"app"``: an AppRequestContext with tenant and app identity.+ - ``None``: no ``ctx`` argument; admission requirements still run.++ For ``"workspace"``, ``"app"`` and ``None``, the pipeline commits and closes+ the admission Session after preparing the arguments and before calling the+ handler. Services called by these handlers own their persistence Sessions.``returns`` takes one ``(code, model, description)`` or several; a routethat stacked N ``@returns`` today declares them here in the same top-to-bottom@@ -187,7 +193,7 @@ def endpoint(spec = EndpointSpec(requirements=requirements,edition=edition,- account_context=account_context,+ context=context,catalog=CatalogMeta(op=op,kind=kind,@@ -202,7 +208,7 @@ def endpoint(return_specs = _normalize_returns(returns)def decorator(view: Callable[..., Any]) -> Callable[..., Any]:- if "ctx" not in inspect.signature(view).parameters:+ if context is not None and "ctx" not in inspect.signature(view).parameters:raise TypeError(f"{view.__qualname__} must declare a 'ctx' parameter")decorated = viewdiff --git a/api/controllers/openapi/_input_schema.py b/api/controllers/openapi/_input_schema.pyindex afaaf2e690f..8cdbcf1fce0 100644--- a/api/controllers/openapi/_input_schema.py+++ b/api/controllers/openapi/_input_schema.py@@ -2,13 +2,9 @@from __future__ import annotations-from typing import Any, cast+from typing import Any-from sqlalchemy.orm import Session--from controllers.service_api.app.error import AppUnavailableError-from models import App-from models.model import AppMode, load_annotation_reply_config+from models.model import AppModeJSON_SCHEMA_DRAFT = "https://json-schema.org/draft/2020-12/schema"@@ -91,42 +87,18 @@ def _form_to_jsonschema(form: list[dict[str, Any]]) -> tuple[dict[str, Any], lisreturn properties, required-def resolve_app_config(app: App, *, session: Session) -> tuple[dict[str, Any], list[dict[str, Any]]]:- """Resolve `(features_dict, user_input_form)` for parameters / schema derivation.-- Raises `AppUnavailableError` on misconfigured apps.- """- if app.mode in {AppMode.ADVANCED_CHAT, AppMode.WORKFLOW}:- workflow = app.workflow_with_session(session=session)- if workflow is None:- raise AppUnavailableError()- return (- workflow.features_dict,- cast(list[dict[str, Any]], workflow.user_input_form(to_old_structure=True)),- )-- app_model_config = app.app_model_config_with_session(session=session)- if app_model_config is None:- raise AppUnavailableError()- annotation_reply = load_annotation_reply_config(session, app_model_config.app_id)- features_dict = cast(dict[str, Any], app_model_config.to_dict(annotation_reply=annotation_reply))- return features_dict, cast(list[dict[str, Any]], features_dict.get("user_input_form", []))---def build_input_schema(app: App, *, session: Session) -> dict[str, Any]:+def build_input_schema(mode: str, user_input_form: list[dict[str, Any]]) -> dict[str, Any]:"""Derive Draft 2020-12 JSON Schema from `user_input_form` + app mode.chat / agent-chat / advanced-chat: top-level `query` (required, minLength=1) + `inputs` object.completion / workflow: `inputs` object only.- Raises `AppUnavailableError` on misconfigured apps."""- _, user_input_form = resolve_app_config(app, session=session)inputs_props, inputs_required = _form_to_jsonschema(user_input_form)properties: dict[str, Any] = {}required: list[str] = []- if app.mode in _CHAT_FAMILY:+ if mode in _CHAT_FAMILY:properties["query"] = {"type": "string", "minLength": 1}required.append("query")diff --git a/api/controllers/openapi/_models.py b/api/controllers/openapi/_models.pyindex 299602328a4..fa53fe06fff 100644--- a/api/controllers/openapi/_models.py+++ b/api/controllers/openapi/_models.py@@ -3,8 +3,7 @@from __future__ import annotationsfrom datetime import datetime-from enum import StrEnum-from typing import Any, Final, Literal, Self+from typing import Any, Literal, Selffrom pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator@@ -14,36 +13,13 @@ from controllers.openapi._upload import UploadPart, UploadPartsfrom enums import DeploymentEditionfrom libs.helper import EmailStr, UUIDStr, UUIDStrOrEmpty, uuid_valuefrom models.model import AppMode-from services.app_dsl_service import Import+from services.entities.app_entities import SupportedAppType+from services.entities.dsl_entities import Import# Server-side cap on `limit` query param for /openapi/v1/* list endpoints.MAX_PAGE_LIMIT = 100-class SupportedAppType(StrEnum):- """App types the ``app`` usage face (``get app``) lists and filters.-- A curated subset of :class:`AppMode`: the real, user-facing app categories.- Excludes runtime-only mode tags that are not standalone apps- (``rag-pipeline`` is a knowledge ``Pipeline``; ``channel`` is unused) and the- roster-owned ``agent`` type (surfaced through the roster, not this list).-- Members reference ``AppMode.*.value`` so the subset relationship is- type-checked: dropping a member from ``AppMode`` breaks this at import.- This is the single source for the listable set — params, filters, and the- generated CLI whitelist all derive from it.- """-- COMPLETION = AppMode.COMPLETION.value- CHAT = AppMode.CHAT.value- ADVANCED_CHAT = AppMode.ADVANCED_CHAT.value- WORKFLOW = AppMode.WORKFLOW.value- AGENT_CHAT = AppMode.AGENT_CHAT.value---SUPPORTED_APP_TYPES: Final[tuple[AppMode, ...]] = tuple(AppMode(t.value) for t in SupportedAppType)--class UsageInfo(BaseModel):prompt_tokens: int = 0completion_tokens: int = 0diff --git a/api/controllers/openapi/app_dsl.py b/api/controllers/openapi/app_dsl.pyindex a6b581b7c3b..b7358358b7b 100644--- a/api/controllers/openapi/app_dsl.py+++ b/api/controllers/openapi/app_dsl.py@@ -4,9 +4,10 @@ from http import HTTPStatusfrom uuid import UUIDfrom flask_restx import Resource-from werkzeug.exceptions import Forbidden+from werkzeug.exceptions import BadRequestfrom constants.oauth_bearer import Scope+from controllers.common.errors import ForbiddenError, NotFoundErrorfrom controllers.common.rbac import PlainApp, RBACCheck, RBACPermission, Workspacefrom controllers.openapi import openapi_nsfrom controllers.openapi._contract import Example, Kind, endpoint, op_of@@ -17,7 +18,6 @@ from controllers.openapi._models import (AppDslImportResponse,Hint,)-from controllers.openapi.auth.context import Contextfrom controllers.openapi.auth.requirements import (CheckAppApiEnabled,CheckRBACPermission,@@ -28,12 +28,11 @@ from controllers.openapi.auth.requirements import ()from controllers.openapi.auth.subjects import AccountSubjectfrom extensions.ext_application_services import application_services-from extensions.ext_database import db-from machinery.context import RequestContext+from machinery.context import AppRequestContext, RequestContextfrom models.account import TenantAccountRole-from services.app_dsl_service import AppDslService+from services.entities.app_entities import AppExportOptionsfrom services.entities.dsl_entities import AppImportParams, CheckDependenciesResult, Import, ImportStatus-from services.errors.app import WorkflowNotFoundError+from services.errors.app import AppDiscoveryNotFoundError, IsDraftWorkflowError, WorkflowNotFoundErrorfrom services.errors.base import NoPermissionError@@ -65,7 +64,7 @@ class AppDslImportApi(Resource):"""@endpoint(- account_context=True,+ context="workspace",op="import.console_app.dsl",kind=Kind.OBJECT,summary="Import an app from DSL text or URL",@@ -103,7 +102,7 @@ class AppDslImportApi(Resource):ctx, AppImportParams.model_validate(body.model_dump()))except NoPermissionError as exc:- raise Forbidden(str(exc)) from exc+ raise ForbiddenError(str(exc)) from excresponse = _import_response(result, workspace_id=workspace_id)match result.status:@@ -128,7 +127,7 @@ class AppDslImportConfirmApi(Resource):"""@endpoint(- account_context=True,+ context="workspace",op="confirm.console_app.dsl_import",kind=Kind.OBJECT,summary="Confirm a pending DSL import",@@ -146,7 +145,7 @@ class AppDslImportConfirmApi(Resource):try:result = application_services().apps.imports.confirm_import(ctx, import_id)except NoPermissionError as exc:- raise Forbidden(str(exc)) from exc+ raise ForbiddenError(str(exc)) from excif result.status == ImportStatus.FAILED:return result, HTTPStatus.BAD_REQUEST@@ -167,6 +166,7 @@ class AppDslExportApi(Resource):"""@endpoint(+ context="app",op="export.console_app.dsl",kind=Kind.OBJECT,summary="Export app DSL as YAML text inside a JSON object",@@ -188,16 +188,15 @@ class AppDslExportApi(Resource):query=AppDslExportQuery,returns=(200, AppDslExportResponse, "Export successful"),)- def get(self, ctx: Context, app_id: str, *, query: AppDslExportQuery):+ def get(self, ctx: AppRequestContext, app_id: str, *, query: AppDslExportQuery):try:- data = AppDslService.export_dsl(- app_model=ctx.app,- session=db.session(),- include_secret=query.include_secret,- workflow_id=query.workflow_id,+ data = application_services().apps.exports.export_app(+ ctx, AppExportOptions(include_secret=query.include_secret, workflow_id=query.workflow_id))- except WorkflowNotFoundError as exc:- return str(exc), 404+ except (WorkflowNotFoundError, AppDiscoveryNotFoundError) as exc:+ raise NotFoundError(str(exc)) from exc+ except IsDraftWorkflowError as exc:+ raise BadRequest(str(exc)) from excreturn AppDslExportResponse(data=data), 200@@ -212,7 +211,7 @@ class AppDslCheckDependenciesApi(Resource):"""@endpoint(- account_context=True,+ context="workspace",op="check.console_app.dependency",kind=Kind.OBJECT,summary="Check plugin dependencies of an app",diff --git a/api/controllers/openapi/apps.py b/api/controllers/openapi/apps.pyindex e395ffe8ee8..890d88de50f 100644--- a/api/controllers/openapi/apps.py+++ b/api/controllers/openapi/apps.py@@ -2,30 +2,17 @@from __future__ import annotations-import uuid as _uuidfrom http import HTTPStatus-from typing import Anyfrom flask_restx import Resource-from sqlalchemy.orm import Session+from werkzeug.exceptions import NotFound-from configs import dify_configfrom constants.oauth_bearer import Scope-from controllers.common.fields import Parametersfrom controllers.common.rbac import PlainApp, RBACCheck, RBACPermissionfrom controllers.openapi import openapi_ns+from controllers.openapi._app_response import app_list_row, build_app_describe_responsefrom controllers.openapi._contract import Example, Kind, endpoint-from controllers.openapi._input_schema import EMPTY_INPUT_SCHEMA, build_input_schema, resolve_app_config-from controllers.openapi._models import (- SUPPORTED_APP_TYPES,- AppDescribeInfo,- AppDescribeQuery,- AppDescribeResponse,- AppListQuery,- AppListResponse,- AppListRow,-)-from controllers.openapi.auth.context import Context+from controllers.openapi._models import AppDescribeQuery, AppDescribeResponse, AppListQuery, AppListResponsefrom controllers.openapi.auth.requirements import (CheckAppApiEnabled,CheckRBACPermission,@@ -34,76 +21,16 @@ from controllers.openapi.auth.requirements import (CheckWorkspaceMember,)from controllers.openapi.auth.subjects import AccountSubject, ResourceAccessSubject-from controllers.service_api.app.error import AppUnavailableError-from core.app.app_config.common.parameters_mapping import get_parameters_from_feature_dictfrom extensions.ext_application_services import application_services-from models import App-from models.enums import AppStatus-from models.model import AppMode-from services.app.access import AppAccessFilter, resolve_app_access_filter-from services.entities.app_entities import AppListParams, AppSummary---def _is_listable(app: AppSummary) -> bool:- """Whether the openapi app face exposes this app (curated, listable types only)."""- return app.mode in SUPPORTED_APP_TYPES---_EMPTY_PARAMETERS: dict[str, Any] = {- "opening_statement": None,- "suggested_questions": [],- "user_input_form": [],- "file_upload": None,- "system_parameters": {},-}---def parameters_payload(app: App, *, session: Session) -> dict:- """Mirrors service_api/app/app.py::AppParameterApi response body."""- features_dict, user_input_form = resolve_app_config(app, session=session)- parameters = get_parameters_from_feature_dict(features_dict=features_dict, user_input_form=user_input_form)- return Parameters.model_validate(parameters).model_dump(mode="json")---def build_app_describe_response(app: App, fields: set[str] | None, *, session: Session) -> AppDescribeResponse:- """Public projection of an app (name / params / input schema) — never internal config."""- want_info = fields is None or "info" in fields- want_params = fields is None or "parameters" in fields- want_schema = fields is None or "input_schema" in fields-- info = (- AppDescribeInfo(- id=str(app.id),- name=app.name,- mode=app.mode,- description=app.description,- updated_at=app.updated_at.isoformat() if app.updated_at else None,- service_api_enabled=bool(app.enable_api),- is_agent=app.mode in (AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT),- )- if want_info- else None- )-- parameters: dict[str, Any] | None = None- input_schema: dict[str, Any] | None = None- if want_params:- try:- parameters = parameters_payload(app, session=session)- except AppUnavailableError:- parameters = dict(_EMPTY_PARAMETERS)- if want_schema:- try:- input_schema = build_input_schema(app, session=session)- except AppUnavailableError:- input_schema = dict(EMPTY_INPUT_SCHEMA)-- return AppDescribeResponse(info=info, parameters=parameters, input_schema=input_schema)+from machinery.context import AppRequestContext, RequestContext+from services.app.query_service import AppDiscoveryQuery+from services.errors.app import AppDiscoveryNotFoundError@openapi_ns.route("/apps/<string:app_id>")class AppDescribeApi(Resource):@endpoint(+ context="app",op="describe.console_app",kind=Kind.OBJECT,summary="App detail, parameters and runtime input_schema",@@ -124,14 +51,18 @@ class AppDescribeApi(Resource):query=AppDescribeQuery,returns=(200, AppDescribeResponse, "App description"),)- def get(self, ctx: Context, app_id: str, *, query: AppDescribeQuery):- # The pipeline has already loaded the app; project it.- return build_app_describe_response(ctx.app, query.fields, session=ctx.session)+ def get(self, ctx: AppRequestContext, app_id: str, *, query: AppDescribeQuery):+ try:+ result = application_services().apps.discovery.describe(ctx, query.fields)+ except AppDiscoveryNotFoundError as exc:+ raise NotFound(str(exc)) from exc+ return build_app_describe_response(result, query.fields)@openapi_ns.route("/apps")class AppListApi(Resource):@endpoint(+ context="workspace",op="get.console_app",kind=Kind.LIST,summary="List apps in a workspace",@@ -150,95 +81,13 @@ class AppListApi(Resource):query=AppListQuery,returns=(HTTPStatus.OK, AppListResponse, "App list"),)- def get(self, ctx: Context, *, query: AppListQuery):- workspace_id = query.workspace_id- account_id = str(ctx.subject.account_id or ctx.subject.token_id)-- empty = AppListResponse.build(page=query.page, limit=query.limit, total=0, items=[])-- if query.name:- try:- parsed_uuid = _uuid.UUID(query.name)- except ValueError:- parsed_uuid = None- else:- parsed_uuid = None-- access_filter = (- resolve_app_access_filter(workspace_id, account_id)- if dify_config.RBAC_ENABLED and isinstance(ctx.subject, AccountSubject)- else AppAccessFilter.unrestricted()+ def get(self, ctx: RequestContext, *, query: AppListQuery):+ result = application_services().apps.discovery.list_apps(+ ctx, AppDiscoveryQuery(query.page, query.limit, query.mode.value if query.mode else None, query.name))-- if ctx.resource_app_ids is not None:- access_filter = AppAccessFilter(set(ctx.resource_app_ids), can_manage_own_apps=False)-- tenant_name: str | None = None- if parsed_uuid is not None:- app = application_services().apps.queries.get_visible_app_by_id(str(parsed_uuid), workspace_id)- if app is None or str(app.tenant_id) != workspace_id:- return empty- if ctx.resource_app_ids is not None and (- str(app.id) not in ctx.resource_app_ids or app.status != AppStatus.NORMAL- ):- return empty- if not _is_listable(app):- return empty- # Apply RBAC visibility to the UUID fast-path the same way the service- # layer does for paginated queries (id in accessible set OR own app).- if not access_filter.is_app_accessible(- str(app.id), str(app.maintainer) if app.maintainer else None, account_id- ):- return empty- workspace = application_services().workspaces.management.get(workspace_id)- tenant_name = workspace.name if workspace else None- item = AppListRow(- id=str(app.id),- name=app.name,- description=app.description,- mode=app.mode,- updated_at=app.updated_at.isoformat() if app.updated_at else None,- workspace_id=str(workspace_id),- workspace_name=tenant_name,- )- env = AppListResponse.build(page=1, limit=1, total=1, items=[item])- return env-- params = AppListParams(- page=query.page,- limit=query.limit,- mode=query.mode.value if query.mode else "all", # type:ignore- name=query.name,- status=AppStatus.NORMAL,- # Visibility gate pushed into the query — pagination.total stays- # consistent across pages because invisible rows never count.- openapi_visible=True,+ return AppListResponse.build(+ page=result.page,+ limit=result.per_page,+ total=result.total,+ items=[app_list_row(entry) for entry in result.items],)-- access_filter.apply_to_params(params)-- pagination = application_services().apps.queries.get_paginate_apps(account_id, workspace_id, params)- if pagination is None:- return empty-- tenant_name = None- if pagination.items:- workspace = application_services().workspaces.management.get(workspace_id)- tenant_name = workspace.name if workspace else None-- items = [- AppListRow(- id=str(r.id),- name=r.name,- description=r.description,- mode=r.mode,- updated_at=r.updated_at.isoformat() if r.updated_at else None,- workspace_id=str(workspace_id),- workspace_name=tenant_name,- )- for r in pagination.items- if _is_listable(r)- ]-- env = AppListResponse.build(page=query.page, limit=query.limit, total=pagination.total, items=items)- return envdiff --git a/api/controllers/openapi/apps_permitted_external.py b/api/controllers/openapi/apps_permitted_external.pyindex 54586772b5f..d5d34863834 100644--- a/api/controllers/openapi/apps_permitted_external.py+++ b/api/controllers/openapi/apps_permitted_external.py@@ -10,19 +10,18 @@ from __future__ import annotationsfrom http import HTTPStatusfrom flask_restx import Resource+from werkzeug.exceptions import NotFound, ServiceUnavailablefrom constants.oauth_bearer import Scopefrom controllers.openapi import openapi_ns+from controllers.openapi._app_response import app_list_row, build_app_describe_responsefrom controllers.openapi._contract import Example, Kind, endpointfrom controllers.openapi._models import (AppDescribeQuery,AppDescribeResponse,- AppListRow,PermittedExternalAppsListQuery,PermittedExternalAppsListResponse,)-from controllers.openapi.apps import build_app_describe_response-from controllers.openapi.auth.context import Contextfrom controllers.openapi.auth.requirements import (CheckAppAccess,CheckAppApiEnabled,@@ -32,9 +31,9 @@ from controllers.openapi.auth.requirements import (from controllers.openapi.auth.subjects import ExternalSsoSubjectfrom enums import DeploymentEditionfrom extensions.ext_application_services import application_services-from models.enums import AppStatus-from services.enterprise.app_permitted_service import list_permitted_apps-from services.entities.app_entities import AppSummary+from machinery.context import AppRequestContext+from services.app.query_service import AppDiscoveryQuery+from services.errors.app import AppDiscoveryNotFoundError, PermittedAppsUnavailableError_ENTERPRISE_ONLY = frozenset({DeploymentEdition.ENTERPRISE})@@ -42,6 +41,7 @@ _ENTERPRISE_ONLY = frozenset({DeploymentEdition.ENTERPRISE})@openapi_ns.route("/permitted-external-apps")class PermittedExternalAppsListApi(Resource):@endpoint(+ context=None,op="get.console_app.external",kind=Kind.LIST,summary="List apps an external SSO subject may run",@@ -54,52 +54,25 @@ class PermittedExternalAppsListApi(Resource):returns=(HTTPStatus.OK, PermittedExternalAppsListResponse, "Permitted external apps list"),edition=_ENTERPRISE_ONLY,)- def get(self, ctx: Context, *, query: PermittedExternalAppsListQuery):- page_result = list_permitted_apps(- page=query.page,- limit=query.limit,- mode=query.mode.value if query.mode else None,- name=query.name,- )-- if not page_result.app_ids:- env = PermittedExternalAppsListResponse.build(- page=query.page, limit=query.limit, total=page_result.total, items=[]- )- return env-- apps_by_id: dict[str, AppSummary] = {- str(a.id): a for a in application_services().apps.queries.find_visible_apps_by_ids(page_result.app_ids)- }- tenant_ids = list({str(a.tenant_id) for a in apps_by_id.values()})- tenants_by_id = {str(t.id): t for t in application_services().workspaces.management.get_many(tenant_ids)}-- items: list[AppListRow] = []- for app_id in page_result.app_ids:- app = apps_by_id.get(app_id)- if not app or app.status != AppStatus.NORMAL:- continue- tenant = tenants_by_id.get(str(app.tenant_id))- items.append(- AppListRow(- id=str(app.id),- name=app.name,- description=app.description,- mode=app.mode,- updated_at=app.updated_at.isoformat() if app.updated_at else None,- workspace_id=str(app.tenant_id),- workspace_name=tenant.name if tenant else None,- )+ def get(self, *, query: PermittedExternalAppsListQuery):+ try:+ result = application_services().apps.discovery.list_permitted_apps(+ AppDiscoveryQuery(query.page, query.limit, query.mode.value if query.mode else None, query.name))- env = PermittedExternalAppsListResponse.build(- page=query.page, limit=query.limit, total=page_result.total, items=items+ except PermittedAppsUnavailableError as exc:+ raise ServiceUnavailable(str(exc)) from exc+ return PermittedExternalAppsListResponse.build(+ page=result.page,+ limit=result.per_page,+ total=result.total,+ items=[app_list_row(entry) for entry in result.items],)- return env@openapi_ns.route("/permitted-external-apps/<string:app_id>")class PermittedExternalAppDescribeApi(Resource):@endpoint(+ context="app",op="describe.console_app.external",kind=Kind.OBJECT,summary="External-subject app detail",@@ -114,6 +87,9 @@ class PermittedExternalAppDescribeApi(Resource):returns=(200, AppDescribeResponse, "Permitted external app description"),edition=_ENTERPRISE_ONLY,)- def get(self, ctx: Context, app_id: str, *, query: AppDescribeQuery):- # The pipeline has already loaded and ACL-checked the app; project it.- return build_app_describe_response(ctx.app, query.fields, session=ctx.session)+ def get(self, ctx: AppRequestContext, app_id: str, *, query: AppDescribeQuery):+ try:+ result = application_services().apps.discovery.describe(ctx, query.fields)+ except AppDiscoveryNotFoundError as exc:+ raise NotFound(str(exc)) from exc+ return build_app_describe_response(result, query.fields)diff --git a/api/controllers/openapi/auth/context.py b/api/controllers/openapi/auth/context.pyindex 96d7e209d5c..0b74225a1b0 100644--- a/api/controllers/openapi/auth/context.py+++ b/api/controllers/openapi/auth/context.py@@ -55,8 +55,9 @@ class Context:return RequestContext(request_id=self.request_id,trace_id=self.trace_id,- account_id=str(self.subject.account_id),+ account_id=str(self.subject.account_id or self.subject.token_id),active_workspace_id=str(self.workspace.id),+ resource_app_ids=self.resource_app_ids,)@propertydiff --git a/api/controllers/openapi/auth/pipelines.py b/api/controllers/openapi/auth/pipelines.pyindex ecd9b0f9f92..3d6226ef34c 100644--- a/api/controllers/openapi/auth/pipelines.py+++ b/api/controllers/openapi/auth/pipelines.py@@ -2,7 +2,8 @@ from __future__ import annotationsfrom collections.abc import Callable, Generatorfrom contextlib import contextmanager-from typing import Any, ClassVar, override+from functools import partial+from typing import Any, ClassVar, assert_never, overridefrom flask import current_app, requestfrom flask_login import user_logged_in@@ -22,10 +23,9 @@ from controllers.openapi.auth.requirements import (from controllers.openapi.auth.resource_access import CheckResourceAccessfrom controllers.openapi.auth.spec import EndpointSpecfrom controllers.openapi.auth.subjects import AccountSubject, ExternalSsoSubject, ResourceAccessSubject, Subject-from core.logging.context import get_request_id, get_trace_idfrom enums import DeploymentEditionfrom libs.oauth_bearer import AuthContext, reset_auth_ctx, set_auth_ctx-from machinery.context import RequestContext+from machinery.context import AppRequestContextfrom models.account import Accountfrom models.model import EndUser@@ -57,12 +57,25 @@ class Pipeline:for requirement in sorted(spec.requirements + self.fixed, key=lambda item: item.rank):requirement.run(subject, ctx, session)with mounted(subject, auth, ctx):- if spec.account_context:- request_context = RequestContext(get_request_id(), get_trace_id(), ctx.account.id, ctx.workspace.id)+ # Bind handler arguments while the admission Session is still open.+ handler_call: Callable[[], Any]+ match spec.context:+ case None:+ handler_call = call+ case "orm":+ handler_call = partial(call, ctx=ctx)+ case "workspace":+ handler_call = partial(call, ctx=ctx.request_context)+ case "app":+ app_context = AppRequestContext(tenant_id=ctx.app.tenant_id, app_id=ctx.app.id)+ handler_call = partial(call, ctx=app_context)+ case unexpected:+ assert_never(unexpected)++ if spec.context != "orm":session.commit()session.close()- return call(ctx=request_context)- return call(ctx=ctx)+ return handler_call()def pipeline_for_subject(subject: Subject) -> Pipeline:diff --git a/api/controllers/openapi/auth/router.py b/api/controllers/openapi/auth/router.pyindex 5ccd1436be3..41090d53e95 100644--- a/api/controllers/openapi/auth/router.py+++ b/api/controllers/openapi/auth/router.py@@ -61,9 +61,8 @@ class AuthRouter:subject = subject_from_auth(auth)pipeline = pipeline_for_subject(subject)- # ORM-backed endpoints share the admission session with the handler.- # Account-context endpoints materialize identity and release it in the- # pipeline, before calling services that own their transactions.+ # The pipeline closes the admission session before handlers that use only+ # identity values or no context; ORM handlers keep sharing it.with session_factory.create_session() as session:ctx = Context(subject,diff --git a/api/controllers/openapi/auth/spec.py b/api/controllers/openapi/auth/spec.pyindex 4a8f97c8c71..d722aba9dcf 100644--- a/api/controllers/openapi/auth/spec.py+++ b/api/controllers/openapi/auth/spec.py@@ -11,13 +11,15 @@ from __future__ import annotationsfrom collections.abc import Mappingfrom dataclasses import dataclassfrom enum import StrEnum-from typing import Any+from typing import Any, Literalfrom pydantic import BaseModelfrom controllers.openapi.auth.requirements import Requirementfrom enums import DeploymentEdition+type AdmissionContext = Literal["orm", "workspace", "app"]+class Kind(StrEnum):"""Response body kinds. Frozen protocol names; the CLI has one handler per value."""@@ -62,12 +64,17 @@ class EndpointSpec:is read, because the route is not exposed on this edition at all. It isnot `ExternalSsoPipeline`'s own gate, which 403s a token kind afterauthentication.++ `context` selects the handler's `ctx` argument and admission Session lifetime.+ `"orm"` keeps the Session open for the handler; all other values commit and+ close it before the handler runs. `None` omits the `ctx` argument; admission+ requirements still run for every endpoint."""requirements: tuple[Requirement, ...]catalog: CatalogMetaedition: frozenset[DeploymentEdition] | None = None- account_context: bool = False+ context: AdmissionContext | None = "orm"def allows(self, edition: DeploymentEdition) -> bool:"""Whether this deployment exposes the route at all. `edition is None`diff --git a/api/controllers/service_api/end_user/end_user.py b/api/controllers/service_api/end_user/end_user.pyindex 723c915a145..283788687bb 100644--- a/api/controllers/service_api/end_user/end_user.py+++ b/api/controllers/service_api/end_user/end_user.py@@ -8,7 +8,8 @@ from controllers.service_api.end_user.error import EndUserNotFoundErrorfrom controllers.service_api.wraps import validate_app_tokenfrom extensions.ext_application_services import application_servicesfrom fields.end_user_fields import EndUserDetail-from machinery.context import ServiceApiRequestContext+from libs.helper import dump_response+from machinery.context import AppRequestContextfrom models.model import Appfrom services.app_scoped_end_user_query_service import AppScopedEndUserNotFoundError@@ -50,7 +51,7 @@ class EndUserApi(Resource):cross-tenant/app access when an end-user ID is known."""- request_context = ServiceApiRequestContext(+ request_context = AppRequestContext(tenant_id=app_model.tenant_id,app_id=app_model.id,)@@ -59,4 +60,4 @@ class EndUserApi(Resource):except AppScopedEndUserNotFoundError as error:raise EndUserNotFoundError() from error- return EndUserDetail.model_validate(end_user).model_dump(mode="json")+ return dump_response(EndUserDetail, end_user)diff --git a/api/core/llm_generator/llm_generator.py b/api/core/llm_generator/llm_generator.pyindex ea066698a29..06272037c27 100644--- a/api/core/llm_generator/llm_generator.py+++ b/api/core/llm_generator/llm_generator.py@@ -169,9 +169,7 @@ def _parse_string_list(text: str) -> list[str]:class WorkflowServiceInterface(Protocol):- def get_draft_workflow(- self, app_model: App, workflow_id: str | None = None, *, session: Session- ) -> Workflow | None:+ def get_draft_workflow(self, app_model: App, *, session: Session) -> Workflow | None:passdef get_node_last_run(self, app_model: App, workflow: Workflow, node_id: str) -> WorkflowNodeExecutionModel | None:diff --git a/api/extensions/application_services/app.py b/api/extensions/application_services/app.pyindex cc63859dadf..d7b62e352ec 100644--- a/api/extensions/application_services/app.py+++ b/api/extensions/application_services/app.py@@ -7,6 +7,8 @@ from sqlalchemy.orm import Session, sessionmakerfrom repositories.account.repository import SQLAlchemyAccountRepositoryfrom repositories.app.api_key_repository import AppApiKeyRepositoryfrom repositories.app.console_repository import ConsoleAppRepository+from repositories.app.export_repository import AppExportRepository+from repositories.workspace.workspace_repository import WorkspaceRepositoryfrom services.agent.roster_package_exporter import RosterAgentPackageExporterfrom services.agent.roster_package_importer import RosterAgentPackageImporterfrom services.api_token_service import ApiTokenCache@@ -14,8 +16,10 @@ from services.app.api_key_service import AppApiKeyServicefrom services.app.console_gateway import AppLifecycleGateway, AppTransferGateway, EnterpriseConsoleAppAccessfrom services.app.console_service import ConsoleAppServicefrom services.app.creators_platform_gateway import CreatorsPlatformGateway+from services.app.discovery_gateway import EnterpriseAppDiscoveryAccess+from services.app.export_service import AppExportServicefrom services.app.import_service import AppImportService-from services.app.query_service import AppQueryService+from services.app.query_service import AppDiscoveryServicefrom services.app_dsl_service import AppDslServicefrom services.app_package_service import AppPackageServicefrom services.app_tracing_config_gateway import OpsTraceManagerGateway@@ -27,8 +31,9 @@ from services.recommended_app_package_service import RecommendedAppPackageServic@dataclass(frozen=True, slots=True)class AppServices:imports: AppImportService+ exports: AppExportService+ discovery: AppDiscoveryServiceconsole: ConsoleAppService- queries: AppQueryServicedef build_app_services(@@ -49,6 +54,14 @@ def build_app_services()return AppServices(imports=AppImportService(accounts=SQLAlchemyAccountRepository(database_client), definitions=transfers),+ exports=AppExportService(+ apps=AppExportRepository(session_factory=database_client), serialize=AppDslService.serialize_export_data+ ),+ discovery=AppDiscoveryService(+ apps=repository,+ workspaces=WorkspaceRepository(database_client),+ access=EnterpriseAppDiscoveryAccess(),+ ),console=ConsoleAppService(apps=repository,access=EnterpriseConsoleAppAccess(members=rbac_members),@@ -57,7 +70,6 @@ def build_app_services(tracing=OpsTraceManagerGateway(),lifecycle=AppLifecycleGateway(session_factory=database_client),),- queries=AppQueryService(apps=repository),)diff --git a/api/extensions/application_services/knowledge.py b/api/extensions/application_services/knowledge.pyindex 70fbfff8057..ee377d87ae4 100644--- a/api/extensions/application_services/knowledge.py+++ b/api/extensions/application_services/knowledge.py@@ -9,6 +9,7 @@ from configs import dify_configfrom core.app.apps.pipeline.pipeline_generator import PipelineGeneratorfrom core.rag.extractor.entity.datasource_type import DatasourceTypefrom libs.helper import generate_text_hash+from repositories.app.console_repository import ConsoleAppRepositoryfrom repositories.knowledge.dataset_api_key_repository import DatasetApiKeyRepositoryfrom repositories.knowledge.dataset_repository import SQLAlchemyDatasetRepositoryfrom repositories.knowledge.document_repository import SQLAlchemyDocumentRepository@@ -16,7 +17,6 @@ from repositories.knowledge.metadata_repository import SQLAlchemyMetadataRepositfrom repositories.knowledge.segment_repository import SQLAlchemySegmentRepositoryfrom repositories.knowledge.upload_file_repository import SQLAlchemyKnowledgeUploadRepositoryfrom services.api_token_service import ApiTokenCache-from services.app.query_service import AppQueryServicefrom services.data_source.credential_gateway import (ActorAwareDatasourceCredentialGateway,TrustedStoredDatasourceCredentialGateway,@@ -93,7 +93,6 @@ def build_knowledge_services(providers: DatasourceProviderService,redis: RedisSegmentClient,tags: TagTargetQuery,- app_queries: AppQueryService,rbac_members: MemberService,) -> KnowledgeServices:"""Build the dataset-controller knowledge use cases."""@@ -129,7 +128,10 @@ def build_knowledge_services(datasets=DatasetApplicationService(dataset_access=dataset_access,operations=SQLAlchemyDatasetOperations(- session_factory=database_client, tags=tags, app_queries=app_queries, members=rbac_members+ session_factory=database_client,+ tags=tags,+ app_queries=ConsoleAppRepository(session_factory=database_client),+ members=rbac_members,),rbac_enabled=dify_config.RBAC_ENABLED,service_api_url=dify_config.SERVICE_API_URL,diff --git a/api/extensions/ext_application_services.py b/api/extensions/ext_application_services.pyindex 51514b7eef4..fe28573388a 100644--- a/api/extensions/ext_application_services.py+++ b/api/extensions/ext_application_services.py@@ -470,7 +470,6 @@ def build_application_services(providers=datasource_credentials.providers,redis=redis,tags=tags,- app_queries=apps.queries,rbac_members=rbac.members,)app_scoped_end_user_repository = AppScopedEndUserRepo(session_factory=database_client)diff --git a/api/machinery/context.py b/api/machinery/context.pyindex f87c0027d70..aca308f82a7 100644--- a/api/machinery/context.py+++ b/api/machinery/context.py@@ -4,10 +4,19 @@ from dataclasses import dataclassfrom typing import NamedTuple+@dataclass(frozen=True, slots=True, kw_only=True)+class AppRequestContext:+ """Tenant and app scope established by API admission."""++ tenant_id: str+ app_id: str++class RequestContext(NamedTuple):"""Framework-neutral request metadata and admitted identity.Anonymous admission uses empty ``account_id`` and ``active_workspace_id`` values.+ ``resource_app_ids`` is absent for account callers; an empty set admits no apps."""request_id: str@@ -15,14 +24,7 @@ class RequestContext(NamedTuple):account_id: stractive_workspace_id: strremote_ip: str | None = None---@dataclass(frozen=True, slots=True, kw_only=True)-class ServiceApiRequestContext:- """Stable app scope admitted for a Service API request."""-- tenant_id: str- app_id: str+ resource_app_ids: frozenset[str] | None = Noneclass AccountRequestContext(NamedTuple):diff --git a/api/repositories/app/console_repository.py b/api/repositories/app/console_repository.pyindex 9b7a01d366e..9e3dc2fff18 100644--- a/api/repositories/app/console_repository.py+++ b/api/repositories/app/console_repository.py@@ -24,7 +24,7 @@ from core.agent.publish_visibility import agent_has_workflow_callable_active_snafrom core.trigger.constants import TRIGGER_NODE_TYPESfrom libs.datetime_utils import naive_utc_nowfrom libs.pagination import PaginatedResult, paginate_query-from machinery.context import RequestContext+from machinery.context import AppRequestContext, RequestContextfrom models.account import Account, Tenantfrom models.agent import (APP_BACKED_AGENT_SOURCES,@@ -41,13 +41,14 @@ from models.model import App, AppMode, AppModelConfig, AppStar, IconTypefrom models.skill import AgentSkillBindingfrom models.workflow import Workflowfrom repositories.app.response import app_record, app_summary+from repositories.app_definition_query_repository import load_app_parameter_configfrom repositories.tag_repository import TagRepositoryfrom services.agent.errors import (AgentAccessNotReadyError,AgentNameConflictError,)from services.app.console_service import ConsoleAppNotFoundError, ConsoleApps-from services.app.query_service import AppQueryStore+from services.app.query_service import AppDescription, DiscoveryApps, RelatedAppsfrom services.app_creation_records import create_installed_app_record, create_site_recordfrom services.entities.app_entities import (RECENT_APP_MODES,@@ -71,8 +72,9 @@ from services.entities.app_entities import (StarredAppListParams,UpdateAppParams,)+from services.errors.app import AppDiscoveryNotFoundErrorfrom services.errors.base import NoPermissionError-from services.openapi.visibility import apply_openapi_gate, is_openapi_visible+from services.openapi.visibility import apply_openapi_gatelogger = logging.getLogger(__name__)_app_trace_settings_adapter = TypeAdapter(AppTraceSettings)@@ -114,7 +116,7 @@ def console_app_actor(session: Session, context: RequestContext) -> Account:return account-class ConsoleAppRepository(ConsoleApps, AppQueryStore):+class ConsoleAppRepository(ConsoleApps, DiscoveryApps, RelatedApps):def __init__(self, *, session_factory: sessionmaker[Session]) -> None:self._session_factory = session_factory@@ -133,11 +135,20 @@ class ConsoleAppRepository(ConsoleApps, AppQueryStore):with self._session_factory() as session:return session.scalar(statement)+ @override+ def describe(self, context: AppRequestContext, *, include_config: bool) -> AppDescription:+ with self._session_factory() as session:+ app = self.get_visible_app_by_id(context.app_id, session, tenant_id=context.tenant_id)+ if app is None:+ raise AppDiscoveryNotFoundError("app not found")+ config = load_app_parameter_config(app, session=session) if include_config else None+ return AppDescription(app_summary(app), bool(app.enable_api), config)+@overridedef find_visible_app(self, app_id: str, tenant_id: str) -> AppSummary | None:with self._session_factory() as session:- app = self.get_visible_app_by_id(app_id, session)- return app_summary(app) if app is not None and app.tenant_id == tenant_id else None+ app = self.get_visible_app_by_id(app_id, session, tenant_id=tenant_id)+ return app_summary(app) if app is not None else None@overridedef find_visible_apps(self, app_ids: Sequence[str]) -> list[AppSummary]:@@ -434,11 +445,14 @@ class ConsoleAppRepository(ConsoleApps, AppQueryStore):def get_visible_app_by_id(app_id: str,session: Session,+ *,+ tenant_id: str,) -> App | None:- app = session.get(App, app_id)- if not app or app.status != "normal" or not is_openapi_visible(app):- return None- return app+ """Find a visible normal app within the admitted tenant."""+ statement = apply_openapi_gate(+ select(App).where(App.id == app_id, App.tenant_id == tenant_id, App.status == AppStatus.NORMAL)+ )+ return session.scalar(statement)@staticmethoddef find_visible_apps_by_ids(diff --git a/api/repositories/app/export_repository.py b/api/repositories/app/export_repository.pynew file mode 100644index 00000000000..9bc3f7ade6f--- /dev/null+++ b/api/repositories/app/export_repository.py@@ -0,0 +1,42 @@+"""Own the read Session for app lookup and DSL export materialization."""++from typing import override++from sqlalchemy.orm import Session, sessionmaker++from models.model import App+from repositories.app.console_repository import ConsoleAppRepository+from services.app.export_service import AppExportStore+from services.app_dsl_service import AppDslService+from services.entities.app_entities import AppExportOptions+from services.entities.dsl_entities import AppDslExportData+from services.errors.app import AppDiscoveryNotFoundError+++class AppExportRepository(AppExportStore):+ def __init__(self, *, session_factory: sessionmaker[Session]) -> None:+ self._session_factory = session_factory++ @override+ def load_export_data(self, *, app_id: str, tenant_id: str | None, options: AppExportOptions) -> AppDslExportData:+ """Read all DSL data before serialization performs external plugin I/O.++ The trusted inner API passes no tenant and can export across workspaces,+ including apps hidden from OpenAPI. Account callers require both tenant+ ownership and OpenAPI visibility.+ """+ with self._session_factory() as session:+ app = (+ session.get(App, app_id)+ if tenant_id is None+ else ConsoleAppRepository.get_visible_app_by_id(app_id, session, tenant_id=tenant_id)+ )+ if app is None:+ raise AppDiscoveryNotFoundError("app not found")+ return AppDslService.load_export_data(+ app_model=app,+ session=session,+ include_secret=options.include_secret,+ workflow_id=options.workflow_id,+ version_id=options.version_id,+ )diff --git a/api/repositories/app_definition_query_repository.py b/api/repositories/app_definition_query_repository.pyindex 03114a08d46..0fae049be29 100644--- a/api/repositories/app_definition_query_repository.py+++ b/api/repositories/app_definition_query_repository.py@@ -45,8 +45,45 @@ def map_site_configuration(site: Site) -> AppSiteConfiguration:)+def _load_app_model_config(app: App, *, session: Session) -> AppModelConfig | None:+ if not app.app_model_config_id:+ return None+ return session.scalar(+ select(AppModelConfig).where(AppModelConfig.id == app.app_model_config_id, AppModelConfig.app_id == app.id)+ )+++def load_app_parameter_config(app: App, *, session: Session) -> AppParameterConfig | None:+ """Materialize the app's own selected config within the caller-owned Session."""+ if app.mode in {AppMode.ADVANCED_CHAT, AppMode.WORKFLOW}:+ if not app.workflow_id:+ return None+ workflow = session.scalar(+ select(Workflow).where(+ Workflow.id == app.workflow_id,+ Workflow.app_id == app.id,+ Workflow.tenant_id == app.tenant_id,+ )+ )+ if workflow is None:+ return None+ return AppParameterConfig(+ features_dict=workflow.features_dict,+ user_input_form=cast(list[dict[str, Any]], workflow.user_input_form(to_old_structure=True)),+ )++ app_model_config = _load_app_model_config(app, session=session)+ if app_model_config is None:+ return None+ features_dict = app_model_config.to_dict(annotation_reply=load_annotation_reply_config(session, app.id))+ return AppParameterConfig(+ features_dict=features_dict,+ user_input_form=cast(list[dict[str, Any]], features_dict.get("user_input_form", [])),+ )++def _get_public_agent_parameter_config(app: App, *, session: Session) -> AppParameterConfig:- app_model_config = app.app_model_config_with_session(session=session)+ app_model_config = _load_app_model_config(app, session=session)agent = app.agent_app_binding_with_session(session=session)if agent is None:raise AgentAppGeneratorError("Agent App has no bound Agent")@@ -102,27 +139,7 @@ class AppDefinitionQueryRepository(AppDefinitionQuery):if public_runtime and app.mode == AppMode.AGENT:return _get_public_agent_parameter_config(app, session=session)- if app.mode in {AppMode.ADVANCED_CHAT, AppMode.WORKFLOW}:- workflow = app.workflow_with_session(session=session)- if workflow is None:- return None-- return AppParameterConfig(- features_dict=workflow.features_dict,- user_input_form=cast(list[dict[str, Any]], workflow.user_input_form(to_old_structure=True)),- )-- app_model_config = app.app_model_config_with_session(session=session)- if app_model_config is None:- return None-- features_dict = app_model_config.to_dict(- annotation_reply=load_annotation_reply_config(session, app.id),- )- return AppParameterConfig(- features_dict=features_dict,- user_input_form=cast(list[dict[str, Any]], features_dict.get("user_input_form", [])),- )+ return load_app_parameter_config(app, session=session)@overridedef get_tool_icon_sources(self, app_id: str) -> tuple[AppToolIconSource, ...] | None:diff --git a/api/repositories/workspace/workspace_repository.py b/api/repositories/workspace/workspace_repository.pyindex a0cf0095cb5..69bee901f46 100644--- a/api/repositories/workspace/workspace_repository.py+++ b/api/repositories/workspace/workspace_repository.py@@ -29,6 +29,7 @@ from repositories.account.repository import SQLAlchemyAccountRepositoryfrom services.account.contracts import AccountCreationfrom services.account.login_service import ConsoleAuthWorkspaceQueryfrom services.account_ports import AccountWorkspaceMembershipQuery, AccountWorkspaceSnapshotQuery+from services.app.query_service import DiscoveryWorkspacesfrom services.entities.account_access_entities import AccountWorkspaceSnapshotfrom services.errors.workspace import (MemberNotInTenantError,@@ -61,10 +62,19 @@ class WorkspaceRepository(ConsoleAuthWorkspaceQuery,DeviceWorkspaceQuery,WorkspaceMemberQuery,+ DiscoveryWorkspaces,):def __init__(self, session_factory: sessionmaker[Session]) -> None:self._session_factory = session_factory+ @override+ def names_by_ids(self, workspace_ids: Sequence[str]) -> dict[str, str]:+ if not workspace_ids:+ return {}+ with self._session_factory() as session:+ rows = session.execute(select(Tenant.id, Tenant.name).where(Tenant.id.in_(workspace_ids)))+ return dict(rows.tuples().all())+def get_account_role(self, *, account_id: str, tenant_id: str) -> str | None:"""Read the current membership role without loading or mutating an Account."""return self.get_legacy_role(workspace_id=tenant_id, account_id=account_id)diff --git a/api/services/app/access.py b/api/services/app/access.pyindex a37793bf051..4b3e8fe03f2 100644--- a/api/services/app/access.py+++ b/api/services/app/access.py@@ -5,7 +5,7 @@ from dataclasses import dataclassfrom services.enterprise import rbac_service as enterprise_rbac_servicefrom services.entities.app_entities import AppListBaseParams-from services.rbac.contracts import MyPermissionsResponse+from services.rbac.contracts import MyPermissionsResponse, ResourceWhitelistResources# Permission keys (dot-notation, from MyPermissionsResponse) that grant# list/preview access to an app. Keep this the single source of truth for both@@ -78,7 +78,13 @@ def resolve_app_access_filter(account_id,)whitelist_scope = enterprise_rbac_service.RBACService.AppAccess.whitelist_resources(tenant_id, account_id)+ return app_access_filter_from_permissions(permissions, whitelist_scope)++def app_access_filter_from_permissions(+ permissions: MyPermissionsResponse, whitelist_scope: ResourceWhitelistResources+) -> AppAccessFilter:+ """Compute visibility from permission and whitelist snapshots without I/O."""can_manage_own_apps = _MANAGE_OWN_APPS_PERMISSION_KEY in permissions.workspace.permission_keyshas_default_preview = has_app_list_permission(permissions.app.default_permission_keys) or has_app_list_permission(permissions.workspace.permission_keys@@ -94,7 +100,7 @@ def resolve_app_access_filter(}accessible_app_ids: set[str] | None- if getattr(whitelist_scope, "unrestricted", False):+ if whitelist_scope.unrestricted:accessible_app_ids = permission_app_idselse:# A restricted app whitelist is the highest-priority visibility gate:diff --git a/api/services/app/discovery_gateway.py b/api/services/app/discovery_gateway.pynew file mode 100644index 00000000000..61e5bbc998c--- /dev/null+++ b/api/services/app/discovery_gateway.py@@ -0,0 +1,25 @@+"""Enterprise visibility adapter for app discovery."""++from typing import override++from configs import dify_config+from machinery.context import RequestContext+from services.app.access import AppAccessFilter, app_access_filter_from_permissions+from services.app.query_service import AppDiscoveryAccess, AppDiscoveryQuery+from services.enterprise.app_permitted_service import list_permitted_apps+from services.enterprise.rbac_service import RBACService+from services.entities.app_entities import PermittedAppsPage+++class EnterpriseAppDiscoveryAccess(AppDiscoveryAccess):+ @override+ def visibility(self, context: RequestContext) -> AppAccessFilter:+ if not dify_config.RBAC_ENABLED:+ return AppAccessFilter.unrestricted()+ permissions = RBACService.MyPermissions.get(context.active_workspace_id, context.account_id)+ whitelist = RBACService.AppAccess.whitelist_resources(context.active_workspace_id, context.account_id)+ return app_access_filter_from_permissions(permissions, whitelist)++ @override+ def permitted_apps(self, query: AppDiscoveryQuery) -> PermittedAppsPage:+ return list_permitted_apps(page=query.page, limit=query.limit, mode=query.mode, name=query.name)diff --git a/api/services/app/export_service.py b/api/services/app/export_service.pynew file mode 100644index 00000000000..6db0222fa3c--- /dev/null+++ b/api/services/app/export_service.py@@ -0,0 +1,31 @@+"""DSL export for account and trusted inner API callers."""++from collections.abc import Callable+from typing import Protocol++from machinery.context import AppRequestContext+from services.entities.app_entities import AppExportOptions+from services.entities.dsl_entities import AppDslExportData+++class AppExportStore(Protocol):+ def load_export_data(self, *, app_id: str, tenant_id: str | None, options: AppExportOptions) -> AppDslExportData:+ """Close the read Session before returning materialized export data.++ A null tenant is reserved for the trusted cross-workspace inner API.+ """+ ...+++class AppExportService:+ def __init__(self, *, apps: AppExportStore, serialize: Callable[[AppDslExportData], str]) -> None:+ self._apps = apps+ self._serialize = serialize++ def export_app(self, context: AppRequestContext, options: AppExportOptions) -> str:+ prepared = self._apps.load_export_data(app_id=context.app_id, tenant_id=context.tenant_id, options=options)+ return self._serialize(prepared)++ def export_for_inner(self, app_id: str, options: AppExportOptions) -> str:+ prepared = self._apps.load_export_data(app_id=app_id, tenant_id=None, options=options)+ return self._serialize(prepared)diff --git a/api/services/app/query_service.py b/api/services/app/query_service.pyindex a6dcfb445ec..0f577d77d56 100644--- a/api/services/app/query_service.py+++ b/api/services/app/query_service.py@@ -1,36 +1,134 @@-"""App discovery and access checks over materialized data."""+"""App discovery queries over materialized records."""from collections.abc import Sequence+from dataclasses import dataclassfrom typing import Protocol+from uuid import UUIDfrom libs.pagination import PaginatedResult-from services.entities.app_entities import AppListParams, AppRecord, AppSummary+from machinery.context import AppRequestContext, RequestContext+from models.enums import AppStatus+from services.app.access import AppAccessFilter+from services.app_definition_query_service import AppParameterConfig+from services.entities.app_entities import SUPPORTED_APP_TYPES, AppListParams, AppRecord, AppSummary, PermittedAppsPage-class AppQueryStore(Protocol):+@dataclass(frozen=True)+class AppDiscoveryQuery:+ page: int+ limit: int+ mode: str | None+ name: str | None+++@dataclass(frozen=True)+class AppDiscoveryEntry:+ app: AppSummary+ workspace_name: str | None+++@dataclass(frozen=True)+class AppDescription:+ app: AppSummary+ service_api_enabled: bool+ config: AppParameterConfig | None+++class DiscoveryApps(Protocol):def find_visible_app(self, app_id: str, tenant_id: str) -> AppSummary | None: ...def find_visible_apps(self, app_ids: Sequence[str]) -> list[AppSummary]: ...def query_apps(self, user_id: str, tenant_id: str, params: AppListParams) -> PaginatedResult[AppSummary] | None: ...+ def describe(self, context: AppRequestContext, *, include_config: bool) -> AppDescription: ...+++class RelatedApps(Protocol):def related_apps(self, tenant_id: str, app_ids: Sequence[str]) -> list[AppRecord]: ...-class AppQueryService:- def __init__(self, *, apps: AppQueryStore) -> None:+class DiscoveryWorkspaces(Protocol):+ def names_by_ids(self, workspace_ids: Sequence[str]) -> dict[str, str]: ...+++class AppDiscoveryAccess(Protocol):+ def visibility(self, context: RequestContext) -> AppAccessFilter: ...++ def permitted_apps(self, query: AppDiscoveryQuery) -> PermittedAppsPage: ...+++class AppDiscoveryService:+ def __init__(self, *, apps: DiscoveryApps, workspaces: DiscoveryWorkspaces, access: AppDiscoveryAccess) -> None:self._apps = apps+ self._workspaces = workspaces+ self._access = access++ def list_apps(self, context: RequestContext, query: AppDiscoveryQuery) -> PaginatedResult[AppDiscoveryEntry]:+ access = (+ AppAccessFilter(set(context.resource_app_ids), can_manage_own_apps=False)+ if context.resource_app_ids is not None+ else self._access.visibility(context)+ )+ try:+ app_id = str(UUID(query.name)) if query.name else None+ except ValueError:+ app_id = None++ if app_id is not None:+ app = self._apps.find_visible_app(app_id, context.active_workspace_id)+ if (+ app is None+ or app.mode not in SUPPORTED_APP_TYPES+ or not access.is_app_accessible(app.id, app.maintainer, context.account_id)+ ):+ return PaginatedResult(items=[], total=0, page=query.page, per_page=query.limit)+ return self._page([app], total=1, page=1, limit=1)- def get_visible_app_by_id(self, app_id: str, tenant_id: str) -> AppSummary | None:- return self._apps.find_visible_app(app_id, tenant_id)+ params = AppListParams.model_validate(+ {+ "page": query.page,+ "limit": query.limit,+ "mode": query.mode or "all",+ "name": query.name,+ "status": AppStatus.NORMAL,+ "openapi_visible": True,+ }+ )+ access.apply_to_params(params)+ result = self._apps.query_apps(context.account_id, context.active_workspace_id, params)+ return self._page(+ [app for app in result.items if app.mode in SUPPORTED_APP_TYPES] if result else [],+ total=result.total if result else 0,+ page=query.page,+ limit=query.limit,+ )- def find_visible_apps_by_ids(self, app_ids: Sequence[str]) -> list[AppSummary]:- return self._apps.find_visible_apps(app_ids)+ def list_permitted_apps(self, query: AppDiscoveryQuery) -> PaginatedResult[AppDiscoveryEntry]:+ permitted = self._access.permitted_apps(query)+ apps = {app.id: app for app in self._apps.find_visible_apps(permitted.app_ids)} if permitted.app_ids else {}+ return self._page(+ [+ apps[app_id]+ for app_id in permitted.app_ids+ if app_id in apps and apps[app_id].status == AppStatus.NORMAL+ ],+ total=permitted.total,+ page=query.page,+ limit=query.limit,+ )- def get_paginate_apps(- self, user_id: str, tenant_id: str, params: AppListParams- ) -> PaginatedResult[AppSummary] | None:- return self._apps.query_apps(user_id, tenant_id, params)+ def describe(self, context: AppRequestContext, fields: set[str] | None) -> AppDescription:+ include_config = fields is None or bool(fields & {"parameters", "input_schema"})+ return self._apps.describe(context, include_config=include_config)- def related_apps(self, tenant_id: str, app_ids: Sequence[str]) -> list[AppRecord]:- return self._apps.related_apps(tenant_id, app_ids)+ def _page(+ self, apps: Sequence[AppSummary], *, total: int, page: int, limit: int+ ) -> PaginatedResult[AppDiscoveryEntry]:+ names = self._workspaces.names_by_ids(list({app.tenant_id for app in apps})) if apps else {}+ return PaginatedResult(+ items=[AppDiscoveryEntry(app, names.get(app.tenant_id)) for app in apps],+ total=total,+ page=page,+ per_page=limit,+ )diff --git a/api/services/app_dsl_service.py b/api/services/app_dsl_service.pyindex f2505ddb793..77c26ff710e 100644--- a/api/services/app_dsl_service.py+++ b/api/services/app_dsl_service.py@@ -928,6 +928,19 @@ class AppDslService:export_data["dependencies"] = [jsonable_encoder(item.model_dump()) for item in dependencies]return yaml.dump(export_data, allow_unicode=True)+ @staticmethod+ def _load_export_workflow(app_model: App, *, workflow_id: str | None, session: Session) -> Workflow:+ """Require the selected published version, or the app draft when no ID is supplied."""+ if workflow_id:+ workflow = WorkflowService.get_published_workflow_by_id(app_model, workflow_id, session=session)+ if workflow is None:+ raise WorkflowNotFoundError(f"Workflow version not found. Workflow ID: {workflow_id}.")+ else:+ workflow = WorkflowService.get_draft_workflow(app_model, session=session)+ if workflow is None:+ raise WorkflowNotFoundError("Missing draft workflow configuration, please check.")+ return workflow+@classmethoddef _append_workflow_export_data(cls,@@ -946,13 +959,7 @@ class AppDslService::param app_model: App instance:param workflow_id: Optional published workflow version to export"""- workflow_service = WorkflowService()- workflow = workflow_service.get_draft_workflow(app_model, workflow_id, session=session)- if not workflow:- if workflow_id:- raise WorkflowNotFoundError(f"Workflow version not found. Workflow ID: {workflow_id}.")- raise WorkflowNotFoundError("Missing draft workflow configuration, please check.")-+ workflow = cls._load_export_workflow(app_model, workflow_id=workflow_id, session=session)workflow_dict = workflow.to_dict(include_secret=include_secret)graph = workflow_dict.get("graph", {})reference_nodes: dict[str, dict[str, Any]] = {}diff --git a/api/services/app_scoped_end_user_query_service.py b/api/services/app_scoped_end_user_query_service.pyindex ab41d8a2ea5..006ecf28724 100644--- a/api/services/app_scoped_end_user_query_service.py+++ b/api/services/app_scoped_end_user_query_service.py@@ -2,7 +2,7 @@from typing import Protocol-from machinery.context import ServiceApiRequestContext+from machinery.context import AppRequestContextfrom services.entities.app_scoped_end_user_entities import AppScopedEndUserRecord@@ -18,7 +18,7 @@ class AppScopedEndUserQueryService:def __init__(self, *, end_users: AppScopedEndUserQuery) -> None:self._app_scoped_end_users = end_users- def get_by_id(self, context: ServiceApiRequestContext, end_user_id: str) -> AppScopedEndUserRecord:+ def get_by_id(self, context: AppRequestContext, end_user_id: str) -> AppScopedEndUserRecord:end_user = self._app_scoped_end_users.find_by_id(tenant_id=context.tenant_id,app_id=context.app_id,diff --git a/api/services/app_service.py b/api/services/app_service.pyindex 8203df815e9..979929e4066 100644--- a/api/services/app_service.py+++ b/api/services/app_service.py@@ -63,7 +63,6 @@ from services.entities.app_entities import (CreateAppParams,)from services.model_provider.service import ModelProviderService-from services.openapi.visibility import apply_openapi_gate, is_openapi_visiblefrom services.rbac import contracts as rbac_contractsfrom services.rbac_agent_access_service import initialize_agent_rbac_accessfrom services.system_feature_service import SystemFeatureService@@ -323,25 +322,6 @@ class AppService:"""return session.scalar(select(App).where(App.id == app_id, App.tenant_id == tenant_id))- @staticmethod- def get_visible_app_by_id(- app_id: str,- session: Session,- ) -> App | None:- app = session.get(App, app_id)- if not app or app.status != "normal" or not is_openapi_visible(app):- return None- return app-- @staticmethod- def find_visible_apps_by_ids(- app_ids: Sequence[str],- session: Session,- ) -> list[App]:- if not app_ids:- return []- return list(session.execute(apply_openapi_gate(select(App).where(App.id.in_(list(app_ids))))).scalars().all())-def get_paginate_apps(self,user_id: str,diff --git a/api/services/enterprise/app_permitted_service.py b/api/services/enterprise/app_permitted_service.pyindex 77d63469951..ce0f27915cd 100644--- a/api/services/enterprise/app_permitted_service.py+++ b/api/services/enterprise/app_permitted_service.py@@ -1,23 +1,15 @@from __future__ import annotationsimport logging-from dataclasses import dataclass--from werkzeug.exceptions import ServiceUnavailablefrom services.enterprise.enterprise_service import EnterpriseService+from services.entities.app_entities import PermittedAppsPage+from services.errors.app import PermittedAppsUnavailableErrorfrom services.errors.enterprise import EnterpriseAPIErrorlogger = logging.getLogger(__name__)-@dataclass(frozen=True, slots=True)-class PermittedAppsPage:- app_ids: list[str]- total: int- has_more: bool--def list_permitted_apps(*,page: int,@@ -35,7 +27,7 @@ def list_permitted_apps(getattr(exc, "status_code", None),str(exc),)- raise ServiceUnavailable("permitted_apps_unavailable") from exc+ raise PermittedAppsUnavailableError("permitted_apps_unavailable") from excreturn PermittedAppsPage(app_ids=[row["appId"] for row in body.get("data", [])],diff --git a/api/services/entities/app_entities.py b/api/services/entities/app_entities.pyindex f77ba9cbcb3..f67fa47a1e5 100644--- a/api/services/entities/app_entities.py+++ b/api/services/entities/app_entities.py@@ -2,7 +2,8 @@from dataclasses import dataclass, fieldfrom datetime import datetime-from typing import Any, Literal, NotRequired, TypedDict+from enum import StrEnum+from typing import Any, Final, Literal, NotRequired, TypedDictfrom uuid import UUIDfrom pydantic import BaseModel, Field@@ -10,6 +11,30 @@ from pydantic import BaseModel, Fieldfrom models.model import AppMode, IconTypefrom services.entities.dsl_entities import DslImportWarning++class SupportedAppType(StrEnum):+ """App types the ``app`` usage face (``get app``) lists and filters.++ A curated subset of :class:`AppMode`: the real, user-facing app categories.+ Excludes runtime-only mode tags that are not standalone apps+ (``rag-pipeline`` is a knowledge ``Pipeline``; ``channel`` is unused) and the+ roster-owned ``agent`` type (surfaced through the roster, not this list).++ Members reference ``AppMode.*.value`` so the subset relationship is+ type-checked: dropping a member from ``AppMode`` breaks this at import.+ This is the single source for the listable set — params, filters, and the+ generated CLI whitelist all derive from it.+ """++ COMPLETION = AppMode.COMPLETION.value+ CHAT = AppMode.CHAT.value+ ADVANCED_CHAT = AppMode.ADVANCED_CHAT.value+ WORKFLOW = AppMode.WORKFLOW.value+ AGENT_CHAT = AppMode.AGENT_CHAT.value+++SUPPORTED_APP_TYPES: Final[tuple[AppMode, ...]] = tuple(AppMode(t.value) for t in SupportedAppType)+AppListSortBy = Literal["last_modified", "recently_created", "earliest_created"]RecentAppMode = Literal[AppMode.COMPLETION,@@ -68,6 +93,13 @@ class AppSummary:maintainer: str | None+@dataclass(frozen=True, slots=True)+class PermittedAppsPage:+ app_ids: list[str]+ total: int+ has_more: bool++@dataclass(frozen=True)class RecentAppListItem:id: strdiff --git a/api/services/errors/app.py b/api/services/errors/app.pyindex 74c29b0857d..d84b36b2ae5 100644--- a/api/services/errors/app.py+++ b/api/services/errors/app.py@@ -1,3 +1,11 @@+class AppDiscoveryNotFoundError(Exception):+ pass+++class PermittedAppsUnavailableError(Exception):+ pass++class MoreLikeThisDisabledError(Exception):passdiff --git a/api/services/knowledge/datasets/adapters.py b/api/services/knowledge/datasets/adapters.pyindex 985373cbba3..8a4645e986b 100644--- a/api/services/knowledge/datasets/adapters.py+++ b/api/services/knowledge/datasets/adapters.py@@ -16,7 +16,7 @@ from models import Account, Dataset, Documentfrom models.dataset import DatasetPermission, DatasetPermissionEnumfrom models.provider_ids import ModelProviderIDfrom repositories.knowledge.dataset_repository import _get_dataset-from services.app.query_service import AppQueryService+from services.app.query_service import RelatedAppsfrom services.enterprise import rbac_servicefrom services.errors.base import NoPermissionErrorfrom services.knowledge.dataset_access import DatasetAccessDeniedError, DatasetNotFoundError@@ -86,7 +86,7 @@ class SQLAlchemyDatasetOperations:*,session_factory: sessionmaker[Session],tags: TagTargetQuery,- app_queries: AppQueryService,+ app_queries: RelatedApps,members: MemberService,) -> None:self._sessions = session_factorydiff --git a/api/services/openapi/visibility.py b/api/services/openapi/visibility.pyindex ed665a768f9..281cf888653 100644--- a/api/services/openapi/visibility.py+++ b/api/services/openapi/visibility.py@@ -22,11 +22,3 @@ def apply_openapi_gate(query: Any) -> Any:(alias of ``.where``)."""return query.filter(App.enable_api.is_(True))---def is_openapi_visible(app: App) -> bool:- """Per-row counterpart for code paths that fetch an App by primary key- (``session.get`` / ``session.scalar``) and need the same visibility check- the query gate would have applied.- """- return bool(app.enable_api)diff --git a/api/services/workflow_service.py b/api/services/workflow_service.pyindex cd96e60caae..9404b34c4c9 100644--- a/api/services/workflow_service.py+++ b/api/services/workflow_service.py@@ -243,19 +243,16 @@ class WorkflowService:)return session.execute(stmt).scalar_one()- def get_draft_workflow(- self, app_model: App, workflow_id: str | None = None, *, session: Session- ) -> Workflow | None:+ @staticmethod+ def get_draft_workflow(app_model: App, *, session: Session) -> Workflow | None:"""- Get draft workflow+ Return the app's draft workflow, or None if no draft exists.Reuses the caller's active session so workflow reads stay in the same- transaction as the surrounding request or task.+ transaction as the surrounding request or task. No service construction+ or Flask database binding is needed for this read."""- if workflow_id:- return self.get_published_workflow_by_id(app_model, workflow_id, session=session)- # fetch draft workflow by app_model- workflow = session.scalar(+ return session.scalar(select(Workflow).where(Workflow.tenant_id == app_model.tenant_id,@@ -265,9 +262,6 @@ class WorkflowService:.limit(1))- # return draft workflow- return workflow-def _get_draft_workflow_for_update(self, app_model: App, *, session: Session) -> Workflow | None:"""Return the app draft while holding its row lock for the caller's transaction."""return session.scalar(@@ -281,8 +275,8 @@ class WorkflowService:.with_for_update())+ @staticmethoddef get_published_workflow_by_id(- self,app_model: App,workflow_id: str,*,diff --git a/api/tests/test_containers_integration_tests/controllers/openapi/test_app_dsl.py b/api/tests/test_containers_integration_tests/controllers/openapi/test_app_dsl.pyindex 8764a860a86..89848a00a56 100644--- a/api/tests/test_containers_integration_tests/controllers/openapi/test_app_dsl.py+++ b/api/tests/test_containers_integration_tests/controllers/openapi/test_app_dsl.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport jsonfrom collections.abc import Callable, Generator+from typing import Protocol, castfrom unittest.mock import patchfrom uuid import uuid4@@ -11,25 +12,29 @@ from faker import Fakerfrom flask import Flaskfrom sqlalchemy.orm import Session-from controllers.openapi._models import AppDslExportQuery, AppDslImportPayload+from controllers.common.errors import NotFoundError+from controllers.openapi._models import AppDslExportQuery, AppDslExportResponse, AppDslImportPayloadfrom controllers.openapi.app_dsl import (AppDslCheckDependenciesApi,AppDslExportApi,AppDslImportApi,AppDslImportConfirmApi,)-from controllers.openapi.auth.requirements import CheckWorkspaceMember-from machinery.context import RequestContext+from machinery.context import AppRequestContext, RequestContextfrom models import Account, App-from models.model import AppModelConfig+from models.model import AppMode, AppModelConfigfrom services.app_dsl_service import CURRENT_DSL_VERSIONfrom services.app_service import AppService, CreateAppParams-from services.entities.dsl_entities import ImportStatus-from tests.test_containers_integration_tests.controllers.openapi.conftest import context_for+from services.entities.dsl_entities import CheckDependenciesResult, Import, ImportStatus+from services.errors.app import WorkflowNotFoundErrorfrom tests.test_containers_integration_tests.helpers import accounts as account_fixturesfrom tests.test_containers_integration_tests.helpers import generate_valid_password+class _Endpoint[T](Protocol):+ __handler__: Callable[..., T]++def _workflow_yaml(*, version: str = CURRENT_DSL_VERSION, name: str = "My App") -> str:return yaml.safe_dump({@@ -55,6 +60,8 @@ def external_deps() -> Generator[dict[str, object]]:patch("services.app_service.SystemFeatureService") as mock_feature_service,patch("services.app_service.EnterpriseService") as mock_enterprise_service,):+ mock_workflow_service.get_draft_workflow.return_value = None+ mock_workflow_service.get_published_workflow_by_id.return_value = Nonemock_workflow_service.return_value.get_draft_workflow.return_value = Nonemock_workflow_service.return_value.sync_draft_workflow.return_value = Nonemock_dependencies_service.generate_latest_dependencies.return_value = [] # type: ignore[assignment]@@ -112,7 +119,7 @@ class TestDslImport:api = AppDslImportApi()body = AppDslImportPayload(mode="yaml-content", yaml_content="[]") # not a mappingwith app.test_request_context(f"/openapi/v1/workspaces/{tenant.id}/apps/imports", method="POST"):- result, code = api.post.__handler__(+ result, code = cast(_Endpoint[tuple[Import, int]], api.post).__handler__(api,RequestContext("test-request", None, account.id, tenant.id),tenant.id,@@ -134,7 +141,7 @@ class TestDslImport:api = AppDslImportApi()body = AppDslImportPayload(mode="yaml-content", yaml_content=_workflow_yaml(version="99.0.0"))with app.test_request_context(f"/openapi/v1/workspaces/{tenant.id}/apps/imports", method="POST"):- result, code = api.post.__handler__(+ result, code = cast(_Endpoint[tuple[Import, int]], api.post).__handler__(api,RequestContext("test-request", None, account.id, tenant.id),tenant.id,@@ -159,7 +166,7 @@ class TestDslImport:api = AppDslImportApi()body = AppDslImportPayload(mode="yaml-content", yaml_content=_workflow_yaml(name="Imported"))with app.test_request_context(f"/openapi/v1/workspaces/{tenant.id}/apps/imports", method="POST"):- result, code = api.post.__handler__(+ result, code = cast(_Endpoint[tuple[Import, int]], api.post).__handler__(api,RequestContext("test-request", None, account.id, tenant.id),tenant.id,@@ -185,7 +192,7 @@ class TestDslImportConfirm:with app.test_request_context(f"/openapi/v1/workspaces/{tenant.id}/apps/imports/{import_id}:confirm", method="POST"):- result, code = api.post.__handler__(+ result, code = cast(_Endpoint[tuple[Import, int]], api.post).__handler__(api,RequestContext("test-request", None, account.id, tenant.id),tenant.id,@@ -218,46 +225,48 @@ class TestDslExport:api = AppDslExportApi()with app.test_request_context(f"/openapi/v1/apps/{app_model.id}/dsl"):- response, code = api.get.__handler__(+ response, code = cast(_Endpoint[tuple[AppDslExportResponse, int]], api.get).__handler__(api,- context_for(- account,- session=db_session_with_containers,- view_args={"app_id": app_model.id},- requirements=(CheckWorkspaceMember(),),- ),+ AppRequestContext(tenant_id=app_model.tenant_id, app_id=app_model.id),app_model.id,query=AppDslExportQuery(),)assert code == 200+ assert isinstance(response, AppDslExportResponse)parsed = yaml.safe_load(response.data)assert parsed["kind"] == "app"assert parsed["app"]["name"] == app_model.namedef test_export_workflow_app_without_draft_maps_to_404(- self, app: Flask, db_session_with_containers: Session, external_deps: dict[str, object]+ self, app: Flask, db_session_with_containers: Session) -> None:"""A workflow app with no draft workflow can't be exported → the serviceraises WorkflowNotFoundError, which the controller maps to 404."""- app_model, account = _app_and_account(db_session_with_containers, mode="workflow")+ app_model = App(+ id=str(uuid4()),+ tenant_id=str(uuid4()),+ name="Workflow without draft",+ mode=AppMode.WORKFLOW,+ enable_api=True,+ enable_site=False,+ )+ db_session_with_containers.add(app_model)+ db_session_with_containers.commit()api = AppDslExportApi()- with app.test_request_context(f"/openapi/v1/apps/{app_model.id}/dsl"):- result, code = api.get.__handler__(+ with (+ app.test_request_context(f"/openapi/v1/apps/{app_model.id}/dsl"),+ pytest.raises(NotFoundError, match="Missing draft workflow configuration") as exc_info,+ ):+ cast(_Endpoint[tuple[AppDslExportResponse, int]], api.get).__handler__(api,- context_for(- account,- session=db_session_with_containers,- view_args={"app_id": app_model.id},- requirements=(CheckWorkspaceMember(),),- ),+ AppRequestContext(tenant_id=app_model.tenant_id, app_id=app_model.id),app_model.id,query=AppDslExportQuery(),)- assert code == 404- assert isinstance(result, str)+ assert isinstance(exc_info.value.__cause__, WorkflowNotFoundError)class TestDslCheckDependencies:@@ -268,7 +277,7 @@ class TestDslCheckDependencies:api = AppDslCheckDependenciesApi()with app.test_request_context(f"/openapi/v1/apps/{app_model.id}/dependencies:check"):- result, code = api.get.__handler__(+ result, code = cast(_Endpoint[tuple[CheckDependenciesResult, int]], api.get).__handler__(api,RequestContext("test-request", None, account.id, app_model.tenant_id),app_model.id,diff --git a/api/tests/test_containers_integration_tests/controllers/openapi/test_apps.py b/api/tests/test_containers_integration_tests/controllers/openapi/test_apps.pyindex 959c9fadb0c..e1f4559c240 100644--- a/api/tests/test_containers_integration_tests/controllers/openapi/test_apps.py+++ b/api/tests/test_containers_integration_tests/controllers/openapi/test_apps.py@@ -1,6 +1,7 @@from __future__ import annotationsfrom collections.abc import Callable+from typing import Protocol, castfrom uuid import uuid4import pytest@@ -8,11 +9,15 @@ from flask import Flaskfrom sqlalchemy.orm import Sessionfrom werkzeug.exceptions import NotFound-from controllers.openapi._models import AppDescribeQuery, AppListQuery+from controllers.openapi._models import AppDescribeQuery, AppDescribeResponse, AppListQuery, AppListResponsefrom controllers.openapi.apps import AppDescribeApi, AppListApi+from machinery.context import AppRequestContext, RequestContextfrom models import Account, Appfrom services.app_service import AppService, CreateAppParams-from tests.test_containers_integration_tests.controllers.openapi.conftest import context_for+++class _Endpoint[T](Protocol):+ __handler__: Callable[..., T]def _create_app(@@ -60,9 +65,9 @@ class TestAppList:api = AppListApi()with app.test_request_context(f"/openapi/v1/apps?workspace_id={tenant.id}"):- result = api.get.__handler__(+ result = cast(_Endpoint[AppListResponse], api.get).__handler__(api,- context_for(account, session=db_session_with_containers),+ RequestContext("request", None, account.id, tenant.id),query=AppListQuery(workspace_id=str(tenant.id)),)@@ -82,9 +87,9 @@ class TestAppList:api = AppListApi()with app.test_request_context(f"/openapi/v1/apps?workspace_id={tenant.id}&name={target.id}"):- result = api.get.__handler__(+ result = cast(_Endpoint[AppListResponse], api.get).__handler__(api,- context_for(account, session=db_session_with_containers),+ RequestContext("request", None, account.id, tenant.id),query=AppListQuery(workspace_id=str(tenant.id), name=str(target.id)),)@@ -105,9 +110,9 @@ class TestAppList:api = AppListApi()with app.test_request_context(f"/openapi/v1/apps?workspace_id={outsider_tenant.id}&name={foreign_app.id}"):- result = api.get.__handler__(+ result = cast(_Endpoint[AppListResponse], api.get).__handler__(api,- context_for(outsider, session=db_session_with_containers),+ RequestContext("request", None, outsider.id, outsider_tenant.id),query=AppListQuery(workspace_id=str(outsider_tenant.id), name=str(foreign_app.id)),)@@ -124,9 +129,9 @@ class TestAppDescribe:api = AppDescribeApi()with app.test_request_context(f"/openapi/v1/apps/{app_model.id}?fields=info"):- result = api.get.__handler__(+ result = cast(_Endpoint[AppDescribeResponse], api.get).__handler__(api,- context_for(account, session=db_session_with_containers, view_args={"app_id": app_model.id}),+ AppRequestContext(tenant_id=app_model.tenant_id, app_id=app_model.id),app_model.id,query=AppDescribeQuery(fields="info"),)@@ -139,18 +144,18 @@ class TestAppDescribe:assert result.parameters is Noneassert result.input_schema is None- def test_describe_unknown_app_is_404(- self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]- ) -> None:+ def test_describe_unknown_app_is_404(self, app: Flask, make_account: Callable[..., Account]) -> None:account = make_account()+ tenant = account.current_tenant+ assert tenant is not Nonemissing_id = str(uuid4())api = AppDescribeApi()with app.test_request_context(f"/openapi/v1/apps/{missing_id}"):with pytest.raises(NotFound):- api.get.__handler__(+ cast(_Endpoint[AppDescribeResponse], api.get).__handler__(api,- context_for(account, session=db_session_with_containers, view_args={"app_id": missing_id}),+ AppRequestContext(tenant_id=tenant.id, app_id=missing_id),missing_id,query=AppDescribeQuery(),)diff --git a/api/tests/test_containers_integration_tests/services/test_app_dsl_service.py b/api/tests/test_containers_integration_tests/services/test_app_dsl_service.pyindex 786d0659370..8c0a0366fed 100644--- a/api/tests/test_containers_integration_tests/services/test_app_dsl_service.py+++ b/api/tests/test_containers_integration_tests/services/test_app_dsl_service.py@@ -125,6 +125,8 @@ class TestAppDslService:patch("services.app_service.SystemFeatureService") as mock_feature_service,patch("services.app_service.EnterpriseService") as mock_enterprise_service,):+ mock_workflow_service.get_draft_workflow.return_value = None+ mock_workflow_service.get_published_workflow_by_id.return_value = Nonemock_workflow_service.return_value.get_draft_workflow.return_value = Nonemock_workflow_service.return_value.sync_draft_workflow.return_value = MagicMock()mock_dependencies_service.generate_latest_dependencies.return_value = []@@ -1272,9 +1274,7 @@ class TestAppDslService:"environment_variables": [],"conversation_variables": [],}- mock_external_service_dependencies[- "workflow_service"- ].return_value.get_draft_workflow.return_value = mock_workflow+ mock_external_service_dependencies["workflow_service"].get_draft_workflow.return_value = mock_workflowexported_dsl = AppDslService.export_dsl(app, include_secret=False, session=db_session_with_containers)exported_data = yaml.safe_load(exported_dsl)@@ -1310,20 +1310,17 @@ class TestAppDslService:workflow_id = str(uuid4())- def mock_get_draft_workflow(app_model, wf_id=None, **_kwargs):- if wf_id == workflow_id:- return mock_workflow- return None-- mock_external_service_dependencies[- "workflow_service"- ].return_value.get_draft_workflow.side_effect = mock_get_draft_workflow+ workflow_service = mock_external_service_dependencies["workflow_service"]+ workflow_service.get_published_workflow_by_id.return_value = mock_workflowexported_dsl = AppDslService.export_dsl(app, include_secret=False, workflow_id=workflow_id, session=db_session_with_containers)exported_data = yaml.safe_load(exported_dsl)+ workflow_service.get_published_workflow_by_id.assert_called_once_with(+ app, workflow_id, session=db_session_with_containers+ )assert exported_data["kind"] == "app"assert "workflow" in exported_data@@ -1334,7 +1331,7 @@ class TestAppDslService:app.mode = "workflow"db_session_with_containers.commit()- mock_external_service_dependencies["workflow_service"].return_value.get_draft_workflow.return_value = None+ mock_external_service_dependencies["workflow_service"].get_published_workflow_by_id.return_value = Nonewith pytest.raises(WorkflowNotFoundError,@@ -1394,9 +1391,7 @@ class TestAppDslService:}workflow = SimpleNamespace(to_dict=lambda *, include_secret: workflow_dict)- workflow_service = MagicMock()- workflow_service.get_draft_workflow.return_value = workflow- monkeypatch.setattr(app_dsl_service, "WorkflowService", lambda: workflow_service)+ monkeypatch.setattr(app_dsl_service.WorkflowService, "get_draft_workflow", MagicMock(return_value=workflow))monkeypatch.setattr(AppDslService,@@ -1435,13 +1430,7 @@ class TestAppDslService:assert nodes[5]["data"]["subscription_id"] == ""assert dependencies == ["dep-1"]- def test_append_workflow_export_data_missing_workflow_raises(- self, monkeypatch: pytest.MonkeyPatch, db_session_with_containers: Session- ):- workflow_service = MagicMock()- workflow_service.get_draft_workflow.return_value = None- monkeypatch.setattr(app_dsl_service, "WorkflowService", lambda: workflow_service)-+ def test_append_workflow_export_data_missing_workflow_raises(self, db_session_with_containers: Session):with pytest.raises(WorkflowNotFoundError, match="Missing draft workflow configuration"):AppDslService._append_workflow_export_data(export_data={},diff --git a/api/tests/unit_tests/controllers/common/test_app_access.py b/api/tests/unit_tests/controllers/common/test_app_access.pyindex 8ffd9dc4de8..2caae866da5 100644--- a/api/tests/unit_tests/controllers/common/test_app_access.py+++ b/api/tests/unit_tests/controllers/common/test_app_access.py@@ -7,6 +7,7 @@ import pytestfrom services.app.access import (APP_LIST_PERMISSION_KEYS,AppAccessFilter,+ app_access_filter_from_permissions,has_app_list_permission,resolve_app_access_filter,)@@ -104,28 +105,27 @@ class TestResolveAppAccessFilter:lambda tenant_id, account_id: whitelist,)- def test_default_preview_is_unrestricted(self, monkeypatch: pytest.MonkeyPatch):- self._patch_whitelist(monkeypatch, ResourceWhitelistResources(unrestricted=True))+ def test_default_preview_is_unrestricted(self):permissions = _permissions(app_default_keys=["app.preview"])- flt = resolve_app_access_filter("tenant-1", "acc-1", permissions=permissions)+ flt = app_access_filter_from_permissions(permissions, ResourceWhitelistResources(unrestricted=True))assert flt.accessible_app_ids is Noneassert flt.can_manage_own_apps is False- def test_restricted_whitelist_overrides_default_preview(self, monkeypatch: pytest.MonkeyPatch):- self._patch_whitelist(monkeypatch, ResourceWhitelistResources(unrestricted=False, resource_ids=["app-9"]))+ def test_restricted_whitelist_overrides_default_preview(self):permissions = _permissions(workspace_keys=["app.full_access", "app.create_and_management"],)- flt = resolve_app_access_filter("tenant-1", "acc-1", permissions=permissions)+ flt = app_access_filter_from_permissions(+ permissions, ResourceWhitelistResources(unrestricted=False, resource_ids=["app-9"])+ )assert flt.accessible_app_ids == {"app-9"}assert flt.can_manage_own_apps is False- def test_override_apps_collected_without_default_preview(self, monkeypatch: pytest.MonkeyPatch):- self._patch_whitelist(monkeypatch, ResourceWhitelistResources(unrestricted=True))+ def test_override_apps_collected_without_default_preview(self):permissions = _permissions(app_overrides=[ResourcePermissionKeys(resource_id="app-1", permission_keys=["app.preview"]),@@ -133,17 +133,18 @@ class TestResolveAppAccessFilter:],)- flt = resolve_app_access_filter("tenant-1", "acc-1", permissions=permissions)+ flt = app_access_filter_from_permissions(permissions, ResourceWhitelistResources(unrestricted=True))assert flt.accessible_app_ids == {"app-1"}- def test_restricted_whitelist_ignores_override_apps(self, monkeypatch: pytest.MonkeyPatch):- self._patch_whitelist(monkeypatch, ResourceWhitelistResources(unrestricted=False, resource_ids=["app-5"]))+ def test_restricted_whitelist_ignores_override_apps(self):permissions = _permissions(app_overrides=[ResourcePermissionKeys(resource_id="app-1", permission_keys=["app.acl.preview"])],)- flt = resolve_app_access_filter("tenant-1", "acc-1", permissions=permissions)+ flt = app_access_filter_from_permissions(+ permissions, ResourceWhitelistResources(unrestricted=False, resource_ids=["app-5"])+ )assert flt.accessible_app_ids == {"app-5"}diff --git a/api/tests/unit_tests/controllers/conftest.py b/api/tests/unit_tests/controllers/conftest.pyindex b8b3ef73415..2d5c5004350 100644--- a/api/tests/unit_tests/controllers/conftest.py+++ b/api/tests/unit_tests/controllers/conftest.py@@ -16,11 +16,11 @@ from extensions.ext_application_services import (_batch_get_enterprise_webapp_access_modes,_batch_get_enterprise_webapp_user_permissions,)-from repositories.app.console_repository import ConsoleAppRepositoryfrom repositories.webapp_access_query_repository import WebAppAccessQueryRepositoryfrom services.app.console_service import ConsoleAppService+from services.app.export_service import AppExportServicefrom services.app.import_service import AppImportService-from services.app.query_service import AppQueryService+from services.app.query_service import AppDiscoveryServicefrom services.credentials.query import CredentialQueryfrom services.data_source.provider_service import DatasourceProviderServicefrom services.enterprise.enterprise_service import EnterpriseService@@ -90,7 +90,8 @@ def pipeline_application(monkeypatch: pytest.MonkeyPatch) -> PipelineGenerator:class AppQueryTestServices:console: ConsoleAppServiceimports: AppImportService- queries: AppQueryService+ exports: AppExportService+ discovery: AppDiscoveryService@dataclass(frozen=True)@@ -108,13 +109,13 @@ def app_query_services(sqlite_session_factory: sessionmaker[Session],monkeypatch: pytest.MonkeyPatch,) -> ControllerTestServices:- repository = ConsoleAppRepository(session_factory=sqlite_session_factory)services = ControllerTestServices(tags=application_tags,apps=AppQueryTestServices(console=app_services.console,imports=app_services.imports,- queries=AppQueryService(apps=repository),+ exports=app_services.exports,+ discovery=app_services.discovery,),webapp_access=WebAppAccessQueryService(access=WebAppAccessQueryRepository(session_factory=sqlite_session_factory),diff --git a/api/tests/unit_tests/controllers/inner_api/app/test_dsl.py b/api/tests/unit_tests/controllers/inner_api/app/test_dsl.pyindex f7f33f0ef7c..0b86a7167cb 100644--- a/api/tests/unit_tests/controllers/inner_api/app/test_dsl.py+++ b/api/tests/unit_tests/controllers/inner_api/app/test_dsl.py@@ -5,48 +5,36 @@ in test_auth_wraps.py; handler tests use inspect.unwrap() to bypass them."""import inspect-from types import SimpleNamespace+from typing import Protocol, castfrom unittest.mock import patch-from uuid import uuid4import pytestfrom flask import Flaskfrom pydantic import ValidationErrorfrom sqlalchemy import eventfrom sqlalchemy.engine import Engine-from sqlalchemy.orm import Session, scoped_session, sessionmaker+from sqlalchemy.orm import Sessionfrom werkzeug.exceptions import UnprocessableEntity-from controllers.inner_api.app import dsl as dsl_modulefrom controllers.inner_api.app.dsl import (EnterpriseAppDSLExport,EnterpriseAppDSLImport,InnerAppDSLImportPayload,)+from controllers.inner_api.wraps import InnerApiUnauthorizedErrorfrom models import Account, App, Tenant, TenantAccountJoinfrom models.account import AccountStatus, TenantAccountRole-from models.model import AppMode, IconType+from models.model import AppModefrom services.app_dsl_service import AppDslService+from services.entities.app_entities import AppExportOptionsfrom services.entities.dsl_entities import Import, ImportStatus-from services.errors.app import IsDraftWorkflowError, WorkflowNotFoundError+from services.errors.app import AppDiscoveryNotFoundError, IsDraftWorkflowError, WorkflowNotFoundErrorfrom tests.unit_tests.config_override import config_overrides_context+from tests.unit_tests.controllers.conftest import ControllerTestServices-def _persist_app(session: Session) -> App:- app = App(- id=str(uuid4()),- tenant_id=str(uuid4()),- name="DSL App",- mode=AppMode.WORKFLOW,- icon_type=IconType.EMOJI,- icon="robot",- icon_background="#ffffff",- enable_site=False,- enable_api=False,- )- session.add(app)- session.commit()- return app+class DocumentedView(Protocol):+ __apidoc__: dict[str, dict[str, dict[str, object]]]def _persist_account(session: Session, *, workspace_id: str = "ws-123") -> Account:@@ -70,7 +58,7 @@ def _persist_account(session: Session, *, workspace_id: str = "ws-123") -> Accouclass TestInnerAppDSLImportPayload:"""Test InnerAppDSLImportPayload Pydantic model validation."""- def test_valid_payload_all_fields(self):+ def test_valid_payload_all_fields(self) -> None:data = {"yaml_content": "version: 0.6.0\nkind: app\n","creator_email": "[email protected]",@@ -83,7 +71,7 @@ class TestInnerAppDSLImportPayload:assert payload.name == "My App"assert payload.description == "A test app"- def test_valid_payload_optional_fields_omitted(self):+ def test_valid_payload_optional_fields_omitted(self) -> None:data = {"yaml_content": "version: 0.6.0\n","creator_email": "[email protected]",@@ -92,12 +80,12 @@ class TestInnerAppDSLImportPayload:assert payload.name is Noneassert payload.description is None- def test_missing_yaml_content_fails(self):+ def test_missing_yaml_content_fails(self) -> None:with pytest.raises(ValidationError) as exc_info:InnerAppDSLImportPayload.model_validate({"creator_email": "[email protected]"})assert "yaml_content" in str(exc_info.value)- def test_missing_creator_email_fails(self):+ def test_missing_creator_email_fails(self) -> None:with pytest.raises(ValidationError) as exc_info:InnerAppDSLImportPayload.model_validate({"yaml_content": "test"})assert "creator_email" in str(exc_info.value)@@ -124,7 +112,7 @@ class TestEnterpriseAppDSLImport:import_status: ImportStatus,http_status: int,transaction: str,- ):+ ) -> None:account = _persist_account(sqlite_session)account_id = account.idsqlite_session.close()@@ -168,9 +156,9 @@ class TestEnterpriseAppDSLImport:event.listen(target, name, callback)try:payload = InnerAppDSLImportPayload(yaml_content="version: 0.6.0\n", creator_email="[email protected]")- with app.test_request_context():+ with app.test_request_context(method="POST", json=payload.model_dump()):body, status = inspect.unwrap(EnterpriseAppDSLImport.post)(- EnterpriseAppDSLImport(), payload, workspace_id="ws-123"+ EnterpriseAppDSLImport(), workspace_id="ws-123")assert status == http_statusassert body["status"] == import_status@@ -186,7 +174,7 @@ class TestEnterpriseAppDSLImport:app: Flask,sqlite_session: Session,creator_email: str,- ):+ ) -> None:sqlite_session.add_all([Account(name="Banned", email="[email protected]", status=AccountStatus.BANNED),@@ -195,254 +183,105 @@ class TestEnterpriseAppDSLImport:)sqlite_session.commit()payload = InnerAppDSLImportPayload(yaml_content="test", creator_email=creator_email)- with app.test_request_context():- body, status = inspect.unwrap(EnterpriseAppDSLImport.post)(- EnterpriseAppDSLImport(), payload, workspace_id="ws-123"- )+ with app.test_request_context(method="POST", json=payload.model_dump()):+ body, status = inspect.unwrap(EnterpriseAppDSLImport.post)(EnterpriseAppDSLImport(), workspace_id="ws-123")assert status == 404- assert creator_email in body["message"]+ assert body == {"message": f"account '{creator_email}' not found or inactive"}class TestEnterpriseAppDSLExport:- """Test EnterpriseAppDSLExport endpoint handler logic.-- Uses inspect.unwrap() to bypass auth/setup decorators.- """-- def test_export_documents_query_parameters(self):- params = EnterpriseAppDSLExport.get.__apidoc__["params"]-+ def test_export_documents_query_parameters(self) -> None:+ params = cast(DocumentedView, EnterpriseAppDSLExport.get).__apidoc__["params"]assert params["include_secret"]["in"] == "query"- assert params["include_secret"]["type"] == "boolean"assert params["workflow_id"]["in"] == "query"- assert params["workflow_id"]["type"] == "string"assert params["workflow_id"]["format"] == "uuid"- @pytest.fixture- def api_instance(self):- return EnterpriseAppDSLExport()-- @pytest.fixture- def scoped_db(self, sqlite_session_factory: sessionmaker[Session]):- db_session = scoped_session(sqlite_session_factory)- with patch.object(dsl_module, "db", SimpleNamespace(session=db_session)):- yield db_session- db_session.remove()-- @patch("controllers.inner_api.app.dsl.AppDslService")- def test_export_success_returns_200(- self,- mock_dsl_cls,- api_instance,- app: Flask,- sqlite_session: Session,- scoped_db,- ):- app_model = _persist_app(sqlite_session)- mock_dsl_cls.export_dsl.return_value = "version: 0.6.0\nkind: app\n"-- unwrapped = inspect.unwrap(api_instance.get)- with app.test_request_context("?include_secret=false"):- result = unwrapped(api_instance, app_id=app_model.id)-- body, status_code = result- assert status_code == 200- assert body["data"] == "version: 0.6.0\nkind: app\n"- call_kwargs = mock_dsl_cls.export_dsl.call_args.kwargs- assert call_kwargs["app_model"].id == app_model.id- assert call_kwargs["session"] is scoped_db()- assert call_kwargs["include_secret"] is False-- @patch("controllers.inner_api.app.dsl.AppDslService")- def test_export_with_secret(- self,- mock_dsl_cls,- api_instance,- app: Flask,- sqlite_session: Session,- scoped_db,- ):- app_model = _persist_app(sqlite_session)- mock_dsl_cls.export_dsl.return_value = "yaml-data"-- unwrapped = inspect.unwrap(api_instance.get)- with app.test_request_context("?include_secret=true"):- result = unwrapped(api_instance, app_id=app_model.id)-- body, status_code = result- assert status_code == 200- call_kwargs = mock_dsl_cls.export_dsl.call_args.kwargs- assert call_kwargs["app_model"].id == app_model.id- assert call_kwargs["session"] is scoped_db()- assert call_kwargs["include_secret"] is True-- @patch("controllers.inner_api.app.dsl.AppDslService")- def test_export_selected_workflow_forwards_canonical_uuid(- self,- mock_dsl_cls,- api_instance,- app: Flask,- sqlite_session: Session,- scoped_db,- ):- app_model = _persist_app(sqlite_session)- mock_dsl_cls.export_dsl.return_value = "yaml-data"- workflow_id = "F1FD7266-56FC-45C7-9D81-A72CD5A1B4F6"-- unwrapped = inspect.unwrap(api_instance.get)- with app.test_request_context(f"?workflow_id={workflow_id}"):- body, status_code = unwrapped(api_instance, app_id=app_model.id)-- assert status_code == 200- assert body["data"] == "yaml-data"- call_kwargs = mock_dsl_cls.export_dsl.call_args.kwargs- assert call_kwargs["app_model"].id == app_model.id- assert call_kwargs["session"] is scoped_db()- assert call_kwargs["include_secret"] is False- assert call_kwargs["workflow_id"] == "f1fd7266-56fc-45c7-9d81-a72cd5a1b4f6"-- @patch("controllers.inner_api.app.dsl.AppDslService")- def test_export_selected_workflow_with_secret(- self,- mock_dsl_cls,- api_instance,- app: Flask,- sqlite_session: Session,- scoped_db,- ):- app_model = _persist_app(sqlite_session)- mock_dsl_cls.export_dsl.return_value = "yaml-data"- workflow_id = "f1fd7266-56fc-45c7-9d81-a72cd5a1b4f6"-- unwrapped = inspect.unwrap(api_instance.get)- with app.test_request_context(f"?include_secret=true&workflow_id={workflow_id}"):- body, status_code = unwrapped(api_instance, app_id=app_model.id)-- assert status_code == 200- assert body["data"] == "yaml-data"- call_kwargs = mock_dsl_cls.export_dsl.call_args.kwargs- assert call_kwargs["app_model"].id == app_model.id- assert call_kwargs["session"] is scoped_db()- assert call_kwargs["include_secret"] is True- assert call_kwargs["workflow_id"] == workflow_id-- @patch("controllers.inner_api.app.dsl.AppDslService")- def test_export_rejects_invalid_selected_workflow_id(+ @pytest.mark.parametrize(+ ("query", "secret", "workflow_id"),+ [+ ("", False, None),+ ("?include_secret=TRUE", True, None),+ ("?include_secret=1", False, None),+ ("?workflow_id=F1FD7266-56FC-45C7-9D81-A72CD5A1B4F6", False, "f1fd7266-56fc-45c7-9d81-a72cd5a1b4f6"),+ ],+ )+ def test_export_parses_options(self,- mock_dsl_cls,- api_instance,app: Flask,- scoped_db,- ):- assert scoped_db() is not None- unwrapped = inspect.unwrap(api_instance.get)- with app.test_request_context("?workflow_id=not-a-uuid"):- body, status_code = unwrapped(api_instance, app_id=str(uuid4()))-- assert status_code == 400- assert body == {- "code": "invalid_workflow_id",- "message": "workflow_id must be a valid UUID",- "status": 400,- }- mock_dsl_cls.export_dsl.assert_not_called()+ app_query_services: ControllerTestServices,+ monkeypatch: pytest.MonkeyPatch,+ query: str,+ secret: bool,+ workflow_id: str | None,+ ) -> None:+ calls: list[tuple[str, AppExportOptions]] = []++ def export(app_id: str, options: AppExportOptions) -> str:+ calls.append((app_id, options))+ return "yaml-data"++ monkeypatch.setattr(app_query_services.apps.exports, "export_for_inner", export)+ with app.test_request_context(query):+ result = inspect.unwrap(EnterpriseAppDSLExport.get)(EnterpriseAppDSLExport(), app_id="app-id")+ assert result == ({"data": "yaml-data"}, 200)+ assert calls == [("app-id", AppExportOptions(include_secret=secret, workflow_id=workflow_id))]- @patch("controllers.inner_api.app.dsl.AppDslService")- def test_export_selected_missing_workflow_returns_404(- self,- mock_dsl_cls,- api_instance,- app: Flask,- sqlite_session: Session,- scoped_db,- ):- app_model = _persist_app(sqlite_session)- mock_dsl_cls.export_dsl.side_effect = WorkflowNotFoundError("selected workflow not found")- workflow_id = "f1fd7266-56fc-45c7-9d81-a72cd5a1b4f6"-- unwrapped = inspect.unwrap(api_instance.get)- with app.test_request_context(f"?workflow_id={workflow_id}"):- body, status_code = unwrapped(api_instance, app_id=app_model.id)-- assert status_code == 404- assert body == {- "code": "workflow_version_not_found",- "message": "selected workflow not found",- "status": 404,- }- call_kwargs = mock_dsl_cls.export_dsl.call_args.kwargs- assert call_kwargs["app_model"].id == app_model.id- assert call_kwargs["session"] is scoped_db()- assert call_kwargs["include_secret"] is False- assert call_kwargs["workflow_id"] == workflow_id-- @patch("controllers.inner_api.app.dsl.AppDslService")- def test_export_selected_draft_workflow_returns_400(- self,- mock_dsl_cls,- api_instance,- app: Flask,- sqlite_session: Session,- scoped_db,- ):- app_model = _persist_app(sqlite_session)- mock_dsl_cls.export_dsl.side_effect = IsDraftWorkflowError("selected workflow is a draft")- workflow_id = "f1fd7266-56fc-45c7-9d81-a72cd5a1b4f6"-- unwrapped = inspect.unwrap(api_instance.get)- with app.test_request_context(f"?workflow_id={workflow_id}"):- body, status_code = unwrapped(api_instance, app_id=app_model.id)-- assert status_code == 400- assert body == {- "code": "workflow_version_not_published",- "message": "selected workflow is a draft",- "status": 400,- }- call_kwargs = mock_dsl_cls.export_dsl.call_args.kwargs- assert call_kwargs["app_model"].id == app_model.id- assert call_kwargs["session"] is scoped_db()- assert call_kwargs["include_secret"] is False- assert call_kwargs["workflow_id"] == workflow_id-- @patch("controllers.inner_api.app.dsl.AppDslService")- def test_export_without_selected_workflow_preserves_workflow_error(+ @pytest.mark.parametrize(+ ("error", "query", "expected"),+ [+ (AppDiscoveryNotFoundError(), "", ({"message": "app not found"}, 404)),+ (+ WorkflowNotFoundError("missing"),+ "?workflow_id=f1fd7266-56fc-45c7-9d81-a72cd5a1b4f6",+ ({"code": "workflow_version_not_found", "message": "missing", "status": 404}, 404),+ ),+ (+ IsDraftWorkflowError("draft"),+ "?workflow_id=f1fd7266-56fc-45c7-9d81-a72cd5a1b4f6",+ ({"code": "workflow_version_not_published", "message": "draft", "status": 400}, 400),+ ),+ ],+ )+ def test_export_maps_domain_errors(self,- mock_dsl_cls,- api_instance,app: Flask,- sqlite_session: Session,- scoped_db,- ):- app_model = _persist_app(sqlite_session)- mock_dsl_cls.export_dsl.side_effect = WorkflowNotFoundError(- "Missing draft workflow configuration, please check."+ app_query_services: ControllerTestServices,+ monkeypatch: pytest.MonkeyPatch,+ error: Exception,+ query: str,+ expected: tuple[dict[str, object], int],+ ) -> None:+ def export(*_args: object) -> str:+ raise error++ monkeypatch.setattr(app_query_services.apps.exports, "export_for_inner", export)+ with app.test_request_context(query):+ assert inspect.unwrap(EnterpriseAppDSLExport.get)(EnterpriseAppDSLExport(), app_id="app-id") == expected++ def test_invalid_workflow_id_is_rejected_before_service_lookup(self, app: Flask) -> None:+ with app.test_request_context("?workflow_id=invalid"):+ result = inspect.unwrap(EnterpriseAppDSLExport.get)(EnterpriseAppDSLExport(), app_id="app-id")+ assert result == (+ {"code": "invalid_workflow_id", "message": "workflow_id must be a valid UUID", "status": 400},+ 400,)- unwrapped = inspect.unwrap(api_instance.get)- with app.test_request_context():- with pytest.raises(WorkflowNotFoundError, match="Missing draft workflow configuration"):- unwrapped(api_instance, app_id=app_model.id)-- call_kwargs = mock_dsl_cls.export_dsl.call_args.kwargs- assert call_kwargs["app_model"].id == app_model.id- assert call_kwargs["session"] is scoped_db()- assert call_kwargs["include_secret"] is False- assert "workflow_id" not in call_kwargs-- def test_export_app_not_found_returns_404(self, api_instance, app: Flask, scoped_db):- assert scoped_db() is not None- unwrapped = inspect.unwrap(api_instance.get)- with app.test_request_context("?include_secret=false"):- result = unwrapped(api_instance, app_id=str(uuid4()))+ def test_default_draft_error_is_propagated(+ self,+ app: Flask,+ app_query_services: ControllerTestServices,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ def export(*_args: object) -> str:+ raise WorkflowNotFoundError("Missing draft workflow configuration")- body, status_code = result- assert status_code == 404- assert "app not found" in body["message"]+ monkeypatch.setattr(app_query_services.apps.exports, "export_for_inner", export)+ with app.test_request_context(), pytest.raises(WorkflowNotFoundError, match="Missing draft"):+ inspect.unwrap(EnterpriseAppDSLExport.get)(EnterpriseAppDSLExport(), app_id="app-id")-class TestModelValidateDecorator:- """The handler tests above unwrap the view, so this is what covers the decorator."""+class TestInnerAppAdmission:+ """Exercise admission and payload validation through the decorated entry point."""def test_invalid_body_is_rejected_before_the_handler_runs(self, app: Flask) -> None:api_instance = EnterpriseAppDSLImport()@@ -458,3 +297,44 @@ class TestModelValidateDecorator:pytest.raises(UnprocessableEntity),):api_instance.post(workspace_id="ws-123")++ def test_bad_key_is_rejected_before_body_validation(self, app: Flask, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("controllers.console.wraps._is_setup_completed", lambda: True)+ with (+ config_overrides_context(INNER_API=True, INNER_API_KEY="inner-api-key"),+ app.test_request_context(method="POST", json={}, headers={"X-Inner-Api-Key": "wrong-key"}),+ pytest.raises(InnerApiUnauthorizedError),+ ):+ EnterpriseAppDSLImport().post(workspace_id="ws-123")++ def test_admitted_import_passes_stable_metadata(+ self,+ app: Flask,+ app_query_services: ControllerTestServices,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ calls: list[dict[str, object]] = []++ def import_as_creator(**kwargs: object) -> Import:+ calls.append(kwargs)+ return Import(id="import-id", status=ImportStatus.COMPLETED)++ monkeypatch.setattr(app_query_services.apps.imports, "import_as_creator", import_as_creator)+ monkeypatch.setattr("controllers.console.wraps._is_setup_completed", lambda: True)+ monkeypatch.setattr("controllers.inner_api.app.dsl.get_request_id", lambda: "request-id")+ monkeypatch.setattr("controllers.inner_api.app.dsl.get_trace_id", lambda: "trace-id")+ with (+ config_overrides_context(INNER_API=True, INNER_API_KEY="inner-api-key"),+ app.test_request_context(+ method="POST",+ json={"yaml_content": "app: {}", "creator_email": "[email protected]"},+ headers={"X-Inner-Api-Key": "inner-api-key"},+ ),+ ):+ body, status = EnterpriseAppDSLImport().post(workspace_id="ws-123")+ assert status == 200+ assert body["status"] == ImportStatus.COMPLETED+ assert calls[0]["request_id"] == "request-id"+ assert calls[0]["trace_id"] == "trace-id"+ assert calls[0]["workspace_id"] == "ws-123"+ assert calls[0]["creator_email"] == "[email protected]"diff --git a/api/tests/unit_tests/controllers/openapi/auth/test_pipelines.py b/api/tests/unit_tests/controllers/openapi/auth/test_pipelines.pyindex 9e7bf73090c..156e9fb6f0c 100644--- a/api/tests/unit_tests/controllers/openapi/auth/test_pipelines.py+++ b/api/tests/unit_tests/controllers/openapi/auth/test_pipelines.py@@ -30,11 +30,11 @@ from controllers.openapi.auth.requirements import (Rank,Requirement,)-from controllers.openapi.auth.spec import CatalogMeta, EndpointSpec, Kind+from controllers.openapi.auth.spec import AdmissionContext, CatalogMeta, EndpointSpec, Kindfrom controllers.openapi.auth.subjects import _SUBJECT_CLASSES, AccountSubject, Subjectfrom enums import DeploymentEditionfrom libs.oauth_bearer import AuthContext, try_get_auth_ctx-from machinery.context import RequestContext+from machinery.context import AppRequestContext, RequestContextfrom services.app_service import AppServicefrom services.enterprise.enterprise_service import WebAppAccessMode@@ -265,12 +265,14 @@ def test_every_registrable_subject_has_a_pipeline() -> None:@pytest.mark.parametrize("handler_raises", [False, True])-def test_account_context_releases_admission_connection_before_handler([email protected]("context_kind", ["orm", "workspace", "app", None])+def test_context_injection_and_admission_session_lifetime(app: Flask,sqlite_session: Session,sqlite_engine: Engine,monkeypatch: pytest.MonkeyPatch,handler_raises: bool,+ context_kind: AdmissionContext | None,) -> None:persist(sqlite_session, make_app(), make_tenant(), make_account(), make_membership())monkeypatch.setattr(MOUNT, lambda _user: None)@@ -285,12 +287,23 @@ def test_account_context_releases_admission_connection_before_handler(def checkin(connection: object, *_args: object) -> None:connections.discard(connection)- def call(*, ctx: RequestContext) -> str:- assert isinstance(ctx, RequestContext)- assert (ctx.account_id, ctx.active_workspace_id) == (ACCOUNT_ID, TENANT_ID)+ def call(**kwargs: object) -> str:+ ctx = kwargs.get("ctx")+ if context_kind == "orm":+ assert isinstance(ctx, Context)+ assert ctx.app.id == APP_ID+ elif context_kind == "workspace":+ assert isinstance(ctx, RequestContext)+ assert (ctx.account_id, ctx.active_workspace_id) == (ACCOUNT_ID, TENANT_ID)+ assert (ctx.request_id, ctx.trace_id) == ("admission-request", "admission-trace")+ elif context_kind == "app":+ assert isinstance(ctx, AppRequestContext)+ assert (ctx.app_id, ctx.tenant_id) == (APP_ID, TENANT_ID)+ else:+ assert kwargs == {}assert checkouts- assert not connections- assert not sqlite_session.in_transaction()+ assert bool(connections) is (context_kind == "orm")+ assert sqlite_session.in_transaction() is (context_kind == "orm")assert try_get_auth_ctx() == subject.authif handler_raises:raise RuntimeError("import failed")@@ -300,15 +313,18 @@ def test_account_context_releases_admission_connection_before_handler(event.listen(sqlite_engine, "checkin", checkin)def run() -> str:+ ctx = make_ctx(sqlite_session, subject, app_id=APP_ID)+ ctx.request_id = "admission-request"+ ctx.trace_id = "admission-trace"return AccountPipeline().run(subject=subject,auth=subject.auth,spec=EndpointSpec(- account_context=True,+ context=context_kind,requirements=(CheckAppApiEnabled(), CheckWorkspaceMember()),- catalog=CatalogMeta(op="test.account_context", kind=Kind.OBJECT, summary="test"),+ catalog=CatalogMeta(op="test.context_injection", kind=Kind.OBJECT, summary="test"),),- ctx=make_ctx(sqlite_session, subject, app_id=APP_ID),+ ctx=ctx,session=sqlite_session,call=call,)@@ -320,6 +336,7 @@ def test_account_context_releases_admission_connection_before_handler(run()else:assert run() == "imported"+ sqlite_session.close()assert not connectionsassert try_get_auth_ctx() is Nonefinally:diff --git a/api/tests/unit_tests/controllers/openapi/auth/test_resource_access.py b/api/tests/unit_tests/controllers/openapi/auth/test_resource_access.pyindex 3c4f7d61473..5a9e1aea76b 100644--- a/api/tests/unit_tests/controllers/openapi/auth/test_resource_access.py+++ b/api/tests/unit_tests/controllers/openapi/auth/test_resource_access.py@@ -279,27 +279,33 @@ def test_stop_task_rejects_other_token_owner(resource_fixture: ResourceFixture)stop.assert_called_once_with("task")[email protected]("search_unbound", [False, True])[email protected]("search", ["list", "bound", "unbound"])[email protected]("empty_bindings", [False, True])def test_app_list_filters_unbound_apps_before_pagination(- resource_fixture: ResourceFixture, sqlite_session: Session, search_unbound: bool+ resource_fixture: ResourceFixture, sqlite_session: Session, search: str, empty_bindings: bool) -> None:- import inspect-- from controllers.openapi._models import AppListQueryfrom controllers.openapi.apps import AppListApi- flask_app, app_id, _, tenant_id, _ = resource_fixture+ flask_app, app_id, token_id, tenant_id, _ = resource_fixtureunbound = App(id=str(uuid4()), tenant_id=tenant_id, name="Unbound app", mode=AppMode.CHAT, enable_api=True, enable_site=False)sqlite_session.add(unbound)- sqlite_session.commit()- with flask_app.test_request_context("/"):- data = call(flask_app, workspace_id=tenant_id, scope=Scope.APPS_READ)- result = inspect.unwrap(AppListApi.get)(- AppListApi(),- data,- query=AppListQuery(workspace_id=tenant_id, name=unbound.id if search_unbound else None),+ if empty_bindings:+ sqlite_session.execute(+ delete(ResourceAccessTokenRelation).where(ResourceAccessTokenRelation.token_id == token_id))- assert result.total == (0 if search_unbound else 1)- assert [app.id for app in result.data] == ([] if search_unbound else [app_id])+ sqlite_session.commit()+ query = {"workspace_id": tenant_id}+ if search != "list":+ query["name"] = app_id if search == "bound" else unbound.id+ with flask_app.test_request_context(+ "/apps",+ query_string=query,+ headers={"Authorization": "Bearer sk-test", CATALOG_HEADER: catalog_for(flask_app)[1]},+ ):+ result, status = AppListApi().get()+ expected_ids: list[str] = [] if empty_bindings or search == "unbound" else [app_id]+ assert status == 200+ assert result["total"] == len(expected_ids)+ assert [app["id"] for app in result["data"]] == expected_idsdiff --git a/api/tests/unit_tests/controllers/openapi/conftest.py b/api/tests/unit_tests/controllers/openapi/conftest.pyindex 2dda092a989..03a4dcfdff9 100644--- a/api/tests/unit_tests/controllers/openapi/conftest.py+++ b/api/tests/unit_tests/controllers/openapi/conftest.py@@ -24,7 +24,7 @@ from models.model import AppMode, IconType@pytest.fixture-def openapi_app():+def openapi_app() -> Flask:# the real factory: flask-restx wire behaviour (404 route suggestions) is app configapp = create_flask_app_with_configs()app.config["TESTING"] = True@@ -33,7 +33,7 @@ def openapi_app():@pytest.fixture-def app():+def app() -> Flask:a = Flask(__name__)a.config["TESTING"] = Truereturn a@@ -127,12 +127,10 @@ def admitted_bearer(@pytest.fixture(autouse=True)def _account_services(monkeypatch: pytest.MonkeyPatch, account_application_services: ApplicationServices) -> None:- from controllers.openapi import apps, apps_permitted_external, workspaces+ from controllers.openapi import workspacesfrom controllers.openapi.auth import loaders, requirements, subjectsfor module in (- apps,- apps_permitted_external,workspaces,loaders,requirements,diff --git a/api/tests/unit_tests/controllers/openapi/test_app_describe_builder.py b/api/tests/unit_tests/controllers/openapi/test_app_describe_builder.pyindex 56602fe729d..2dae8ee13a4 100644--- a/api/tests/unit_tests/controllers/openapi/test_app_describe_builder.py+++ b/api/tests/unit_tests/controllers/openapi/test_app_describe_builder.py@@ -1,87 +1,55 @@from datetime import datetime-from sqlalchemy.orm import Session+import pytest+from controllers.openapi._app_response import _EMPTY_PARAMETERS, build_app_describe_responsefrom controllers.openapi._input_schema import EMPTY_INPUT_SCHEMA-from controllers.openapi.apps import _EMPTY_PARAMETERS, build_app_describe_response-from controllers.service_api.app.error import AppUnavailableError-from models.model import App, AppMode+from models.model import AppMode+from services.app.query_service import AppDescription+from services.app_definition_query_service import AppParameterConfig+from services.entities.app_entities import AppSummary-def _app() -> App:- app = App(- id="11111111-1111-1111-1111-111111111111",- tenant_id="tenant-1",- name="Demo",- mode=AppMode.CHAT,- description="d",- enable_api=True,+def description(config: AppParameterConfig | None) -> AppDescription:+ return AppDescription(+ AppSummary("app-id", "tenant-id", "Demo", "d", AppMode.CHAT, "normal", datetime(2026, 1, 1), "maintainer"),+ True,+ config,)- app.updated_at = datetime(2026, 1, 1)- return app-def test_fields_none_returns_all_blocks(monkeypatch, unbound_session: Session):- app = _app()- session = unbound_session- parameters_calls: list[tuple[App, Session]] = []- input_schema_calls: list[tuple[App, Session]] = []-- def parameters_payload(requested_app: App, *, session: Session):- parameters_calls.append((requested_app, session))- return {"k": "v"}-- def input_schema(requested_app: App, *, session: Session):- input_schema_calls.append((requested_app, session))- return {"s": 1}-- monkeypatch.setattr("controllers.openapi.apps.parameters_payload", parameters_payload)- monkeypatch.setattr("controllers.openapi.apps.build_input_schema", input_schema)- resp = build_app_describe_response(app, None, session=session)- assert resp.info is not None- assert resp.info.name == "Demo"- assert resp.parameters == {"k": "v"}- assert resp.input_schema == {"s": 1}- assert parameters_calls == [(app, session)]- assert input_schema_calls == [(app, session)]---def test_fields_subset_limits_blocks(monkeypatch, unbound_session: Session):- session = unbound_session- monkeypatch.setattr("controllers.openapi.apps.parameters_payload", lambda _app, **_kwargs: {"k": "v"})- monkeypatch.setattr("controllers.openapi.apps.build_input_schema", lambda _app, **_kwargs: {"s": 1})- resp = build_app_describe_response(_app(), ["info"], session=session)- assert resp.info is not None- assert resp.parameters is None- assert resp.input_schema is None---def test_info_omits_author_and_tags(monkeypatch, unbound_session: Session):- session = unbound_session- monkeypatch.setattr("controllers.openapi.apps.parameters_payload", lambda _app, **_kwargs: {})- monkeypatch.setattr("controllers.openapi.apps.build_input_schema", lambda _app, **_kwargs: {})- resp = build_app_describe_response(_app(), ["info"], session=session)- assert resp.info is not None- # Usage-face describe must not expose creator identity or tags (cross-tenant leak).- assert not hasattr(resp.info, "author")- assert not hasattr(resp.info, "tags")---def test_parameters_fallback_on_app_unavailable(monkeypatch, unbound_session: Session):- def _raise(app, *, session):- raise AppUnavailableError()-- monkeypatch.setattr("controllers.openapi.apps.parameters_payload", _raise)- monkeypatch.setattr("controllers.openapi.apps.build_input_schema", lambda _app, **_kwargs: {"s": 1})- resp = build_app_describe_response(_app(), ["parameters"], session=unbound_session)- assert resp.parameters == dict(_EMPTY_PARAMETERS)---def test_input_schema_fallback_on_app_unavailable(monkeypatch, unbound_session: Session):- def _raise(app, *, session):- raise AppUnavailableError()-- monkeypatch.setattr("controllers.openapi.apps.parameters_payload", lambda _app, **_kwargs: {"k": "v"})- monkeypatch.setattr("controllers.openapi.apps.build_input_schema", _raise)- resp = build_app_describe_response(_app(), ["input_schema"], session=unbound_session)- assert resp.input_schema == dict(EMPTY_INPUT_SCHEMA)+def test_full_description_projects_materialized_data_without_request_or_session() -> None:+ form = [{"text-input": {"variable": "industry", "label": "Industry", "required": True}}]+ response = build_app_describe_response(description(AppParameterConfig({}, form)), None)+ assert response.info is not None+ assert response.info.model_dump() == {+ "id": "app-id",+ "name": "Demo",+ "description": "d",+ "mode": "chat",+ "updated_at": "2026-01-01T00:00:00",+ "service_api_enabled": True,+ "is_agent": False,+ }+ assert response.parameters is not None+ assert response.parameters["user_input_form"] == form+ assert response.input_schema is not None+ assert response.input_schema["properties"]["inputs"]["required"] == ["industry"]++[email protected]("fields", [{"info"}, {"parameters"}, {"input_schema"}, set()])+def test_projection_honors_requested_fields_and_missing_config_fallbacks(fields: set[str]) -> None:+ response = build_app_describe_response(description(None), fields)+ assert (response.info is not None) == ("info" in fields)+ assert response.parameters == (_EMPTY_PARAMETERS if "parameters" in fields else None)+ assert response.input_schema == (EMPTY_INPUT_SCHEMA if "input_schema" in fields else None)+++def test_empty_parameters_preserve_public_response_contract() -> None:+ assert _EMPTY_PARAMETERS == {+ "opening_statement": None,+ "suggested_questions": [],+ "user_input_form": [],+ "file_upload": None,+ "system_parameters": {},+ }diff --git a/api/tests/unit_tests/controllers/openapi/test_app_discovery.py b/api/tests/unit_tests/controllers/openapi/test_app_discovery.pynew file mode 100644index 00000000000..d208b1be024--- /dev/null+++ b/api/tests/unit_tests/controllers/openapi/test_app_discovery.py@@ -0,0 +1,87 @@+"""Transport mappings over stable admitted contexts."""++from collections.abc import Callable+from typing import Protocol, cast++import pytest+from flask import Flask+from werkzeug.exceptions import NotFound, ServiceUnavailable++from controllers.openapi._models import (+ AppDescribeQuery,+ AppDescribeResponse,+ PermittedExternalAppsListQuery,+ PermittedExternalAppsListResponse,+)+from controllers.openapi.apps import AppDescribeApi+from controllers.openapi.apps_permitted_external import PermittedExternalAppDescribeApi, PermittedExternalAppsListApi+from machinery.context import AppRequestContext+from models.model import AppMode+from services.app.query_service import AppDescription+from services.entities.app_entities import AppSummary+from services.errors.app import AppDiscoveryNotFoundError, PermittedAppsUnavailableError+from tests.unit_tests.controllers.conftest import ControllerTestServices+++class Endpoint[T](Protocol):+ __handler__: Callable[..., T]++[email protected]("api", [AppDescribeApi(), PermittedExternalAppDescribeApi()])+def test_describe_passes_admitted_scope_and_projects_response(+ app: Flask,+ app_query_services: ControllerTestServices,+ monkeypatch: pytest.MonkeyPatch,+ api: AppDescribeApi | PermittedExternalAppDescribeApi,+) -> None:+ context = AppRequestContext(tenant_id="workspace-id", app_id="app-id")+ calls: list[tuple[AppRequestContext, set[str] | None]] = []++ def describe(ctx: AppRequestContext, fields: set[str] | None) -> AppDescription:+ calls.append((ctx, fields))+ return AppDescription(+ AppSummary("app-id", "workspace-id", "App", "", AppMode.CHAT, "normal", None, None), True, None+ )++ monkeypatch.setattr(app_query_services.apps.discovery, "describe", describe)+ with app.test_request_context():+ result = cast(Endpoint[AppDescribeResponse], api.get).__handler__(+ api, context, "app-id", query=AppDescribeQuery.model_validate({"fields": "info"})+ )+ assert calls == [(context, {"info"})]+ assert result.info is not None+ assert result.info.id == "app-id"+ assert result.parameters is None+ assert result.input_schema is None++[email protected]("api", [AppDescribeApi(), PermittedExternalAppDescribeApi()])+def test_describe_translates_disappearing_app_to_404(+ app: Flask,+ app_query_services: ControllerTestServices,+ monkeypatch: pytest.MonkeyPatch,+ api: AppDescribeApi | PermittedExternalAppDescribeApi,+) -> None:+ def missing(*_args: object) -> AppDescription:+ raise AppDiscoveryNotFoundError("app not found")++ monkeypatch.setattr(app_query_services.apps.discovery, "describe", missing)+ context = AppRequestContext(tenant_id="workspace-id", app_id="app-id")+ with app.test_request_context(), pytest.raises(NotFound, match="app not found"):+ cast(Endpoint[AppDescribeResponse], api.get).__handler__(api, context, "app-id", query=AppDescribeQuery())+++def test_external_failure_is_translated_at_http_boundary(+ app: Flask,+ app_query_services: ControllerTestServices,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def unavailable(*_args: object) -> None:+ raise PermittedAppsUnavailableError("permitted_apps_unavailable")++ monkeypatch.setattr(app_query_services.apps.discovery, "list_permitted_apps", unavailable)+ api = PermittedExternalAppsListApi()+ with app.test_request_context(), pytest.raises(ServiceUnavailable, match="permitted_apps_unavailable"):+ cast(Endpoint[PermittedExternalAppsListResponse], api.get).__handler__(+ api, query=PermittedExternalAppsListQuery()+ )diff --git a/api/tests/unit_tests/controllers/openapi/test_app_dsl.py b/api/tests/unit_tests/controllers/openapi/test_app_dsl.pyindex 216ba150b2a..07091d84d9d 100644--- a/api/tests/unit_tests/controllers/openapi/test_app_dsl.py+++ b/api/tests/unit_tests/controllers/openapi/test_app_dsl.py@@ -1,15 +1,32 @@from collections.abc import Callable+from dataclasses import dataclassfrom typing import Protocol, cast+from uuid import uuid4import pytest-from flask import Flask-from werkzeug.exceptions import Forbidden+from flask import Flask, request+from flask_restx import Resource+from sqlalchemy.orm import Session, sessionmaker+from controllers.common.errors import ForbiddenErrorfrom controllers.openapi._contract import op_of-from controllers.openapi._models import AppDslImportPayload, AppDslImportResponse, Hint-from controllers.openapi.app_dsl import AppDslImportApi, AppDslImportConfirmApi+from controllers.openapi._errors import OpenApiErrorFormatter+from controllers.openapi._models import (+ AppDslExportQuery,+ AppDslExportResponse,+ AppDslImportPayload,+ AppDslImportResponse,+ Hint,+)+from controllers.openapi.app_dsl import AppDslExportApi, AppDslImportApi, AppDslImportConfirmApifrom controllers.openapi.auth.spec import EndpointSpec-from machinery.context import RequestContext+from libs.external_api import ExternalApi+from machinery.context import AppRequestContext, RequestContext+from models.model import App, AppMode+from models.workflow import Workflow, WorkflowType+from repositories.app.export_repository import AppExportRepository+from services.app.export_service import AppExportService+from services.app_dsl_service import AppDslServicefrom services.entities.dsl_entities import Import, ImportStatusfrom services.errors.base import NoPermissionErrorfrom tests.unit_tests.controllers.conftest import ControllerTestServices@@ -22,6 +39,105 @@ class _EndpointView(Protocol):__handler__: Callable[..., tuple[AppDslImportResponse, int]]+class _ExportEndpoint(Protocol):+ __handler__: Callable[..., tuple[AppDslExportResponse, int]]+++@dataclass(frozen=True)+class ExportAppServices:+ exports: AppExportService+++@dataclass(frozen=True)+class ExportServices:+ apps: ExportAppServices+++ ("missing", "status", "error_code"),+ [+ ("app", 404, "not_found"),+ ("draft", 404, "not_found"),+ ("version", 404, "not_found"),+ ("draft_version", 400, "bad_request"),+ ],+)+def test_export_errors_have_canonical_http_responses(+ sqlite_session: Session,+ sqlite_session_factory: sessionmaker[Session],+ missing: str,+ status: int,+ error_code: str,+) -> None:+ """Exercise the admitted handler, real export reads and HTTP error formatter."""+ app_id, tenant_id, workflow_id = str(uuid4()), str(uuid4()), str(uuid4())+ if missing != "app":+ sqlite_session.add(+ App(+ id=app_id,+ tenant_id=tenant_id,+ name="Exported workflow",+ mode=AppMode.WORKFLOW,+ enable_api=True,+ enable_site=False,+ )+ )+ if missing in {"version", "draft_version"}:+ # A draft exists, but an explicitly requested version must not fall back to it.+ sqlite_session.add(+ Workflow(+ id=workflow_id if missing == "draft_version" else str(uuid4()),+ tenant_id=tenant_id,+ app_id=app_id,+ type=WorkflowType.WORKFLOW,+ version=Workflow.VERSION_DRAFT,+ graph='{"nodes": [], "edges": []}',+ features="{}",+ created_by="account-id",+ )+ )+ sqlite_session.commit()++ app = Flask(__name__)+ app.config["TESTING"] = True+ app.extensions["application_services"] = ExportServices(+ apps=ExportAppServices(+ exports=AppExportService(+ apps=AppExportRepository(session_factory=sqlite_session_factory),+ serialize=AppDslService.serialize_export_data,+ )+ )+ )+ api = ExternalApi(app, error_body_formatter=OpenApiErrorFormatter())++ class AdmittedExport(Resource):+ def get(self, app_id: str) -> tuple[AppDslExportResponse, int]:+ return cast(_ExportEndpoint, AppDslExportApi.get).__handler__(+ AppDslExportApi(),+ AppRequestContext(tenant_id=tenant_id, app_id=app_id),+ app_id,+ query=AppDslExportQuery.model_validate(request.args.to_dict(flat=True)),+ )++ api.add_resource(AdmittedExport, "/apps/<string:app_id>/dsl")+ response = app.test_client().get(+ f"/apps/{app_id}/dsl",+ query_string={"workflow_id": workflow_id} if missing in {"version", "draft_version"} else {},+ )++ messages = {+ "app": "app not found",+ "draft": "Missing draft workflow configuration, please check.",+ "version": f"Workflow version not found. Workflow ID: {workflow_id}.",+ "draft_version": (+ f"Cannot use draft workflow version. Workflow ID: {workflow_id}. "+ "Please use a published workflow version or leave workflow_id empty."+ ),+ }+ assert response.status_code == status+ assert response.get_json() == {"code": error_code, "message": messages[missing], "status": status}++@pytest.mark.parametrize(("api", "kwargs"),[@@ -53,10 +169,12 @@ def test_permission_denial_maps_to_forbidden(context = RequestContext("request-1", None, "account-1", "workspace-1")with app.test_request_context("/openapi/v1/workspaces/workspace-1/apps/imports", method="POST"):- with pytest.raises(Forbidden, match="denied") as exc_info:+ with pytest.raises(ForbiddenError, match="denied") as exc_info:cast(_EndpointView, api.post).__handler__(api, context, **kwargs)assert isinstance(exc_info.value.__cause__, NoPermissionError)+ assert exc_info.value.code == 403+ assert exc_info.value.data == {"code": "forbidden", "message": "denied", "status": 403}@pytest.mark.parametrize(diff --git a/api/tests/unit_tests/controllers/openapi/test_app_payloads.py b/api/tests/unit_tests/controllers/openapi/test_app_payloads.pydeleted file mode 100644index 6ce3476808f..00000000000--- a/api/tests/unit_tests/controllers/openapi/test_app_payloads.py+++ /dev/null@@ -1,45 +0,0 @@-"""Unit tests for app payload-rendering helpers — independent of-HTTP plumbing or DB. Pin the response shapes that are CLI contracts.-"""--from __future__ import annotations--import pytest-from sqlalchemy.orm import Session--from controllers.openapi.apps import ( # pyright: ignore[reportPrivateUsage]- _EMPTY_PARAMETERS,- parameters_payload,-)-from controllers.service_api.app.error import AppUnavailableError-from models.model import App-from tests.unit_tests.model_factories import make_app---def _app() -> App:- return make_app(app_id="app1", name="X", description="d", enable_site=False, max_active_requests=0)---def test_parameters_payload_raises_app_unavailable_when_no_config(unbound_session: Session):- app = _app()-- with pytest.raises(AppUnavailableError):- parameters_payload(app, session=unbound_session)---def test_empty_parameters_constant_matches_describe_fallback_shape():- """The fallback dict served by /describe when an app has no config- must match the spec's stated keys (opening_statement, suggested_questions,- user_input_form, file_upload, system_parameters)."""- assert set(_EMPTY_PARAMETERS.keys()) == {- "opening_statement",- "suggested_questions",- "user_input_form",- "file_upload",- "system_parameters",- }- assert _EMPTY_PARAMETERS["suggested_questions"] == []- assert _EMPTY_PARAMETERS["user_input_form"] == []- assert _EMPTY_PARAMETERS["opening_statement"] is None- assert _EMPTY_PARAMETERS["file_upload"] is None- assert _EMPTY_PARAMETERS["system_parameters"] == {}diff --git a/api/tests/unit_tests/controllers/openapi/test_apps_permitted_external_query.py b/api/tests/unit_tests/controllers/openapi/test_apps_permitted_external_query.pyindex 475333927c1..496fcc1031c 100644--- a/api/tests/unit_tests/controllers/openapi/test_apps_permitted_external_query.py+++ b/api/tests/unit_tests/controllers/openapi/test_apps_permitted_external_query.py@@ -10,21 +10,15 @@ The allow/deny answers live in `test_auth_matrix.py`.from __future__ import annotations-from types import SimpleNamespace-from unittest.mock import patch-import pytestfrom pydantic import ValidationError-from sqlalchemy.orm import Sessionfrom controllers.openapi.apps_permitted_external import (- PermittedExternalAppDescribeApi,PermittedExternalAppsListQuery,)-from models.model import App, AppMode-def test_query_defaults_match_apps_list():+def test_query_defaults_match_apps_list() -> None:q = PermittedExternalAppsListQuery.model_validate({})assert q.page == 1assert q.limit == 20@@ -32,7 +26,7 @@ def test_query_defaults_match_apps_list():assert q.name is None-def test_query_rejects_workspace_id():+def test_query_rejects_workspace_id() -> None:"""workspace_id is meaningless for /permitted-external-apps (cross-tenant);rejecting it forces CLI authors to drop the param rather than send itsilently."""@@ -40,35 +34,11 @@ def test_query_rejects_workspace_id():PermittedExternalAppsListQuery.model_validate({"workspace_id": "ws-1"})-def test_query_validates_mode_against_supported_app_type():+def test_query_validates_mode_against_supported_app_type() -> None:with pytest.raises(ValidationError):PermittedExternalAppsListQuery.model_validate({"mode": "not-a-mode"})-def test_query_clamps_limit_at_max():+def test_query_clamps_limit_at_max() -> None:with pytest.raises(ValidationError):PermittedExternalAppsListQuery.model_validate({"limit": 500})---def test_describe_forwards_request_session_to_response_builder(unbound_session: Session):- api = PermittedExternalAppDescribeApi()- app = App(- id="app-id",- tenant_id="tenant-1",- name="Permitted app",- mode=AppMode.CHAT,- enable_site=True,- enable_api=True,- )- ctx = SimpleNamespace(app=app, session=unbound_session)- query = SimpleNamespace(fields={"info"})- response = object()-- with patch(- "controllers.openapi.apps_permitted_external.build_app_describe_response",- return_value=response,- ) as build_response:- result = api.get.__handler__(api, ctx, "app-id", query=query)-- assert result is response- build_response.assert_called_once_with(app, query.fields, session=unbound_session)diff --git a/api/tests/unit_tests/controllers/openapi/test_input_schema.py b/api/tests/unit_tests/controllers/openapi/test_input_schema.pyindex 6e88fa39e54..fdb8a726948 100644--- a/api/tests/unit_tests/controllers/openapi/test_input_schema.py+++ b/api/tests/unit_tests/controllers/openapi/test_input_schema.py@@ -2,17 +2,13 @@from __future__ import annotations-import json-import pytest-from sqlalchemy.orm import Session-from controllers.openapi._input_schema import _form_to_jsonschema-from models.model import App, AppMode, AppModelConfig-from models.workflow import Workflow, WorkflowType+from controllers.openapi._input_schema import _form_to_jsonschema, build_input_schema+from models.model import AppMode-def _wrap(component: dict) -> list[dict]:+def _wrap(component: dict[str, object]) -> list[dict[str, object]]:"""user_input_form rows are single-key dicts: {"text-input": {...}}."""return [component]@@ -92,120 +88,26 @@ def test_max_length_omitted_when_zero() -> None:assert "maxLength" not in props["x"]-from controllers.openapi._input_schema import EMPTY_INPUT_SCHEMA, build_input_schema-from controllers.service_api.app.error import AppUnavailableError---def _persist_app(- session: Session,- mode: AppMode,- *,- form: list[dict] | None = None,- has_config: bool = True,-) -> App:- app = App(- id="00000000-0000-0000-0000-000000000001",- tenant_id="00000000-0000-0000-0000-000000000002",- name="Input schema app",- mode=mode,- enable_site=False,- enable_api=True,- )- if mode in (AppMode.WORKFLOW, AppMode.ADVANCED_CHAT):- if has_config:- variables = [body | {"type": row_type} for row in form or [] for row_type, body in row.items()]- workflow = Workflow(- id="00000000-0000-0000-0000-000000000004",- tenant_id=app.tenant_id,- app_id=app.id,- type=WorkflowType.CHAT,- version=Workflow.VERSION_DRAFT,- graph=json.dumps({"nodes": [{"id": "start", "data": {"type": "start", "variables": variables}}]}),- features="{}",- created_by="00000000-0000-0000-0000-000000000003",- )- app.workflow_id = workflow.id- session.add(workflow)- else:- if has_config:- app_model_config = AppModelConfig(app_id=app.id, user_input_form=json.dumps(form or []))- app.app_model_config_id = app_model_config.id- session.add(app_model_config)- session.add(app)- session.flush()- return app---def test_chat_mode_includes_query(sqlite_session: Session) -> None:- app = _persist_app(- sqlite_session,- AppMode.CHAT,- form=[{"text-input": {"variable": "x", "label": "X", "required": True}}],- )- session = sqlite_session- schema = build_input_schema(app, session=session)- assert schema["$schema"] == "https://json-schema.org/draft/2020-12/schema"- assert "query" in schema["properties"]- assert schema["properties"]["query"]["type"] == "string"- assert schema["properties"]["query"]["minLength"] == 1- assert "query" in schema["required"]- assert "inputs" in schema["required"]- assert schema["properties"]["inputs"]["additionalProperties"] is False- assert session.get(AppModelConfig, app.app_model_config_id) is not None---def test_agent_chat_mode_includes_query(sqlite_session: Session) -> None:- app = _persist_app(sqlite_session, AppMode.AGENT_CHAT, form=[])- schema = build_input_schema(app, session=sqlite_session)- assert "query" in schema["properties"]---def test_advanced_chat_mode_includes_query(sqlite_session: Session) -> None:- app = _persist_app(sqlite_session, AppMode.ADVANCED_CHAT, form=[])- schema = build_input_schema(app, session=sqlite_session)- assert "query" in schema["properties"]---def test_workflow_mode_omits_query(sqlite_session: Session) -> None:- app = _persist_app(sqlite_session, AppMode.WORKFLOW, form=[])- schema = build_input_schema(app, session=sqlite_session)- assert "query" not in schema["properties"]- assert schema["required"] == ["inputs"]---def test_completion_mode_omits_query(sqlite_session: Session) -> None:- app = _persist_app(sqlite_session, AppMode.COMPLETION, form=[])- schema = build_input_schema(app, session=sqlite_session)- assert "query" not in schema["properties"]- assert schema["required"] == ["inputs"]---def test_inputs_required_driven_by_form(sqlite_session: Session) -> None:- app = _persist_app(- sqlite_session,- AppMode.CHAT,- form=[+ ("mode", "has_query"),+ [+ (AppMode.CHAT, True),+ (AppMode.AGENT_CHAT, True),+ (AppMode.ADVANCED_CHAT, True),+ (AppMode.WORKFLOW, False),+ (AppMode.COMPLETION, False),+ ],+)+def test_input_schema_depends_only_on_mode_and_materialized_form(mode: AppMode, has_query: bool) -> None:+ schema = build_input_schema(+ mode,+ [{"text-input": {"variable": "industry", "label": "Industry", "required": True}},{"text-input": {"variable": "context", "label": "Context", "required": False}},],)- schema = build_input_schema(app, session=sqlite_session)+ assert schema["$schema"] == "https://json-schema.org/draft/2020-12/schema"+ assert ("query" in schema["properties"]) == has_query+ assert schema["required"] == (["query", "inputs"] if has_query else ["inputs"])assert schema["properties"]["inputs"]["required"] == ["industry"]---def test_misconfigured_chat_raises_app_unavailable(sqlite_session: Session) -> None:- app = _persist_app(sqlite_session, AppMode.CHAT, has_config=False)- with pytest.raises(AppUnavailableError):- build_input_schema(app, session=sqlite_session)---def test_misconfigured_workflow_raises_app_unavailable(sqlite_session: Session) -> None:- app = _persist_app(sqlite_session, AppMode.WORKFLOW, has_config=False)- with pytest.raises(AppUnavailableError):- build_input_schema(app, session=sqlite_session)---def test_empty_input_schema_sentinel_shape() -> None:- assert EMPTY_INPUT_SCHEMA["type"] == "object"- assert EMPTY_INPUT_SCHEMA["properties"] == {}- assert EMPTY_INPUT_SCHEMA["required"] == []+ assert schema["properties"]["inputs"]["additionalProperties"] is Falsediff --git a/api/tests/unit_tests/controllers/openapi/test_supported_app_type.py b/api/tests/unit_tests/controllers/openapi/test_supported_app_type.pyindex 3af1c148644..5c0ed78f54e 100644--- a/api/tests/unit_tests/controllers/openapi/test_supported_app_type.py+++ b/api/tests/unit_tests/controllers/openapi/test_supported_app_type.py@@ -4,11 +4,11 @@ openapi `app` face (`get app`) exposes and the CLI `--mode` whitelist derives frfrom __future__ import annotations-from controllers.openapi._models import SUPPORTED_APP_TYPES, SupportedAppTypefrom models.model import AppMode+from services.entities.app_entities import SUPPORTED_APP_TYPES, SupportedAppType-def test_supported_app_type_is_the_listable_subset_of_app_mode():+def test_supported_app_type_is_the_listable_subset_of_app_mode() -> None:"""SupportedAppType (and the derived SUPPORTED_APP_TYPES tuple) is exactly thecurated, listable subset of AppMode; non-app/runtime modes stay out."""assert {t.value for t in SupportedAppType} == {diff --git a/api/tests/unit_tests/controllers/service_api/end_user/test_end_user.py b/api/tests/unit_tests/controllers/service_api/end_user/test_end_user.pyindex 7177b256aae..d52b5613b38 100644--- a/api/tests/unit_tests/controllers/service_api/end_user/test_end_user.py+++ b/api/tests/unit_tests/controllers/service_api/end_user/test_end_user.py@@ -7,14 +7,14 @@ import pytestfrom controllers.service_api.end_user import end_user as controller_modulefrom controllers.service_api.end_user.end_user import EndUserApifrom controllers.service_api.end_user.error import EndUserNotFoundError-from machinery.context import ServiceApiRequestContext+from machinery.context import AppRequestContextfrom models.model import Appfrom services.app_scoped_end_user_query_service import AppScopedEndUserNotFoundErrorfrom services.entities.app_scoped_end_user_entities import AppScopedEndUserRecord-def _request_context(*, tenant_id: str = "workspace-1", app_id: str = "app-1") -> ServiceApiRequestContext:- return ServiceApiRequestContext(+def _request_context(*, tenant_id: str = "workspace-1", app_id: str = "app-1") -> AppRequestContext:+ return AppRequestContext(tenant_id=tenant_id,app_id=app_id,)@@ -23,9 +23,9 @@ def _request_context(*, tenant_id: str = "workspace-1", app_id: str = "app-1") -class EndUserQueryServiceStub:def __init__(self, result: AppScopedEndUserRecord | Exception) -> None:self._result = result- self.calls: list[tuple[ServiceApiRequestContext, str]] = []+ self.calls: list[tuple[AppRequestContext, str]] = []- def get_by_id(self, context: ServiceApiRequestContext, end_user_id: str) -> AppScopedEndUserRecord:+ def get_by_id(self, context: AppRequestContext, end_user_id: str) -> AppScopedEndUserRecord:self.calls.append((context, end_user_id))if isinstance(self._result, Exception):raise self._resultdiff --git a/api/tests/unit_tests/extensions/test_ext_application_services.py b/api/tests/unit_tests/extensions/test_ext_application_services.pyindex 8b41d60da44..13715853de2 100644--- a/api/tests/unit_tests/extensions/test_ext_application_services.py+++ b/api/tests/unit_tests/extensions/test_ext_application_services.py@@ -45,6 +45,7 @@ from models.provider import ProviderCredentialfrom repositories.account.repository import SQLAlchemyAccountRepositoryfrom repositories.account_activation_repository import SQLAlchemyAccountActivationRepositoryfrom repositories.account_integration_repository import SQLAlchemyAccountIntegrationRepository+from repositories.app.console_repository import ConsoleAppRepositoryfrom repositories.app.site_command_repository import AppSiteCommandRepositoryfrom repositories.app.tracing_config_repository import SQLAlchemyAppTracingConfigRepositoryfrom repositories.app.workflow_comment_repository import WorkflowCommentRepository@@ -252,7 +253,11 @@ def test_init_app_registers_services_for_the_current_app(assert repository._session_factory is sqlite_session_factoryassert isinstance(services.workflow_statistics, WorkflowStatisticQueryService)assert isinstance(services.apps, AppServices)- assert services.apps.console._apps is services.apps.queries._apps+ assert services.apps.console._apps is services.apps.discovery._apps+ dataset_operations = services.knowledge.datasets._operations+ assert isinstance(dataset_operations, SQLAlchemyDatasetOperations)+ assert isinstance(dataset_operations._app_queries, ConsoleAppRepository)+ assert dataset_operations._app_queries._session_factory is sqlite_session_factorycreators = services.apps.console._creatorsassert isinstance(creators, CreatorsPlatformGateway)assert creators._oauth is services.oauth_serverdiff --git a/api/tests/unit_tests/machinery/test_service_api_context.py b/api/tests/unit_tests/machinery/test_app_context.pysimilarity index 53%rename from api/tests/unit_tests/machinery/test_service_api_context.pyrename to api/tests/unit_tests/machinery/test_app_context.pyindex dc17aa7890c..fed90d1e460 100644--- a/api/tests/unit_tests/machinery/test_service_api_context.py+++ b/api/tests/unit_tests/machinery/test_app_context.py@@ -1,8 +1,8 @@-from machinery.context import ServiceApiRequestContext+from machinery.context import AppRequestContext-def test_service_api_request_context_contains_only_app_scope() -> None:- context = ServiceApiRequestContext(+def test_app_request_context_contains_only_app_scope() -> None:+ context = AppRequestContext(tenant_id="tenant-1",app_id="app-1",)diff --git a/api/tests/unit_tests/pyrefly.toml b/api/tests/unit_tests/pyrefly.tomlindex fddb712cdc8..d024d0e6c3d 100644--- a/api/tests/unit_tests/pyrefly.toml+++ b/api/tests/unit_tests/pyrefly.toml@@ -126,15 +126,11 @@ project-excludes = ["controllers/inner_api/test_mail.py","controllers/inner_api/test_runtime_credentials.py","controllers/mcp/test_mcp.py",- "controllers/openapi/conftest.py","controllers/openapi/test_account.py",- "controllers/openapi/test_app_describe_builder.py","controllers/openapi/test_app_list_query.py",- "controllers/openapi/test_app_payloads.py","controllers/openapi/test_app_run_dispatch.py","controllers/openapi/test_app_run_rate_limit.py","controllers/openapi/test_app_run_streaming.py",- "controllers/openapi/test_apps_permitted_external_query.py","controllers/openapi/test_audit_app_run.py","controllers/openapi/test_contract.py","controllers/openapi/test_cors.py",@@ -146,7 +142,6 @@ project-excludes = ["controllers/openapi/test_error_contract.py","controllers/openapi/test_health.py","controllers/openapi/test_human_input_form.py",- "controllers/openapi/test_input_schema.py","controllers/openapi/test_meta_version.py","controllers/openapi/test_models.py","controllers/openapi/test_oauth_sso_claims.py",@@ -646,7 +641,6 @@ project-excludes = ["services/dataset_service_test_helpers.py","services/document_service_validation.py","services/enterprise/test_account_deletion_sync.py",- "services/enterprise/test_app_permitted_service.py","services/enterprise/test_plugin_manager_service.py","services/enterprise/test_traceparent_propagation.py","services/hit_service.py",diff --git a/api/tests/unit_tests/repositories/test_app_definition_query_repository.py b/api/tests/unit_tests/repositories/test_app_definition_query_repository.pyindex a4888797492..cec3f8fbbee 100644--- a/api/tests/unit_tests/repositories/test_app_definition_query_repository.py+++ b/api/tests/unit_tests/repositories/test_app_definition_query_repository.py@@ -4,11 +4,13 @@ import pytestfrom sqlalchemy.orm import Session, sessionmakerfrom core.tools.entities.tool_entities import ApiProviderSchemaType+from machinery.context import AppRequestContextfrom models.account import Account, Tenant, TenantStatusfrom models.enums import CustomizeTokenStrategy, TagTypefrom models.model import App, AppMode, AppModelConfig, IconType, Site, Tag, TagBindingfrom models.tools import ApiToolProviderfrom models.workflow import Workflow, WorkflowKind, WorkflowType+from repositories.app.console_repository import ConsoleAppRepositoryfrom repositories.app_definition_query_repository import AppDefinitionQueryRepositoryfrom services.app_definition_query_service import (AppDefinitionSummary,@@ -76,6 +78,54 @@ def test_get_published_parameter_config_returns_none_for_missing_app(assert repository.get_published_parameter_config(_APP_ID) is None+ ("mode", "ownership"),+ [+ (mode, ownership)+ for mode in (AppMode.CHAT, AppMode.WORKFLOW, AppMode.ADVANCED_CHAT)+ for ownership in ("owned", "foreign_app", "missing", "unset")+ ]+ + [(AppMode.WORKFLOW, "foreign_tenant"), (AppMode.ADVANCED_CHAT, "foreign_tenant")],+)+def test_parameter_config_readers_enforce_the_same_ownership(+ sqlite_session_factory: sessionmaker[Session], mode: AppMode, ownership: str+) -> None:+ with sqlite_session_factory.begin() as session:+ app = _persist_app(session, mode=mode)+ owner_id = _PROVIDER_ID if ownership == "foreign_app" else app.id+ if mode == AppMode.CHAT:+ config = AppModelConfig(app_id=owner_id, opening_statement="Owned config")+ app.app_model_config_id = config.id if ownership != "unset" else None+ else:+ config = Workflow(+ id=_WORKFLOW_ID,+ tenant_id=_OTHER_TENANT_ID if ownership == "foreign_tenant" else _TENANT_ID,+ app_id=owner_id,+ type=WorkflowType.WORKFLOW if mode == AppMode.WORKFLOW else WorkflowType.CHAT,+ version="1",+ graph='{"nodes": []}',+ features='{"opening_statement": "Owned config"}',+ created_by=_ACCOUNT_ID,+ )+ app.workflow_id = config.id if ownership != "unset" else None+ if ownership != "missing":+ session.add(config)++ definition = AppDefinitionQueryRepository(session_factory=sqlite_session_factory).get_published_parameter_config(+ _APP_ID+ )+ description = ConsoleAppRepository(session_factory=sqlite_session_factory).describe(+ AppRequestContext(tenant_id=_TENANT_ID, app_id=_APP_ID), include_config=True+ )++ assert definition == description.config+ if ownership == "owned":+ assert definition is not None+ assert definition.features_dict["opening_statement"] == "Owned config"+ else:+ assert definition is None++@pytest.mark.parametrize(("mode", "workflow_type"),[diff --git a/api/tests/unit_tests/repositories/test_app_definition_query_repository_agent.py b/api/tests/unit_tests/repositories/test_app_definition_query_repository_agent.pyindex d483a43c59d..d51f4b6dafc 100644--- a/api/tests/unit_tests/repositories/test_app_definition_query_repository_agent.py+++ b/api/tests/unit_tests/repositories/test_app_definition_query_repository_agent.py@@ -166,12 +166,15 @@ def test_get_public_parameter_config_loads_agent_snapshot([(Agent, AgentConfigSnapshot, AgentConfigRevision, AppAnnotationSetting, AppModelConfig)],indirect=True,)-def test_published_agent_app_parameters_use_soul_file_upload(sqlite_session: Session):[email protected]("foreign_model_config", [False, True])+def test_published_agent_app_parameters_use_soul_file_upload(+ sqlite_session: Session, foreign_model_config: bool+) -> None:tenant_id = _stable_uuid("tenant:one")agent_id = _stable_uuid("agent:one")snapshot_id = _stable_uuid("snapshot:one")app_model_config = AppModelConfig(- app_id=_stable_uuid(f"app:{tenant_id}"),+ app_id=_stable_uuid("foreign-app") if foreign_model_config else _stable_uuid(f"app:{tenant_id}"),opening_statement="Hi from legacy presentation config",file_upload=json.dumps({"enabled": False, "image": {"enabled": False}}),)@@ -212,7 +215,7 @@ def test_published_agent_app_parameters_use_soul_file_upload(sqlite_session: Ses)parameters = get_parameters_from_feature_dict(features_dict=features_dict, user_input_form=user_input_form)- assert parameters["opening_statement"] == "Hi from legacy presentation config"+ assert parameters["opening_statement"] == (None if foreign_model_config else "Hi from legacy presentation config")assert parameters["file_upload"] == {"enabled": True,"allowed_file_extensions": ["PNG"],diff --git a/api/tests/unit_tests/repositories/test_console_app_repository.py b/api/tests/unit_tests/repositories/test_console_app_repository.pyindex 1b4f66f6276..ce6b3d6580b 100644--- a/api/tests/unit_tests/repositories/test_console_app_repository.py+++ b/api/tests/unit_tests/repositories/test_console_app_repository.py@@ -2,6 +2,7 @@import jsonfrom collections.abc import Callable+from dataclasses import asdictfrom uuid import uuid4import pytest@@ -19,6 +20,7 @@ from repositories.app.console_repository import ConsoleAppRepositoryfrom services.app.console_service import ConsoleAppNotFoundErrorfrom services.entities.app_entities import (AppListParams,+ AppRecord,AppTraceSettings,StarredAppListParams,UpdateAppParams,@@ -55,6 +57,81 @@ def repository(sqlite_session_factory: sessionmaker[Session]) -> ConsoleAppReposreturn ConsoleAppRepository(session_factory=sqlite_session_factory)[email protected]("case", ["visible", "missing", "disabled_api", "disabled_status", "foreign_workspace"])+def test_visible_app_lookup_checks_workspace_status_and_api(sqlite_session: Session, case: str) -> None:+ app = persist_app(sqlite_session, enable_api=case != "disabled_api")+ if case == "disabled_status":+ sqlite_session.execute(+ text("UPDATE apps SET status = :status WHERE id = :app_id"), {"status": "disabled", "app_id": app.id}+ )+ sqlite_session.commit()+ app_id = str(uuid4()) if case == "missing" else app.id+ tenant_id = str(uuid4()) if case == "foreign_workspace" else WORKSPACE++ result = ConsoleAppRepository.get_visible_app_by_id(app_id, sqlite_session, tenant_id=tenant_id)++ if case == "visible":+ assert result is app+ else:+ assert result is None+++def test_visible_apps_bulk_lookup_preserves_cross_workspace_semantics(sqlite_session: Session) -> None:+ visible = persist_app(sqlite_session)+ foreign = persist_app(sqlite_session, tenant_id=str(uuid4()))+ disabled_api = persist_app(sqlite_session, enable_api=False)++ result = ConsoleAppRepository.find_visible_apps_by_ids(+ [visible.id, foreign.id, disabled_api.id, str(uuid4())], sqlite_session+ )++ assert {app.id for app in result} == {visible.id, foreign.id}+++def test_visible_apps_bulk_lookup_skips_database_for_empty_ids(unbound_session: Session) -> None:+ assert ConsoleAppRepository.find_visible_apps_by_ids([], unbound_session) == []+++def test_related_apps_materializes_scoped_records_and_closes_session(sqlite_engine: Engine) -> None:+ factory = sessionmaker(bind=sqlite_engine, expire_on_commit=False, close_resets_only=False)+ with factory() as session:+ visible_id = persist_app(session, name="Visible").id+ disabled_id = persist_app(session, enable_api=False).id+ foreign_id = persist_app(session, tenant_id=str(uuid4())).id++ repository = ConsoleAppRepository(session_factory=factory)+ connections: set[object] = set()+ checkouts: list[object] = []++ def checkout(connection: object, *_args: object) -> None:+ connections.add(connection)+ checkouts.append(connection)++ def checkin(connection: object, *_args: object) -> None:+ connections.remove(connection)++ event.listen(sqlite_engine, "checkout", checkout)+ event.listen(sqlite_engine, "checkin", checkin)+ try:+ related = repository.related_apps(WORKSPACE, [disabled_id, foreign_id, visible_id, str(uuid4())])+ assert [item.id for item in related] == [disabled_id, visible_id]+ assert all(isinstance(item, AppRecord) for item in related)+ assert not connections++ checkout_count = len(checkouts)+ assert checkout_count > 0+ assert asdict(related[1])["name"] == "Visible"+ serialized = AppPagination.model_validate(+ {"page": 1, "limit": 2, "total": 2, "has_more": False, "data": related}+ ).model_dump(mode="json")+ assert [item["id"] for item in serialized["data"]] == [disabled_id, visible_id]+ assert len(checkouts) == checkout_count+ assert not connections+ finally:+ event.remove(sqlite_engine, "checkout", checkout)+ event.remove(sqlite_engine, "checkin", checkin)++def test_rbac_maintainer_lookup_requires_owning_workspace(repository: ConsoleAppRepository, sqlite_session: Session) -> None:diff --git a/api/tests/unit_tests/repositories/workspace/test_workspace_repository.py b/api/tests/unit_tests/repositories/workspace/test_workspace_repository.pyindex 385c4a75517..d9b339f8c9c 100644--- a/api/tests/unit_tests/repositories/workspace/test_workspace_repository.py+++ b/api/tests/unit_tests/repositories/workspace/test_workspace_repository.py@@ -49,6 +49,16 @@ def seeded(sqlite_session_factory: sessionmaker[Session]) -> WorkspaceRepositoryreturn WorkspaceRepository(sqlite_session_factory)+def test_names_by_ids_returns_only_existing_requested_workspaces(seeded: WorkspaceRepository) -> None:+ assert seeded.names_by_ids(["w1", "w3", "missing", "w1"]) == {"w1": "First", "w3": "Archived"}+ assert seeded.names_by_ids(["missing"]) == {}+++def test_names_by_ids_short_circuits_empty_input(unbound_session_factory: sessionmaker[Session]) -> None:+ repository = WorkspaceRepository(unbound_session_factory)+ assert repository.names_by_ids([]) == {}++def test_lists_preserve_visibility_order_and_archived_memberships(seeded: WorkspaceRepository) -> None:assert [row.id for row in seeded.list_for_account("a1")] == ["w1", "w2"]assert seeded.list_for_account("absent") == ()diff --git a/api/tests/unit_tests/services/app/test_console_gateway.py b/api/tests/unit_tests/services/app/test_console_gateway.pyindex 063f98c0e7a..f3c085c919a 100644--- a/api/tests/unit_tests/services/app/test_console_gateway.py+++ b/api/tests/unit_tests/services/app/test_console_gateway.py@@ -17,7 +17,7 @@ from core.plugin.entities.plugin import PluginDependency, PluginInstallationfrom core.plugin.impl.plugin import PluginInstallerfrom enums import CloudPlan, DeploymentEditionfrom extensions.application_services.app import AppServices-from machinery.context import RequestContext+from machinery.context import AppRequestContext, RequestContextfrom models.account import Account, TenantAccountJoin, TenantAccountRolefrom models.agent import (Agent,@@ -33,6 +33,7 @@ from models.agent import (from models.agent_config_entities import AgentSoulConfigfrom models.model import App, AppMode, AppModelConfig, IconTypefrom models.workflow import Workflow, WorkflowType+from repositories.app.export_repository import AppExportRepositoryfrom services.agent.dsl_entities import AGENT_PACKAGE_REF_KEYfrom services.agent.package_resource_exporter import AgentPackageResourceExporterfrom services.agent.roster_package_exporter import RosterAgentPackageExporter@@ -40,6 +41,7 @@ from services.agent.roster_package_importer import RosterAgentPackageImporterfrom services.agent.roster_service import AgentRosterServicefrom services.app.console_gateway import AppTransferGateway, EnterpriseConsoleAppAccessfrom services.app.console_service import ConsoleAppNotFoundError, InvalidAppAccessModesError+from services.app.export_service import AppExportServicefrom services.app_dsl_service import AppDslServicefrom services.app_package_service import AppPackageService, PreparedAppPackagefrom services.enterprise.enterprise_service import EnterpriseService, WebAppSettings@@ -177,7 +179,9 @@ def test_copy_preserves_shared_roster_bindings_and_clones_owned_inline_agents(monkeypatch.setattr(DependenciesAnalysisService, "generate_dependencies", lambda **_kwargs: [])monkeypatch.setattr(SystemFeatureService, "is_webapp_auth_enabled", lambda: False)workflow_service = WorkflowService(session_maker=sqlite_session_factory)- monkeypatch.setattr("services.app_dsl_service.WorkflowService", lambda: workflow_service)+ monkeypatch.setattr(+ "services.app_dsl_service.WorkflowService", Mock(wraps=WorkflowService, return_value=workflow_service)+ )exported = app_services.console.export(context, app_id, AppExportOptions(format="yaml"))assert isinstance(exported, str)@@ -463,7 +467,10 @@ def test_access_mode_batch_validates_completeness(monkeypatch: pytest.MonkeyPatc@pytest.mark.parametrize("mode", [AppMode.WORKFLOW, AppMode.ADVANCED_CHAT, AppMode.CHAT, AppMode.COMPLETION, AppMode.AGENT_CHAT])-def test_dsl_export_uses_owned_short_session_and_preserves_selectors(sqlite_engine: Engine, mode: AppMode) -> None:+def test_dsl_export_uses_owned_short_session_and_preserves_selectors(+ sqlite_engine: Engine,+ mode: AppMode,+) -> None:factory = sessionmaker(bind=sqlite_engine, expire_on_commit=False, close_resets_only=False)app_id, workspace = str(uuid4()), str(uuid4())with factory.begin() as session:@@ -483,6 +490,8 @@ def test_dsl_export_uses_owned_short_session_and_preserves_selectors(sqlite_engi@staticmethoddef serialize_export_data(prepared: AppDslExportData) -> str:assert prepared.tenant_id == workspace+ with pytest.raises(InvalidRequestError):+ opened[-1].execute(select(App))return f"kind: app\napp: {{mode: {mode}}}"gateway = AppTransferGateway(@@ -496,6 +505,7 @@ def test_dsl_export_uses_owned_short_session_and_preserves_selectors(sqlite_engicontext = RequestContext("request", None, "actor", workspace)options = AppExportOptions(include_secret=True, workflow_id="workflow")dsl = gateway.export_dsl(context, app_id, options)+ assert dsl == f"kind: app\napp: {{mode: {mode}}}"exported_app = calls[0]["app_model"]assert isinstance(exported_app, App)assert exported_app.id == app_id@@ -513,8 +523,9 @@ def test_dsl_export_uses_owned_short_session_and_preserves_selectors(sqlite_engi[AppMode.CHAT, AppMode.COMPLETION, AppMode.AGENT_CHAT, AppMode.WORKFLOW, AppMode.ADVANCED_CHAT, AppMode.AGENT],)@pytest.mark.parametrize("remote_fails", [False, True])[email protected]("surface", ["console", "openapi", "inner"])def test_real_dsl_export_releases_connection_before_plugin_request(- sqlite_engine: Engine, monkeypatch: pytest.MonkeyPatch, mode: AppMode, remote_fails: bool+ sqlite_engine: Engine, monkeypatch: pytest.MonkeyPatch, mode: AppMode, remote_fails: bool, surface: str) -> None:factory = sessionmaker(bind=sqlite_engine, expire_on_commit=False, close_resets_only=False)app_id, workspace, actor = str(uuid4()), str(uuid4()), str(uuid4())@@ -544,8 +555,6 @@ def test_real_dsl_export_releases_connection_before_plugin_request(session.flush()app.app_model_config_id = config.id- workflow_service = WorkflowService(session_maker=factory)- monkeypatch.setattr("services.app_dsl_service.WorkflowService", lambda: workflow_service)checked_out: set[object] = set()calls: list[list[str]] = []@@ -572,15 +581,28 @@ def test_real_dsl_export_releases_connection_before_plugin_request(agent_importer=RosterAgentPackageImporter(),recommended_packages=RecommendedAppPackageService(sources=Mock(), exporter=Mock()),)+ exports = AppExportService(+ apps=AppExportRepository(session_factory=factory), serialize=AppDslService.serialize_export_data+ )++ def export() -> str:+ if surface == "console":+ return gateway.export_dsl(RequestContext("request", None, actor, workspace), app_id, AppExportOptions())+ if surface == "openapi":+ return exports.export_app(+ AppRequestContext(tenant_id=workspace, app_id=app_id),+ AppExportOptions(),+ )+ return exports.export_for_inner(app_id, AppExportOptions())+event.listen(sqlite_engine, "checkout", checkout)event.listen(sqlite_engine, "checkin", checkin)try:- context = RequestContext("request", None, actor, workspace)if remote_fails:with pytest.raises(RuntimeError, match="Plugin daemon unavailable"):- gateway.export_dsl(context, app_id, AppExportOptions())+ export()else:- exported = yaml.safe_load(gateway.export_dsl(context, app_id, AppExportOptions()))+ exported = yaml.safe_load(export())assert exported["app"]["mode"] == modeassert exported["dependencies"] == []assert len(calls) == 1diff --git a/api/tests/unit_tests/services/app/test_discovery_gateway.py b/api/tests/unit_tests/services/app/test_discovery_gateway.pynew file mode 100644index 00000000000..44cf837f3d5--- /dev/null+++ b/api/tests/unit_tests/services/app/test_discovery_gateway.py@@ -0,0 +1,49 @@+"""Discovery permissions use enterprise HTTP snapshots without opening Sessions."""++from collections.abc import Callable+from unittest.mock import ANY, Mock, call++import pytest+from sqlalchemy.orm import Session++from machinery.context import RequestContext+from services.app.access import AppAccessFilter+from services.app.discovery_gateway import EnterpriseAppDiscoveryAccess+from services.enterprise.enterprise_service import EnterpriseRequest++[email protected]("rbac_enabled", [False, True])+def test_visibility_needs_no_database_session(+ config_overrides: Callable[..., None], monkeypatch: pytest.MonkeyPatch, rbac_enabled: bool+) -> None:+ config_overrides(RBAC_ENABLED=rbac_enabled)+ send = Mock(+ side_effect=[+ {"workspace": {"permission_keys": ["app.full_access", "app.create_and_management"]}},+ {"unrestricted": False, "resource_ids": ["app-1"]},+ ]+ )+ monkeypatch.setattr(EnterpriseRequest, "send_inner_rbac_request", send)++ def reject_session(*_args: object, **_kwargs: object) -> None:+ pytest.fail("Discovery permissions must not create a database Session")++ monkeypatch.setattr(Session, "__init__", reject_session)+ result = EnterpriseAppDiscoveryAccess().visibility(RequestContext("req", None, "account-1", "tenant-1"))+ if rbac_enabled:+ assert result == AppAccessFilter({"app-1"}, False)+ assert send.call_args_list == [+ call(+ "GET",+ endpoint,+ tenant_id="tenant-1",+ account_id="account-1",+ params=None,+ json=None,+ timeout=ANY,+ )+ for endpoint in ("/rbac/my-permissions", "/rbac/apps/whitelist/resources")+ ]+ else:+ assert result == AppAccessFilter.unrestricted()+ send.assert_not_called()diff --git a/api/tests/unit_tests/services/app/test_export_service.py b/api/tests/unit_tests/services/app/test_export_service.pynew file mode 100644index 00000000000..510d86df070--- /dev/null+++ b/api/tests/unit_tests/services/app/test_export_service.py@@ -0,0 +1,107 @@+"""Exercise composed DSL export with real rows and workflow selectors."""++from dataclasses import replace+from uuid import uuid4++import pytest+import yaml+from flask import has_app_context+from sqlalchemy.orm import Session++from extensions.application_services.app import AppServices+from machinery.context import AppRequestContext+from models.model import App, AppMode+from models.workflow import Workflow, WorkflowType+from services.app_dsl_service import DependenciesAnalysisService+from services.entities.app_entities import AppExportOptions+from services.errors.app import AppDiscoveryNotFoundError, IsDraftWorkflowError, WorkflowNotFoundError++[email protected](autouse=True)+def _provide_app_context() -> None:+ """Override the suite's Flask context so export uses only injected dependencies."""+ assert not has_app_context()++[email protected](params=[AppMode.WORKFLOW, AppMode.ADVANCED_CHAT])+def exported_app(sqlite_session: Session, request: pytest.FixtureRequest) -> AppRequestContext:+ app_id, tenant_id = str(uuid4()), str(uuid4())+ sqlite_session.add(+ App(+ id=app_id,+ tenant_id=tenant_id,+ name="Exported",+ mode=request.param,+ enable_api=True,+ enable_site=False,+ )+ )+ sqlite_session.commit()+ return AppRequestContext(tenant_id=tenant_id, app_id=app_id)+++def test_export_scopes_openapi_but_allows_trusted_inner_apps(+ sqlite_session: Session,+ app_services: AppServices,+ exported_app: AppRequestContext,+) -> None:+ with pytest.raises(AppDiscoveryNotFoundError):+ app_services.exports.export_app(replace(exported_app, tenant_id=str(uuid4())), AppExportOptions())+ with pytest.raises(WorkflowNotFoundError):+ app_services.exports.export_app(exported_app, AppExportOptions())+ app = sqlite_session.get(App, exported_app.app_id)+ assert app is not None+ app.enable_api = False+ sqlite_session.commit()+ with pytest.raises(AppDiscoveryNotFoundError):+ app_services.exports.export_app(exported_app, AppExportOptions())+ with pytest.raises(WorkflowNotFoundError):+ app_services.exports.export_for_inner(exported_app.app_id, AppExportOptions())++[email protected]("surface", ["openapi", "inner"])[email protected]("selector", ["published", "default_draft", "draft", "foreign", "foreign_tenant", "missing"])+def test_selected_workflow_ownership_and_publication(+ sqlite_session: Session,+ app_services: AppServices,+ exported_app: AppRequestContext,+ selector: str,+ surface: str,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ workflow_id = str(uuid4())+ if selector != "missing":+ sqlite_session.add(+ Workflow(+ id=workflow_id,+ tenant_id=str(uuid4()) if selector == "foreign_tenant" else exported_app.tenant_id,+ app_id=str(uuid4()) if selector == "foreign" else exported_app.app_id,+ type=WorkflowType.WORKFLOW,+ version=Workflow.VERSION_DRAFT if selector in {"draft", "default_draft"} else "published",+ graph='{"nodes": [], "edges": []}',+ features="{}",+ created_by="account-id",+ )+ )+ sqlite_session.commit()+ options = AppExportOptions(workflow_id=None if selector == "default_draft" else workflow_id)+ if surface == "inner":+ app = sqlite_session.get(App, exported_app.app_id)+ assert app is not None+ app.enable_api = False+ sqlite_session.commit()++ def export() -> str:+ if surface == "inner":+ return app_services.exports.export_for_inner(exported_app.app_id, options)+ return app_services.exports.export_app(exported_app, options)++ if selector in {"published", "default_draft"}:+ monkeypatch.setattr(DependenciesAnalysisService, "generate_dependencies", lambda **_kwargs: [])+ data = yaml.safe_load(export())+ assert data["app"]["name"] == "Exported"+ assert data["workflow"]["graph"] == {"nodes": [], "edges": []}+ else:+ error = IsDraftWorkflowError if selector == "draft" else WorkflowNotFoundError+ with pytest.raises(error):+ export()diff --git a/api/tests/unit_tests/services/app/test_query_service.py b/api/tests/unit_tests/services/app/test_query_service.pyindex fbc481a1961..a4a14b886e6 100644--- a/api/tests/unit_tests/services/app/test_query_service.py+++ b/api/tests/unit_tests/services/app/test_query_service.py@@ -1,91 +1,244 @@-"""App query results survive repository closure without ORM or request state."""+"""App discovery queries preserve visibility and Session boundaries."""-from dataclasses import asdict+import json+from dataclasses import dataclass, fieldfrom uuid import uuid4+import pytestfrom sqlalchemy import Engine, event-from sqlalchemy.orm import sessionmaker+from sqlalchemy.orm import Session, sessionmaker-from fields.app_fields import AppPagination-from models.enums import AppStatus-from models.model import App, AppMode+from machinery.context import AppRequestContext, RequestContext+from models.account import Tenant+from models.model import App, AppMode, AppModelConfig+from models.workflow import Workflow, WorkflowTypefrom repositories.app.console_repository import ConsoleAppRepository-from services.app.query_service import AppQueryService-from services.entities.app_entities import AppListParams, AppRecord, AppSummary---def test_queries_return_materialized_data_and_close_their_sessions(sqlite_engine: Engine) -> None:- factory = sessionmaker(bind=sqlite_engine, expire_on_commit=False, close_resets_only=False)- tenant_id, other_tenant_id, account_id = (str(uuid4()) for _ in range(3))- visible_id, disabled_id, foreign_id = (str(uuid4()) for _ in range(3))- with factory.begin() as session:- session.add_all(- [- App(- id=app_id,- tenant_id=workspace,- name=name,- description=name,- mode=AppMode.CHAT,- enable_api=enabled,- enable_site=False,- )- for app_id, workspace, name, enabled in (- (visible_id, tenant_id, "Visible", True),- (disabled_id, tenant_id, "Disabled", False),- (foreign_id, other_tenant_id, "Other tenant", True),- )- ]- )+from repositories.workspace.workspace_repository import WorkspaceRepository+from services.app.access import AppAccessFilter+from services.app.query_service import AppDiscoveryQuery, AppDiscoveryService+from services.entities.app_entities import PermittedAppsPage+from services.errors.app import AppDiscoveryNotFoundError+++@dataclass+class DiscoveryAccess:+ access_filter: AppAccessFilter+ permitted: PermittedAppsPage+ contexts: list[RequestContext] = field(default_factory=list)+ queries: list[AppDiscoveryQuery] = field(default_factory=list)++ def visibility(self, context: RequestContext) -> AppAccessFilter:+ self.contexts.append(context)+ return self.access_filter++ def permitted_apps(self, query: AppDiscoveryQuery) -> PermittedAppsPage:+ self.queries.append(query)+ return self.permitted+++def access() -> DiscoveryAccess:+ return DiscoveryAccess(AppAccessFilter.unrestricted(), PermittedAppsPage([], 0, False))+++def service(sqlite_session_factory: sessionmaker[Session], access: DiscoveryAccess) -> AppDiscoveryService:+ return AppDiscoveryService(+ apps=ConsoleAppRepository(session_factory=sqlite_session_factory),+ workspaces=WorkspaceRepository(sqlite_session_factory),+ access=access,+ )+++def persist_app(session: Session, *, tenant_id: str, **values: object) -> str:+ app_id = str(uuid4())+ attributes: dict[str, object] = {+ "id": app_id,+ "tenant_id": tenant_id,+ "name": "Visible",+ "description": "description",+ "mode": AppMode.CHAT,+ "enable_api": True,+ "enable_site": False,+ }+ attributes.update(values)+ session.add(App(**attributes))+ session.commit()+ return app_id++[email protected]("uuid_search", [True, False])[email protected]("visibility", ["unrestricted", "whitelisted", "own", "denied"])+def test_list_and_uuid_search_apply_same_visibility(+ sqlite_session: Session,+ service: AppDiscoveryService,+ access: DiscoveryAccess,+ uuid_search: bool,+ visibility: str,+) -> None:+ tenant_id = str(uuid4())+ context = RequestContext("req", None, "account-id", tenant_id)+ tenant = Tenant(name="Workspace")+ tenant.id = tenant_id+ sqlite_session.add(tenant)+ app_id = persist_app(sqlite_session, tenant_id=tenant_id, maintainer=context.account_id)+ persist_app(sqlite_session, tenant_id=tenant_id, enable_api=False)+ persist_app(sqlite_session, tenant_id=str(uuid4()))+ access.access_filter = AppAccessFilter(+ None if visibility == "unrestricted" else {app_id} if visibility == "whitelisted" else set(),+ visibility == "own",+ )+ query = AppDiscoveryQuery(3 if uuid_search else 1, 20, None, app_id.upper() if uuid_search else None)+ result = service.list_apps(context, query)+ assert access.contexts == [context]+ assert result.total == (0 if visibility == "denied" else 1)+ if visibility == "denied":+ assert result.items == []+ assert (result.page, result.per_page) == (query.page, query.limit)+ else:+ assert [entry.app.id for entry in result.items] == [app_id]+ assert result.items[0].workspace_name == "Workspace"+ assert (result.page, result.per_page) == ((1, 1) if uuid_search else (1, 20))++[email protected]("values", [{"enable_api": False}, {"mode": AppMode.AGENT}])+def test_uuid_search_does_not_expose_unlistable_apps(+ sqlite_session: Session,+ service: AppDiscoveryService,+ values: dict[str, object],+) -> None:+ tenant_id = str(uuid4())+ app_id = persist_app(sqlite_session, tenant_id=tenant_id, **values)+ result = service.list_apps(+ RequestContext("req", None, "account-id", tenant_id), AppDiscoveryQuery(1, 20, None, app_id)+ )+ assert result.total == 0+ assert result.items == []+- repository = ConsoleAppRepository(session_factory=factory)- service = AppQueryService(apps=repository)+def test_uuid_search_is_tenant_scoped(sqlite_session: Session, service: AppDiscoveryService) -> None:+ app_id = persist_app(sqlite_session, tenant_id=str(uuid4()))+ result = service.list_apps(+ RequestContext("req", None, "account-id", str(uuid4())), AppDiscoveryQuery(1, 20, None, app_id)+ )+ assert result.items == []++[email protected]("uuid_search", [False, True])[email protected]("bound", [False, True])+def test_resource_bindings_replace_account_visibility(+ sqlite_session: Session, service: AppDiscoveryService, access: DiscoveryAccess, uuid_search: bool, bound: bool+) -> None:+ tenant_id = str(uuid4())+ app_id = persist_app(sqlite_session, tenant_id=tenant_id, maintainer="token-id")+ persist_app(sqlite_session, tenant_id=tenant_id, maintainer="token-id")+ access.access_filter = AppAccessFilter(set(), can_manage_own_apps=True)+ context = RequestContext(+ "req", None, "token-id", tenant_id, resource_app_ids=frozenset({app_id}) if bound else frozenset()+ )+ result = service.list_apps(context, AppDiscoveryQuery(1, 1, None, app_id if uuid_search else None))++ assert access.contexts == []+ assert result.total == (1 if bound else 0)+ assert [entry.app.id for entry in result.items] == ([app_id] if bound else [])+++def test_external_list_keeps_remote_order_and_total_after_local_filtering(+ sqlite_session: Session,+ service: AppDiscoveryService,+ access: DiscoveryAccess,+) -> None:+ tenant_id = str(uuid4())+ tenant = Tenant(name="Workspace")+ tenant.id = tenant_id+ sqlite_session.add(tenant)+ first = persist_app(sqlite_session, tenant_id=tenant_id)+ second = persist_app(sqlite_session, tenant_id=str(uuid4()))+ disabled = persist_app(sqlite_session, tenant_id=tenant_id, enable_api=False)+ access.permitted = PermittedAppsPage([second, disabled, str(uuid4()), first], 50, True)+ result = service.list_permitted_apps(AppDiscoveryQuery(2, 5, "chat", "name"))+ assert access.queries == [AppDiscoveryQuery(2, 5, "chat", "name")]+ assert (result.total, result.page, result.per_page) == (50, 2, 5)+ assert [entry.app.id for entry in result.items] == [second, first]+ assert [entry.workspace_name for entry in result.items] == [None, "Workspace"]++[email protected]("mode", [AppMode.CHAT, AppMode.WORKFLOW])[email protected]("foreign_config", [True, False])+def test_description_materializes_only_owned_config_and_closes_session(+ sqlite_session: Session,+ sqlite_engine: Engine,+ service: AppDiscoveryService,+ mode: AppMode,+ foreign_config: bool,+) -> None:+ tenant_id = str(uuid4())+ app_id = persist_app(sqlite_session, tenant_id=tenant_id, mode=mode)+ owner = str(uuid4()) if foreign_config else app_id+ form = [{"text-input": {"variable": "industry", "label": "Industry", "required": True}}]+ app = sqlite_session.get(App, app_id)+ assert app is not None+ if mode == AppMode.CHAT:+ config = AppModelConfig(app_id=owner, user_input_form=json.dumps(form))+ app.app_model_config_id = config.id+ else:+ config = Workflow(+ id=str(uuid4()),+ tenant_id=tenant_id,+ app_id=owner,+ type=WorkflowType.WORKFLOW,+ version=Workflow.VERSION_DRAFT,+ created_by="account-id",+ features="{}",+ graph=json.dumps(+ {+ "nodes": [+ {+ "id": "start",+ "data": {+ "type": "start",+ "variables": [+ {+ "type": "text-input",+ "variable": "industry",+ "label": "Industry",+ "required": True,+ }+ ],+ },+ }+ ]+ }+ ),+ )+ app.workflow_id = config.id+ sqlite_session.add(config)+ sqlite_session.commit()+ sqlite_session.close()+ context = AppRequestContext(tenant_id=tenant_id, app_id=app_id)connections: set[object] = set()- checkouts: list[object] = []def checkout(connection: object, *_args: object) -> None:connections.add(connection)- checkouts.append(connection)def checkin(connection: object, *_args: object) -> None:- connections.remove(connection)+ connections.discard(connection)event.listen(sqlite_engine, "checkout", checkout)event.listen(sqlite_engine, "checkin", checkin)try:- app = service.get_visible_app_by_id(visible_id, tenant_id)- assert isinstance(app, AppSummary)+ result = service.describe(context, None)assert not connections- assert service.get_visible_app_by_id(visible_id, other_tenant_id) is None- assert service.get_visible_app_by_id(disabled_id, tenant_id) is None- assert service.get_visible_app_by_id(str(uuid4()), tenant_id) is None+ assert result.app.id == app_id+ if foreign_config:+ assert result.config is None+ else:+ assert result.config is not None+ assert result.config.user_input_form[0]["text-input"]["variable"] == "industry"+ assert service.describe(context, {"info"}).config is Noneassert not connections-- visible = service.find_visible_apps_by_ids([visible_id, disabled_id])- assert [item.id for item in visible] == [visible_id]- assert not connections- page = service.get_paginate_apps(- account_id, tenant_id, AppListParams(status=AppStatus.NORMAL, openapi_visible=True)- )- assert page is not None- assert [item.id for item in page.items] == [visible_id]- assert page.total == 1- assert not connections-- related = service.related_apps(tenant_id, [disabled_id, foreign_id, visible_id, str(uuid4())])- assert [item.id for item in related] == [disabled_id, visible_id]- assert all(isinstance(item, AppRecord) for item in related)- assert not connections-- checkout_count = len(checkouts)- assert checkout_count > 0- assert asdict(app)["name"] == "Visible"- assert asdict(page)["items"][0]["tenant_id"] == tenant_id- serialized = AppPagination.model_validate(- {"page": 1, "limit": 2, "total": 2, "has_more": False, "data": related}- ).model_dump(mode="json")- assert [item["id"] for item in serialized["data"]] == [disabled_id, visible_id]- assert len(checkouts) == checkout_count+ with pytest.raises(AppDiscoveryNotFoundError):+ service.describe(AppRequestContext(tenant_id=str(uuid4()), app_id=app_id), None)assert not connectionsfinally:event.remove(sqlite_engine, "checkout", checkout)diff --git a/api/tests/unit_tests/services/enterprise/test_app_permitted_service.py b/api/tests/unit_tests/services/enterprise/test_app_permitted_service.pyindex 339f783ca8e..af2be4837da 100644--- a/api/tests/unit_tests/services/enterprise/test_app_permitted_service.py+++ b/api/tests/unit_tests/services/enterprise/test_app_permitted_service.py@@ -2,13 +2,15 @@ from unittest.mock import patchimport pytest-from services.enterprise.app_permitted_service import PermittedAppsPage, list_permitted_apps+from services.enterprise.app_permitted_service import list_permitted_apps+from services.entities.app_entities import PermittedAppsPage+from services.errors.app import PermittedAppsUnavailableErrorfrom services.errors.enterprise import EnterpriseAPIErrorWRAPPER = "services.enterprise.app_permitted_service.EnterpriseService.WebAppAuth.list_externally_accessible_apps"-def test_list_permitted_apps_decodes_camelcase_response():+def test_list_permitted_apps_decodes_camelcase_response() -> None:fake_body = {"data": [{"appId": "a"}, {"appId": "b"}],"total": 2,@@ -24,32 +26,28 @@ def test_list_permitted_apps_decodes_camelcase_response():m.assert_called_once_with(page=1, limit=10, mode=None, name=None)-def test_list_permitted_apps_passes_filters_to_wrapper():- fake_body = {"data": [], "total": 0, "hasMore": False}+def test_list_permitted_apps_passes_filters_to_wrapper() -> None:+ fake_body: dict[str, object] = {"data": [], "total": 0, "hasMore": False}with patch(WRAPPER, return_value=fake_body) as m:list_permitted_apps(page=2, limit=5, mode="workflow", name="alpha")m.assert_called_once_with(page=2, limit=5, mode="workflow", name="alpha")-def test_list_permitted_apps_503_on_ee_error():+def test_list_permitted_apps_503_on_ee_error() -> None:with patch(WRAPPER, side_effect=EnterpriseAPIError("boom", status_code=500)):- from werkzeug.exceptions import ServiceUnavailable-- with pytest.raises(ServiceUnavailable):+ with pytest.raises(PermittedAppsUnavailableError):list_permitted_apps(page=1, limit=10)-def test_list_permitted_apps_503_on_status_error():+def test_list_permitted_apps_503_on_status_error() -> None:with patch(WRAPPER, side_effect=EnterpriseAPIError("bad key", status_code=401)):- from werkzeug.exceptions import ServiceUnavailable-- with pytest.raises(ServiceUnavailable):+ with pytest.raises(PermittedAppsUnavailableError):list_permitted_apps(page=1, limit=10)-def test_list_permitted_apps_handles_empty_response():- fake_body = {"data": [], "total": 0, "hasMore": False}+def test_list_permitted_apps_handles_empty_response() -> None:+ fake_body: dict[str, object] = {"data": [], "total": 0, "hasMore": False}with patch(WRAPPER, return_value=fake_body):page = list_permitted_apps(page=1, limit=10)assert page.app_ids == []diff --git a/api/tests/unit_tests/services/knowledge/test_dataset_adapters.py b/api/tests/unit_tests/services/knowledge/test_dataset_adapters.pyindex dce7c1d5242..f9fb45e2a01 100644--- a/api/tests/unit_tests/services/knowledge/test_dataset_adapters.py+++ b/api/tests/unit_tests/services/knowledge/test_dataset_adapters.py@@ -11,7 +11,6 @@ from controllers.console.datasets.datasets import (DatasetQueryListResponse,RelatedAppListResponse,)-from extensions.application_services.app import AppServicesfrom machinery.context import RequestContextfrom models import Account, App, Dataset, Documentfrom models.account import Tenant, TenantAccountJoin, TenantAccountRole@@ -23,6 +22,7 @@ from models.dataset import (DocumentSegment,)from models.enums import CreatorUserRole, DatasetQuerySource, IndexingStatus, SegmentStatus+from repositories.app.console_repository import ConsoleAppRepositoryfrom services.enterprise import rbac_servicefrom services.knowledge.dataset_access import DatasetNotFoundErrorfrom services.knowledge.datasets.adapters import SQLAlchemyDatasetOperations@@ -78,7 +78,6 @@ def operations(sqlite_session_factory: sessionmaker[Session],monkeypatch: pytest.MonkeyPatch,application_tags: TagApplicationService,- app_services: AppServices,rbac_domain: RBACDomain,) -> SQLAlchemyDatasetOperations:apply_config_overrides(monkeypatch, RBAC_ENABLED=False)@@ -99,7 +98,7 @@ def operations(return SQLAlchemyDatasetOperations(session_factory=sqlite_session_factory,tags=application_tags,- app_queries=app_services.queries,+ app_queries=ConsoleAppRepository(session_factory=sqlite_session_factory),members=rbac_domain.rbac.members,)diff --git a/api/tests/unit_tests/services/test_app_dsl_service.py b/api/tests/unit_tests/services/test_app_dsl_service.pyindex 66d2f0067b4..99ba986aa54 100644--- a/api/tests/unit_tests/services/test_app_dsl_service.py+++ b/api/tests/unit_tests/services/test_app_dsl_service.py@@ -929,12 +929,9 @@ def test_import_app_reraises_permission_denial_instead_of_failed_result(def test_append_workflow_export_data_reports_missing_selected_workflow(- monkeypatch: pytest.MonkeyPatch, unbound_session: Session+ sqlite_session: Session,) -> None:workflow_id = "11111111-1111-4111-8111-111111111111"- workflow_service = Mock()- workflow_service.get_draft_workflow.return_value = None- monkeypatch.setattr("services.app_dsl_service.WorkflowService", Mock(return_value=workflow_service))app = _app(app_id="app-1", tenant_id="tenant-1")with pytest.raises(WorkflowNotFoundError, match=f"Workflow version not found. Workflow ID: {workflow_id}"):@@ -942,7 +939,7 @@ def test_append_workflow_export_data_reports_missing_selected_workflow(export_data={},app_model=app,include_secret=False,- session=unbound_session,+ session=sqlite_session,workflow_id=workflow_id,)diff --git a/api/tests/unit_tests/services/test_app_service.py b/api/tests/unit_tests/services/test_app_service.pyindex 10bb7013173..48fe5e2767f 100644--- a/api/tests/unit_tests/services/test_app_service.py+++ b/api/tests/unit_tests/services/test_app_service.py@@ -436,12 +436,8 @@ def test_unpublished_agent_app_access_cannot_be_enabled(assert commits == []-class TestOpenapiVisibilityHelpers:- """Coverage for the session-injected, openapi-visibility-scoped- ``AppService`` getters used by ``/openapi/v1/apps*``. These helpers- centralise the "row exists + status normal + openapi-visibility- gate passes" check so the controller can stay free of SQL.- """+class TestAppLookup:+ """The auth pipeline's app lookup preserves status and API enablement signals."""def test_get_app_by_id_is_plain_session_get(self, sqlite_session: Session):"""``get_app_by_id`` must NOT apply status / visibility filters@@ -457,56 +453,6 @@ class TestOpenapiVisibilityHelpers:def test_get_app_by_id_returns_none_when_missing(self, sqlite_session: Session):assert AppService.get_app_by_id(str(uuid4()), sqlite_session) is None- def test_get_visible_app_by_id_returns_app_when_visible(self, sqlite_session: Session):- app = _persist_app(sqlite_session, tenant_id=str(uuid4()))-- with patch("services.app_service.is_openapi_visible", return_value=True):- assert AppService.get_visible_app_by_id(app.id, sqlite_session) is app-- def test_get_visible_app_by_id_returns_none_when_row_missing(self, sqlite_session: Session):- assert AppService.get_visible_app_by_id(str(uuid4()), sqlite_session) is None-- def test_get_visible_app_by_id_returns_none_when_status_not_normal(self, sqlite_session: Session):- """Soft-deleted/archived rows must not surface on the openapi- surface — the helper hides them by returning ``None``.- """- app = _persist_app(sqlite_session, tenant_id=str(uuid4()))- app.status = "archived" # type: ignore[assignment]-- with patch("services.app_service.is_openapi_visible", return_value=True):- assert AppService.get_visible_app_by_id(app.id, sqlite_session) is None-- def test_get_visible_app_by_id_returns_none_when_visibility_gate_rejects(self, sqlite_session: Session):- """``is_openapi_visible`` is the per-row counterpart to- ``apply_openapi_gate`` — when it returns False the helper must- treat the row as invisible (not "found but unauthorized").- """- app = _persist_app(sqlite_session, tenant_id=str(uuid4()))-- with patch("services.app_service.is_openapi_visible", return_value=False):- assert AppService.get_visible_app_by_id(app.id, sqlite_session) is None-- def test_find_visible_apps_by_ids_short_circuits_on_empty_input(self, unbound_session: Session):- """Empty id list must not emit ``WHERE id IN ()`` — Postgres- rejects empty IN lists and the call is a guaranteed no-op- anyway. The helper returns ``[]`` without touching the session.- """- assert AppService.find_visible_apps_by_ids([], unbound_session) == []-- def test_find_visible_apps_by_ids_passes_through_visibility_gate(self, sqlite_session: Session):- """Bulk fetch routes through ``apply_openapi_gate`` exactly once- and materialises the scalar rows. **No** status filter is- applied here — the EE permitted-external pipeline filters- non-normal hits in Python so its page count stays anchored.- """- rows = [_persist_app(sqlite_session, tenant_id=str(uuid4())) for _ in range(2)]-- with patch("services.app_service.apply_openapi_gate", side_effect=lambda q: q) as gate:- out = AppService.find_visible_apps_by_ids([app.id for app in rows], sqlite_session)-- assert {app.id for app in out} == {app.id for app in rows}- gate.assert_called_once()-def test_get_recent_apps_uses_one_tenant_scoped_projection_query(sqlite_session: Session) -> None:tenant_id = str(uuid4())diff --git a/api/tests/unit_tests/services/test_end_user_query_service.py b/api/tests/unit_tests/services/test_end_user_query_service.pyindex 2d2b256a2ab..47a0dc90e62 100644--- a/api/tests/unit_tests/services/test_end_user_query_service.py+++ b/api/tests/unit_tests/services/test_end_user_query_service.py@@ -2,13 +2,13 @@ from datetime import datetimeimport pytest-from machinery.context import ServiceApiRequestContext+from machinery.context import AppRequestContextfrom services.app_scoped_end_user_query_service import AppScopedEndUserNotFoundError, AppScopedEndUserQueryServicefrom services.entities.app_scoped_end_user_entities import AppScopedEndUserRecord-def _context() -> ServiceApiRequestContext:- return ServiceApiRequestContext(+def _context() -> AppRequestContext:+ return AppRequestContext(tenant_id="workspace-1",app_id="app-1",)diff --git a/api/tests/unit_tests/services/test_workflow_service.py b/api/tests/unit_tests/services/test_workflow_service.pyindex 492e645391b..3b15a5f671d 100644--- a/api/tests/unit_tests/services/test_workflow_service.py+++ b/api/tests/unit_tests/services/test_workflow_service.py@@ -321,37 +321,21 @@ class TestWorkflowService:assert result is None- def test_get_draft_workflow_with_workflow_id(self, workflow_service: WorkflowService, sqlite_session: Session):- """Test get_draft_workflow with workflow_id calls get_published_workflow_by_id."""+ # ==================== Get Published Workflow Tests ====================+ # These tests verify retrieval of published workflows (versioned snapshots)++ def test_get_published_workflow_by_id_reuses_provided_session(self, sqlite_session: Session):+ """Published lookup sees uncommitted rows through the caller's session."""app = TestWorkflowAssociatedDataFactory.create_app()workflow_id = "workflow-123"workflow = TestWorkflowAssociatedDataFactory.create_workflow(workflow_id=workflow_id, version="v1")sqlite_session.add(workflow)- sqlite_session.commit()+ sqlite_session.flush()- result = workflow_service.get_draft_workflow(app, workflow_id=workflow_id, session=sqlite_session)+ result = WorkflowService.get_published_workflow_by_id(app, workflow_id, session=sqlite_session)assert result is workflow- def test_get_draft_workflow_with_workflow_id_reuses_provided_session(- self, workflow_service: WorkflowService, sqlite_session: Session- ):- """Test get_draft_workflow passes an injected session to published workflow lookup."""- app = TestWorkflowAssociatedDataFactory.create_app()- workflow_id = "workflow-123"- mock_workflow = TestWorkflowAssociatedDataFactory.create_workflow(version="v1")-- with patch.object(- workflow_service, "get_published_workflow_by_id", return_value=mock_workflow- ) as mock_get_published:- result = workflow_service.get_draft_workflow(app, workflow_id=workflow_id, session=sqlite_session)-- assert result == mock_workflow- mock_get_published.assert_called_once_with(app, workflow_id, session=sqlite_session)-- # ==================== Get Published Workflow Tests ====================- # These tests verify retrieval of published workflows (versioned snapshots)-def test_get_published_workflow_by_id_success(self, workflow_service: WorkflowService, sqlite_session: Session):"""Test get_published_workflow_by_id returns published workflow."""app = TestWorkflowAssociatedDataFactory.create_app()