Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

feat(api): add inner API for enterprise admin app list and detail (#44044)

Yunlu Wen734a9ea74dea
diff --git a/api/controllers/inner_api/__init__.py b/api/controllers/inner_api/__init__.py
index 9fac0a6d1f7..4d62be5302f 100644
--- a/api/controllers/inner_api/__init__.py
+++ b/api/controllers/inner_api/__init__.py
@@ -30,6 +30,7 @@ from .agent import files as _agent_files
from .agent import llm as _agent_llm
from .agent import runtime_usage as _agent_runtime_usage
from .agent import tools as _agent_tools
+from .app import app as _app_app
from .app import dsl as _app_dsl
from .app import file_grants as _app_file_grants
from .knowledge import retrieval as _knowledge_retrieval
@@ -46,6 +47,7 @@ __all__ = [
"_agent_llm",
"_agent_runtime_usage",
"_agent_tools",
+ "_app_app",
"_app_dsl",
"_app_file_grants",
"_knowledge_retrieval",
diff --git a/api/controllers/inner_api/app/app.py b/api/controllers/inner_api/app/app.py
new file mode 100644
index 00000000000..b1b325ba444
--- /dev/null
+++ b/api/controllers/inner_api/app/app.py
@@ -0,0 +1,317 @@
+"""Inner API endpoints for the enterprise admin app list and app detail.
+
+Called by the enterprise admin-api service. The list covers Studio-visible apps
+across all workspaces with their publish state and invocation count; enterprise
+joins its own data onto it by app id. The detail adds what only CE owns: the
+app's published version, access points, and invocations.
+"""
+
+from http import HTTPStatus
+from typing import Literal
+from uuid import UUID
+
+from flask_restx import Resource
+from pydantic import BaseModel, Field, ValidationError, field_validator
+from werkzeug.exceptions import BadRequest
+
+from controllers.common.fields import SimpleMessageResponse
+from controllers.common.schema import (
+ query_params_from_model,
+ query_params_from_request,
+ register_response_schema_models,
+)
+from controllers.console.wraps import setup_required
+from controllers.inner_api import inner_api_ns
+from controllers.inner_api.wraps import enterprise_inner_api_only
+from extensions.ext_application_services import application_services
+from fields.base import ResponseModel
+from libs.helper import to_timestamp
+from models.model import AppMode
+from services.app.enterprise_app_service import (
+ EnterpriseAppApi,
+ EnterpriseAppCreator,
+ EnterpriseAppListParams,
+ EnterpriseAppMCPServer,
+ EnterpriseAppPublishedVersion,
+ EnterpriseAppSite,
+ EnterpriseAppTrigger,
+)
+
+EnterpriseAppListMode = Literal["completion", "workflow", "chat", "advanced-chat", "agent-chat", "agent"]
+APP_LIST_QUERY_ARRAY_FIELDS = ("workspace_ids", "modes")
+
+
+class EnterpriseAppListQuery(BaseModel):
+ page: int = Field(default=1, ge=1, le=99999, description="Page number (1-99999)")
+ limit: int = Field(default=20, ge=1, le=100, description="Page size (1-100)")
+ workspace_ids: list[UUID] = Field(default_factory=list, description="Filter by workspace IDs (repeatable)")
+ modes: list[EnterpriseAppListMode] = Field(default_factory=list, description="Filter by app modes (repeatable)")
+ name: str | None = Field(default=None, max_length=255, description="Filter by app name substring")
+ sort_by: Literal["created_at", "name"] = Field(default="created_at", description="Sort field")
+ sort_order: Literal["asc", "desc"] = Field(default="desc", description="Sort direction")
+
+ @field_validator("name", mode="before")
+ @classmethod
+ def blank_name_as_none(cls, value: object) -> object:
+ return value.strip() or None if isinstance(value, str) else value
+
+
+class EnterpriseAppCreatorResponse(ResponseModel):
+ id: str
+ name: str
+ email: str
+
+
+class EnterpriseAppResponse(ResponseModel):
+ id: str
+ name: str
+ description: str
+ mode: str
+ icon_type: str | None
+ icon: str | None
+ icon_background: str | None
+ workspace_id: str
+ workspace_name: str | None
+ created_by: EnterpriseAppCreatorResponse | None
+ created_at: int
+ updated_at: int
+
+
+_INVOCATION_COUNT_DESCRIPTION = (
+ "Invocations in the last 24h: published workflow runs (app-run, webhook, schedule, plugin) for "
+ "workflow and advanced-chat apps, non-debugger messages for other apps"
+)
+
+
+_TRIGGER_ENTRY_ACCESS_DESCRIPTION = (
+ "Null when the published workflow has a trigger entry, since trigger-entry workflows cannot be run through "
+ "Web App, Service API, or MCP"
+)
+
+
+class EnterpriseAppListItemResponse(EnterpriseAppResponse):
+ published: bool = Field(description="Whether the app detail reports a published_version")
+ invocation_count_24h: int = Field(description=_INVOCATION_COUNT_DESCRIPTION)
+
+
+class EnterpriseAppPaginationResponse(ResponseModel):
+ page: int
+ limit: int
+ total: int
+ has_more: bool
+ data: list[EnterpriseAppListItemResponse]
+
+
+class EnterpriseAppPublishedVersionResponse(ResponseModel):
+ id: str
+ version: str | None = Field(description="Workflow version string; null for Agent config snapshots")
+ version_number: int | None = Field(
+ description="The #N shown in Studio version history; null for unnumbered legacy workflows"
+ )
+ marked_name: str | None = Field(description="Workflow version name; null for Agent config snapshots")
+ marked_comment: str | None = Field(description="Workflow version comment or Agent snapshot version note")
+ created_by: EnterpriseAppCreatorResponse | None
+ published_at: int
+
+
+class EnterpriseAppSiteResponse(ResponseModel):
+ enabled: bool
+ code: str | None
+ app_base_url: str | None
+
+
+class EnterpriseAppApiResponse(ResponseModel):
+ enabled: bool
+ base_url: str | None
+ api_key_count: int
+
+
+class EnterpriseAppMCPServerResponse(ResponseModel):
+ status: str
+ server_code: str
+
+
+class EnterpriseAppTriggerResponse(ResponseModel):
+ id: str
+ node_id: str | None
+ title: str
+ trigger_type: str
+ provider_name: str | None
+ status: str
+ webhook_url: str | None
+
+
+class EnterpriseAppDetailResponse(EnterpriseAppResponse):
+ published_version: EnterpriseAppPublishedVersionResponse | None = Field(
+ description=(
+ "Version the app serves, unaffected by later unpublished draft edits; null when never published, "
+ "and always for chat, completion, and agent-chat apps"
+ )
+ )
+ published_version_count: int = Field(
+ description="Number of entries in the app's Studio version history; 0 for apps without versions"
+ )
+ site: EnterpriseAppSiteResponse | None = Field(description=_TRIGGER_ENTRY_ACCESS_DESCRIPTION)
+ api: EnterpriseAppApiResponse | None = Field(description=_TRIGGER_ENTRY_ACCESS_DESCRIPTION)
+ mcp_server: EnterpriseAppMCPServerResponse | None = Field(
+ description=f"{_TRIGGER_ENTRY_ACCESS_DESCRIPTION}, or when no MCP server was ever created"
+ )
+ triggers: list[EnterpriseAppTriggerResponse]
+ last_invoked_at: int | None = Field(
+ description="Latest invocation counted like invocation_count_24h, without the 24h limit"
+ )
+ invocation_count_24h: int = Field(description=_INVOCATION_COUNT_DESCRIPTION)
+ failed_invocation_count_24h: int = Field(
+ description=(
+ "Invocations counted in invocation_count_24h that ended failed or partial-succeeded (workflow runs) "
+ "or in error (messages); running and stopped runs are not failures"
+ ),
+ )
+
+
+register_response_schema_models(inner_api_ns, EnterpriseAppPaginationResponse, EnterpriseAppDetailResponse)
+
+
+def _creator_response(creator: EnterpriseAppCreator | None) -> EnterpriseAppCreatorResponse | None:
+ if creator is None:
+ return None
+ return EnterpriseAppCreatorResponse(id=creator.id, name=creator.name, email=creator.email)
+
+
+def _published_version_response(
+ version: EnterpriseAppPublishedVersion | None,
+) -> EnterpriseAppPublishedVersionResponse | None:
+ if version is None:
+ return None
+ return EnterpriseAppPublishedVersionResponse(
+ id=version.id,
+ version=version.version,
+ version_number=version.version_number,
+ marked_name=version.marked_name,
+ marked_comment=version.marked_comment,
+ created_by=_creator_response(version.created_by),
+ published_at=to_timestamp(version.published_at),
+ )
+
+
+def _site_response(site: EnterpriseAppSite | None) -> EnterpriseAppSiteResponse | None:
+ if site is None:
+ return None
+ return EnterpriseAppSiteResponse(enabled=site.enabled, code=site.code, app_base_url=site.app_base_url)
+
+
+def _api_response(api: EnterpriseAppApi | None) -> EnterpriseAppApiResponse | None:
+ if api is None:
+ return None
+ return EnterpriseAppApiResponse(enabled=api.enabled, base_url=api.base_url, api_key_count=api.api_key_count)
+
+
+def _mcp_server_response(server: EnterpriseAppMCPServer | None) -> EnterpriseAppMCPServerResponse | None:
+ if server is None:
+ return None
+ return EnterpriseAppMCPServerResponse(status=server.status, server_code=server.server_code)
+
+
+def _trigger_response(trigger: EnterpriseAppTrigger) -> EnterpriseAppTriggerResponse:
+ return EnterpriseAppTriggerResponse(
+ id=trigger.id,
+ node_id=trigger.node_id,
+ title=trigger.title,
+ trigger_type=trigger.trigger_type,
+ provider_name=trigger.provider_name,
+ status=trigger.status,
+ webhook_url=trigger.webhook_url,
+ )
+
+
+@inner_api_ns.route("/enterprise/apps")
+class EnterpriseAppList(Resource):
+ @setup_required
+ @enterprise_inner_api_only
+ @inner_api_ns.doc(
+ "enterprise_app_list",
+ params=query_params_from_model(EnterpriseAppListQuery),
+ responses={HTTPStatus.BAD_REQUEST: "Invalid query parameters"},
+ )
+ @inner_api_ns.response(HTTPStatus.OK, "Success", inner_api_ns.models[EnterpriseAppPaginationResponse.__name__])
+ def get(self):
+ """List Studio-visible apps across all workspaces."""
+ try:
+ query = query_params_from_request(EnterpriseAppListQuery, list_fields=APP_LIST_QUERY_ARRAY_FIELDS)
+ except ValidationError as exc:
+ raise BadRequest(str(exc)) from exc
+
+ result = application_services().apps.enterprise.list_apps(
+ EnterpriseAppListParams(
+ page=query.page,
+ limit=query.limit,
+ workspace_ids=[str(workspace_id) for workspace_id in query.workspace_ids],
+ modes=[AppMode(mode) for mode in query.modes],
+ name=query.name,
+ sort_by=query.sort_by,
+ sort_order=query.sort_order,
+ )
+ )
+ return EnterpriseAppPaginationResponse(
+ page=result.page,
+ limit=result.per_page,
+ total=result.total,
+ has_more=result.has_next,
+ data=[
+ EnterpriseAppListItemResponse(
+ id=item.app.id,
+ name=item.app.name,
+ description=item.app.description,
+ mode=item.app.mode,
+ icon_type=item.app.icon_type,
+ icon=item.app.icon,
+ icon_background=item.app.icon_background,
+ workspace_id=item.app.workspace_id,
+ workspace_name=item.app.workspace_name,
+ created_by=_creator_response(item.app.created_by),
+ created_at=to_timestamp(item.app.created_at),
+ updated_at=to_timestamp(item.app.updated_at),
+ published=item.published,
+ invocation_count_24h=item.invocation_count,
+ )
+ for item in result.items
+ ],
+ ).model_dump(mode="json")
+
+
+@inner_api_ns.route("/enterprise/apps/<uuid:app_id>")
+class EnterpriseAppDetail(Resource):
+ @setup_required
+ @enterprise_inner_api_only
+ @inner_api_ns.doc("enterprise_app_detail", responses={HTTPStatus.NOT_FOUND: "App not found"})
+ @inner_api_ns.response(HTTPStatus.OK, "Success", inner_api_ns.models[EnterpriseAppDetailResponse.__name__])
+ def get(self, app_id: UUID):
+ """Get a Studio-visible app with its published version, access points, and invocations."""
+ detail = application_services().apps.enterprise.get_app(str(app_id))
+ if detail is None:
+ return SimpleMessageResponse(message="app not found").model_dump(mode="json"), HTTPStatus.NOT_FOUND
+
+ app = detail.app
+ return EnterpriseAppDetailResponse(
+ id=app.id,
+ name=app.name,
+ description=app.description,
+ mode=app.mode,
+ icon_type=app.icon_type,
+ icon=app.icon,
+ icon_background=app.icon_background,
+ workspace_id=app.workspace_id,
+ workspace_name=app.workspace_name,
+ created_by=_creator_response(app.created_by),
+ created_at=to_timestamp(app.created_at),
+ updated_at=to_timestamp(app.updated_at),
+ published_version=_published_version_response(detail.published_version),
+ published_version_count=detail.published_version_count,
+ site=_site_response(detail.site),
+ api=_api_response(detail.api),
+ mcp_server=_mcp_server_response(detail.mcp_server),
+ triggers=[_trigger_response(trigger) for trigger in detail.triggers],
+ last_invoked_at=to_timestamp(detail.last_invoked_at),
+ invocation_count_24h=detail.invocation_count,
+ failed_invocation_count_24h=detail.failed_invocation_count,
+ ).model_dump(mode="json")
diff --git a/api/extensions/application_services/app.py b/api/extensions/application_services/app.py
index 05f2d03133c..8459402af50 100644
--- a/api/extensions/application_services/app.py
+++ b/api/extensions/application_services/app.py
@@ -4,11 +4,15 @@ from dataclasses import dataclass
from sqlalchemy.orm import Session, sessionmaker
+from configs import dify_config
+from libs.datetime_utils import naive_utc_now
from repositories.account.repository import SQLAlchemyAccountRepository
from repositories.app.api_key_repository import AppApiKeyRepository
from repositories.app.console_repository import ConsoleAppRepository
from repositories.app.dsl_import_repository import DslImportRepository
+from repositories.app.enterprise_app_repository import EnterpriseAppRepository
from repositories.app.export_repository import AppExportRepository
+from repositories.factory import DifyAPIRepositoryFactory
from repositories.workspace.workspace_repository import WorkspaceRepository
from services.agent.roster_package_exporter import RosterAgentPackageExporter
from services.agent.roster_package_importer import RosterAgentPackageImporter
@@ -18,6 +22,7 @@ from services.app.console_gateway import AppLifecycleGateway, AppTransferGateway
from services.app.console_service import ConsoleAppService
from services.app.creators_platform_gateway import CreatorsPlatformGateway
from services.app.discovery_gateway import EnterpriseAppDiscoveryAccess
+from services.app.enterprise_app_service import EnterpriseAppService
from services.app.export_service import AppExportService
from services.app.import_service import AppImportService
from services.app.query_service import AppDiscoveryService
@@ -37,6 +42,7 @@ class AppServices:
dsl_imports: DslImportService
discovery: AppDiscoveryService
console: ConsoleAppService
+ enterprise: EnterpriseAppService
def build_app_services(
@@ -74,6 +80,15 @@ def build_app_services(
tracing=OpsTraceManagerGateway(),
lifecycle=AppLifecycleGateway(session_factory=database_client),
),
+ enterprise=EnterpriseAppService(
+ apps=EnterpriseAppRepository(
+ session_factory=database_client,
+ app_web_url=dify_config.APP_WEB_URL,
+ service_api_url=dify_config.SERVICE_API_URL,
+ ),
+ workflow_runs=DifyAPIRepositoryFactory.create_api_workflow_run_repository(session_maker=database_client),
+ now=naive_utc_now,
+ ),
)
diff --git a/api/extensions/logstore/repositories/logstore_api_workflow_run_repository.py b/api/extensions/logstore/repositories/logstore_api_workflow_run_repository.py
index ac8a75d8890..59f4836f7f7 100644
--- a/api/extensions/logstore/repositories/logstore_api_workflow_run_repository.py
+++ b/api/extensions/logstore/repositories/logstore_api_workflow_run_repository.py
@@ -16,7 +16,7 @@ Key Features:
import logging
import os
import time
-from collections.abc import Sequence
+from collections.abc import Iterable, Mapping, Sequence
from datetime import UTC, datetime
from typing import Any, cast, override
@@ -30,7 +30,7 @@ from libs.datetime_utils import ensure_naive_utc, naive_utc_now
from libs.infinite_scroll_pagination import InfiniteScrollPagination
from models.enums import CreatorUserRole, WorkflowRunTriggeredFrom
from models.workflow import WorkflowRun, WorkflowType
-from repositories.api_workflow_run_repository import APIWorkflowRunRepository
+from repositories.api_workflow_run_repository import APIWorkflowRunRepository, AppWorkflowRunStats
from repositories.types import (
AverageInteractionStats,
DailyRunsStats,
@@ -603,6 +603,124 @@ class LogstoreAPIWorkflowRunRepository(APIWorkflowRunRepository):
logger.exception("Failed to get workflow runs count")
raise
+ @override
+ def get_stats_by_app_ids(
+ self,
+ tenant_id_by_app_id: Mapping[str, str],
+ triggered_from: Sequence[WorkflowRunTriggeredFrom],
+ created_since: datetime,
+ ) -> dict[str, AppWorkflowRunStats]:
+ """
+ Combine two queries: the windowed counts need the latest version of each
+ run, while the newest start time does not and spans the whole history.
+ """
+ if not tenant_id_by_app_id:
+ return {}
+ status_counts = self._status_counts_by_app(tenant_id_by_app_id, triggered_from, created_since)
+ return {
+ app_id: AppWorkflowRunStats(status_counts=status_counts.get(app_id, {}), last_created_at=started_at)
+ for app_id, started_at in self._last_started_at_by_app(tenant_id_by_app_id, triggered_from).items()
+ }
+
+ def _status_counts_by_app(
+ self,
+ tenant_id_by_app_id: Mapping[str, str],
+ triggered_from: Sequence[WorkflowRunTriggeredFrom],
+ created_since: datetime,
+ ) -> dict[str, dict[WorkflowExecutionStatus, int]]:
+ """
+ Count runs per app and latest status.
+
+ Every log version of a run carries the run's started_at, and each one is
+ written after the run starts, so __time__ prunes the scan before the
+ window function picks the latest version.
+ """
+ # started_at is stored as naive UTC isoformat, so string comparison orders it chronologically.
+ since = escape_sql_string(created_since.isoformat())
+ since_unix = int(created_since.replace(tzinfo=UTC).timestamp())
+ sql = f"""
+ SELECT tenant_id, app_id, status, COUNT(*) AS count
+ FROM (
+ SELECT tenant_id, app_id, status,
+ ROW_NUMBER() OVER (PARTITION BY id ORDER BY log_version DESC) AS rn
+ FROM {AliyunLogStore.workflow_execution_logstore}
+ WHERE {self._app_run_filter(tenant_id_by_app_id, triggered_from)}
+ AND __time__ >= {since_unix}
+ AND started_at >= '{since}'
+ ) t
+ WHERE rn = 1
+ GROUP BY tenant_id, app_id, status
+ """
+ try:
+ results = self.logstore_client.execute_sql(
+ sql=sql, query="*", logstore=AliyunLogStore.workflow_execution_logstore
+ )
+ except Exception:
+ logger.exception("Failed to get workflow run status counts by app")
+ raise
+
+ counts: dict[str, dict[WorkflowExecutionStatus, int]] = {}
+ for row in results:
+ app_id = row.get("app_id")
+ if app_id not in tenant_id_by_app_id or tenant_id_by_app_id[app_id] != row.get("tenant_id"):
+ continue
+ try:
+ status = WorkflowExecutionStatus(str(row.get("status")))
+ except ValueError:
+ logger.warning("Invalid status value: %s, skipping", row.get("status"))
+ continue
+ counts.setdefault(app_id, {})[status] = safe_int(row.get("count", 0))
+ return counts
+
+ def _last_started_at_by_app(
+ self,
+ tenant_id_by_app_id: Mapping[str, str],
+ triggered_from: Sequence[WorkflowRunTriggeredFrom],
+ ) -> dict[str, datetime]:
+ """Every log version of a run carries the same started_at, so no deduplication is needed."""
+ sql = f"""
+ SELECT tenant_id, app_id, MAX(started_at) AS last_started_at
+ FROM {AliyunLogStore.workflow_execution_logstore}
+ WHERE {self._app_run_filter(tenant_id_by_app_id, triggered_from)}
+ AND started_at != ''
+ AND __time__ > 0
+ GROUP BY tenant_id, app_id
+ """
+ try:
+ results = self.logstore_client.execute_sql(
+ sql=sql, query="*", logstore=AliyunLogStore.workflow_execution_logstore
+ )
+ except Exception:
+ logger.exception("Failed to get last workflow run time by app")
+ raise
+
+ last_created_at: dict[str, datetime] = {}
+ for row in results:
+ app_id = row.get("app_id")
+ started_at = row.get("last_started_at")
+ if (
+ app_id in tenant_id_by_app_id
+ and tenant_id_by_app_id[app_id] == row.get("tenant_id")
+ and isinstance(started_at, str)
+ and started_at
+ ):
+ last_created_at[app_id] = ensure_naive_utc(datetime.fromisoformat(started_at))
+ return last_created_at
+
+ @staticmethod
+ def _app_run_filter(
+ tenant_id_by_app_id: Mapping[str, str], triggered_from: Sequence[WorkflowRunTriggeredFrom]
+ ) -> str:
+ def in_list(values: Iterable[str]) -> str:
+ return ", ".join(f"'{escape_identifier(value)}'" for value in values)
+
+ sources = ", ".join(f"'{escape_sql_string(source.value)}'" for source in triggered_from)
+ return (
+ f"tenant_id IN ({in_list(set(tenant_id_by_app_id.values()))})"
+ f" AND app_id IN ({in_list(tenant_id_by_app_id)})"
+ f" AND triggered_from IN ({sources})"
+ )
+
@override
def get_daily_runs_statistics(
self,
diff --git a/api/models/agent.py b/api/models/agent.py
index eb1fafae98a..d610680729c 100644
--- a/api/models/agent.py
+++ b/api/models/agent.py
@@ -98,6 +98,18 @@ class AgentConfigRevisionOperation(StrEnum):
IMPORT_PACKAGE = "import_package"
+# Revisions that add an entry to an Agent App's user-facing version history.
+# Imported Agent Apps also list the version their package seeded.
+AGENT_APP_VERSION_OPERATIONS = frozenset(
+ {
+ AgentConfigRevisionOperation.PUBLISH_DRAFT,
+ AgentConfigRevisionOperation.SAVE_NEW_VERSION,
+ AgentConfigRevisionOperation.SAVE_TO_ROSTER,
+ AgentConfigRevisionOperation.RESTORE_VERSION,
+ }
+)
+
+
class AgentConfigDraftType(StrEnum):
"""Editable Agent Soul draft workspace type."""
diff --git a/api/models/workflow.py b/api/models/workflow.py
index 42d17032762..f7ceb8b102b 100644
--- a/api/models/workflow.py
+++ b/api/models/workflow.py
@@ -23,7 +23,7 @@ from sqlalchemy import (
)
from sqlalchemy.orm import Mapped, mapped_column
-from core.trigger.constants import TRIGGER_PLUGIN_NODE_TYPE
+from core.trigger.constants import TRIGGER_PLUGIN_NODE_TYPE, is_trigger_node_type
from core.workflow.environment_variables import load_environment_variables
from core.workflow.human_input_adapter import adapt_node_config_for_graph
from core.workflow.llm_environment_variable import LLMEnvironmentVariable, dump_environment_variable
@@ -513,6 +513,13 @@ class Workflow(Base): # bug
else:
yield from ((node["id"], node["data"]) for node in graph_dict["nodes"])
+ def has_trigger_node(self) -> bool:
+ """Whether the graph has a trigger entry, which rules out Web App, Service API, OpenAPI, and MCP runs."""
+ return any(
+ isinstance(node_type := node_data.get("type"), str) and is_trigger_node_type(node_type)
+ for _, node_data in self.walk_nodes()
+ )
+
def user_input_form(self, to_old_structure: bool = False) -> list[Any]:
# get start node from graph
if not self.graph:
diff --git a/api/repositories/api_workflow_run_repository.py b/api/repositories/api_workflow_run_repository.py
index cd282fdbdfb..1314dba318e 100644
--- a/api/repositories/api_workflow_run_repository.py
+++ b/api/repositories/api_workflow_run_repository.py
@@ -34,7 +34,7 @@ Example:
```
"""
-from collections.abc import Callable, Sequence
+from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
from datetime import datetime
from typing import Protocol, TypedDict
@@ -43,7 +43,7 @@ from sqlalchemy.orm import Session
from core.workflow.nodes.human_input.pause_reason import PauseReason as DifyPauseReason
from graphon.entities.pause_reason import PauseReason as GraphonPauseReason
-from graphon.enums import WorkflowType
+from graphon.enums import WorkflowExecutionStatus, WorkflowType
from libs.infinite_scroll_pagination import InfiniteScrollPagination
from models.enums import WorkflowRunTriggeredFrom
from models.workflow import WorkflowAppLog, WorkflowArchiveLog, WorkflowPause, WorkflowPauseReason, WorkflowRun
@@ -81,6 +81,16 @@ class WorkflowRunCleanupRef:
created_at: datetime
+@dataclass(frozen=True)
+class AppWorkflowRunStats:
+ """Runs of one app, limited to the requested trigger sources."""
+
+ # Runs created at or after the requested time, by current status.
+ status_counts: Mapping[WorkflowExecutionStatus, int]
+ # Naive UTC creation time of the newest run, with no time limit.
+ last_created_at: datetime
+
+
class APIWorkflowRunRepository(Protocol):
"""
Protocol for service-layer WorkflowRun repository operations.
@@ -209,6 +219,25 @@ class APIWorkflowRunRepository(Protocol):
"""
...
+ def get_stats_by_app_ids(
+ self,
+ tenant_id_by_app_id: Mapping[str, str],
+ triggered_from: Sequence[WorkflowRunTriggeredFrom],
+ created_since: datetime,
+ ) -> dict[str, AppWorkflowRunStats]:
+ """
+ Summarize runs for several apps at once.
+
+ Args:
+ tenant_id_by_app_id: App ids to summarize, each mapped to its owning tenant id
+ triggered_from: Trigger sources to include
+ created_since: Naive UTC lower bound for AppWorkflowRunStats.status_counts
+
+ Returns:
+ Stats keyed by app id; apps without matching runs are absent
+ """
+ ...
+
def get_expired_runs_batch(
self,
tenant_id: str,
diff --git a/api/repositories/app/enterprise_app_repository.py b/api/repositories/app/enterprise_app_repository.py
new file mode 100644
index 00000000000..64756362646
--- /dev/null
+++ b/api/repositories/app/enterprise_app_repository.py
@@ -0,0 +1,466 @@
+"""Own the read Session for the enterprise cross-workspace app reads.
+
+Workflow runs are read through ``APIWorkflowRunRepository`` by the service,
+because deployments may keep them outside the database. The reads here that
+belong to other domains (workflows, Agents, sites, API tokens, MCP servers,
+triggers, messages) query those tables directly until each domain owns a
+repository that can serve them.
+"""
+
+from collections.abc import Sequence
+from datetime import datetime
+from typing import override
+
+import sqlalchemy as sa
+from sqlalchemy.orm import InstrumentedAttribute, Session, sessionmaker
+
+from core.agent.publish_visibility import (
+ agent_has_workflow_callable_active_snapshot,
+ workflow_callable_active_snapshot_filter,
+)
+from libs.helper import escape_like_pattern
+from libs.pagination import PaginatedResult, clamp_pagination
+from libs.url_utils import normalize_api_base_url
+from models import Account, Tenant
+from models.agent import (
+ AGENT_APP_VERSION_OPERATIONS,
+ APP_BACKED_AGENT_SOURCES,
+ Agent,
+ AgentConfigRevision,
+ AgentConfigRevisionOperation,
+ AgentConfigSnapshot,
+ AgentScope,
+ AgentSource,
+ AgentStatus,
+)
+from models.enums import ApiTokenType, AppStatus, AppTriggerType, InvokeFrom, MessageStatus
+from models.model import ApiToken, App, AppMCPServer, AppMode, Message, Site
+from models.trigger import AppTrigger, WorkflowWebhookTrigger
+from models.workflow import Workflow
+from services.app.enterprise_app_service import (
+ WORKFLOW_APP_MODES,
+ EnterpriseAppApi,
+ EnterpriseAppCreator,
+ EnterpriseAppListEntry,
+ EnterpriseAppListParams,
+ EnterpriseAppMCPServer,
+ EnterpriseAppMessageStats,
+ EnterpriseAppPublishedVersion,
+ EnterpriseAppRecord,
+ EnterpriseAppSite,
+ EnterpriseAppStore,
+ EnterpriseAppSummary,
+ EnterpriseAppTrigger,
+)
+from services.entities.app_entities import RECENT_APP_MODES
+
+# App modes a Studio user can open from the app list.
+ENTERPRISE_APP_LIST_MODES: tuple[AppMode, ...] = (*RECENT_APP_MODES, AppMode.AGENT)
+_NON_DEBUGGER_MESSAGE = Message.invoke_from != InvokeFrom.DEBUGGER
+
+# Outer joins: the workspace and creator columns are None at runtime when the row is missing.
+_SummaryRow = tuple[App, str, str, str, str]
+
+
+def _creator(account_id: str | None, name: str | None, email: str | None) -> EnterpriseAppCreator | None:
+ """Build a creator from outer-joined Account columns, which are all None when the row is missing."""
+ if account_id is None or name is None or email is None:
+ return None
+ return EnterpriseAppCreator(id=account_id, name=name, email=email)
+
+
+def _roster_agent_condition(
+ tenant_id: sa.ColumnElement[str] | InstrumentedAttribute[str] | str,
+ app_id: sa.ColumnElement[str] | InstrumentedAttribute[str] | str,
+) -> sa.ColumnElement[bool]:
+ """Match the active roster Agent an Agent App is bound to."""
+ return sa.and_(
+ Agent.tenant_id == tenant_id,
+ Agent.app_id == app_id,
+ Agent.scope == AgentScope.ROSTER,
+ Agent.status == AgentStatus.ACTIVE,
+ )
+
+
+def _studio_visible_condition() -> sa.ColumnElement[bool]:
+ """Match Studio's app list across all workspaces.
+
+ Agent Apps are listed only while bound to an active roster Agent, which also
+ excludes the hidden runtime backing Apps of workflow-only Agents.
+ """
+ roster_agent = (
+ sa.exists()
+ .where(
+ Agent.tenant_id == App.tenant_id,
+ Agent.app_id == App.id,
+ Agent.scope == AgentScope.ROSTER,
+ Agent.source.in_(APP_BACKED_AGENT_SOURCES),
+ Agent.status == AgentStatus.ACTIVE,
+ )
+ .correlate(App)
+ )
+ return sa.and_(
+ App.is_universal.is_(False),
+ App.status == AppStatus.NORMAL,
+ App.mode.in_(ENTERPRISE_APP_LIST_MODES),
+ sa.or_(App.mode != AppMode.AGENT, roster_agent),
+ )
+
+
+def _summary_query() -> sa.Select[_SummaryRow]:
+ # TODO: read workspace names and creators through the workspace and account
+ # domain repositories once they can serve batch lookups.
+ return (
+ sa.select(App, Tenant.name, Account.id, Account.name, Account.email)
+ .outerjoin(Tenant, Tenant.id == App.tenant_id)
+ .outerjoin(Account, Account.id == App.created_by)
+ .where(_studio_visible_condition())
+ )
+
+
+def _summary(row: sa.Row[_SummaryRow]) -> EnterpriseAppSummary:
+ app, workspace_name, creator_id, creator_name, creator_email = row
+ return EnterpriseAppSummary(
+ id=app.id,
+ name=app.name,
+ description=app.description,
+ mode=app.mode,
+ icon_type=app.icon_type,
+ icon=app.icon,
+ icon_background=app.icon_background,
+ workspace_id=app.tenant_id,
+ workspace_name=workspace_name,
+ created_by=_creator(creator_id, creator_name, creator_email),
+ created_at=app.created_at,
+ updated_at=app.updated_at,
+ )
+
+
+class EnterpriseAppRepository(EnterpriseAppStore):
+ def __init__(self, *, session_factory: sessionmaker[Session], app_web_url: str, service_api_url: str) -> None:
+ self._session_factory = session_factory
+ self._app_base_url = app_web_url.rstrip("/") or None
+ self._api_base_url = normalize_api_base_url(service_api_url) if service_api_url else None
+
+ @override
+ def list_apps(self, params: EnterpriseAppListParams) -> PaginatedResult[EnterpriseAppListEntry]:
+ filters = [_studio_visible_condition()]
+ if params.workspace_ids:
+ filters.append(App.tenant_id.in_(params.workspace_ids))
+ if params.modes:
+ filters.append(App.mode.in_(params.modes))
+ if params.name:
+ filters.append(App.name.ilike(f"%{escape_like_pattern(params.name)}%", escape="\\"))
+
+ sort_column = sa.func.lower(App.name) if params.sort_by == "name" else App.created_at
+ order_by = sort_column.asc() if params.sort_order == "asc" else sort_column.desc()
+ page, limit = clamp_pagination(params.page, params.limit)
+
+ with self._session_factory() as session:
+ total = session.scalar(sa.select(sa.func.count()).select_from(App).where(*filters)) or 0
+ rows = session.execute(
+ _summary_query()
+ .where(*filters)
+ # App id breaks ties so page boundaries stay stable.
+ .order_by(order_by, App.id.asc())
+ .offset((page - 1) * limit)
+ .limit(limit)
+ ).all()
+ published = self._published_app_ids(session, [row[0] for row in rows])
+ items = [EnterpriseAppListEntry(app=_summary(row), published=row[0].id in published) for row in rows]
+ return PaginatedResult(items=items, total=total, page=page, per_page=limit)
+
+ @override
+ def get_app(self, app_id: str) -> EnterpriseAppRecord | None:
+ with self._session_factory() as session:
+ row = session.execute(_summary_query().where(App.id == app_id)).one_or_none()
+ if row is None:
+ return None
+ app = row[0]
+ published_version, published_version_count = self._published_versions(session, app)
+ manual_entry = not self._published_trigger_entry(session, app)
+ return EnterpriseAppRecord(
+ app=_summary(row),
+ published_version=published_version,
+ published_version_count=published_version_count,
+ site=EnterpriseAppSite(
+ enabled=app.enable_site,
+ code=self._site_code(session, app),
+ app_base_url=self._app_base_url,
+ )
+ if manual_entry
+ else None,
+ api=EnterpriseAppApi(
+ enabled=app.enable_api,
+ base_url=self._api_base_url,
+ api_key_count=self._api_key_count(session, app),
+ )
+ if manual_entry
+ else None,
+ mcp_server=self._mcp_server(session, app) if manual_entry else None,
+ triggers=self._triggers(session, app),
+ )
+
+ @override
+ def get_message_stats_by_app_ids(
+ self, app_ids: Sequence[str], *, created_since: datetime
+ ) -> dict[str, EnterpriseAppMessageStats]:
+ # TODO: move to the message domain repository once it exists.
+ if not app_ids:
+ return {}
+ counts_stmt = (
+ sa.select(Message.app_id, Message.status, sa.func.count(Message.id))
+ .where(Message.app_id.in_(app_ids), _NON_DEBUGGER_MESSAGE, Message.created_at >= created_since)
+ .group_by(Message.app_id, Message.status)
+ )
+ # One LIMIT 1 lookup per app, so each stops at that app's newest message instead of scanning its history.
+ latest_messages = [
+ sa.select(Message.app_id, Message.created_at)
+ .where(Message.app_id == app_id, _NON_DEBUGGER_MESSAGE)
+ .order_by(Message.created_at.desc())
+ .limit(1)
+ .subquery()
+ for app_id in app_ids
+ ]
+ last_stmt = sa.union_all(*(sa.select(latest_message) for latest_message in latest_messages))
+ status_counts: dict[str, dict[MessageStatus, int]] = {}
+ with self._session_factory() as session:
+ for app_id, status, count in session.execute(counts_stmt):
+ status_counts.setdefault(app_id, {})[MessageStatus(status)] = int(count)
+ last_created_at: dict[str, datetime] = dict(session.execute(last_stmt).tuples().all())
+ return {
+ app_id: EnterpriseAppMessageStats(status_counts=status_counts.get(app_id, {}), last_created_at=created_at)
+ for app_id, created_at in last_created_at.items()
+ }
+
+ @staticmethod
+ def _published_trigger_entry(session: Session, app: App) -> bool:
+ """Whether the published workflow starts from a trigger, matching AppGenerateService's run check."""
+ # TODO: move to the workflow domain repository once it exists.
+ if app.mode != AppMode.WORKFLOW or not app.workflow_id:
+ return False
+ workflow = session.scalar(sa.select(Workflow).where(Workflow.id == app.workflow_id, Workflow.app_id == app.id))
+ return workflow is not None and workflow.has_trigger_node()
+
+ @staticmethod
+ def _site_code(session: Session, app: App) -> str | None:
+ # TODO: move to the site domain repository once it has a read side.
+ return session.scalar(sa.select(Site.code).where(Site.app_id == app.id).limit(1))
+
+ @staticmethod
+ def _api_key_count(session: Session, app: App) -> int:
+ # TODO: move to AppApiKeyRepository once it can count keys without loading the tokens.
+ return (
+ session.scalar(
+ sa.select(sa.func.count())
+ .select_from(ApiToken)
+ .where(ApiToken.app_id == app.id, ApiToken.type == ApiTokenType.APP)
+ )
+ or 0
+ )
+
+ @staticmethod
+ def _published_app_ids(session: Session, apps: Sequence[App]) -> set[str]:
+ """Batch form of the published_version check: ids whose detail reports a published version."""
+ # TODO: move to the workflow and Agent domain repositories once they exist.
+ workflow_app_ids = [app.id for app in apps if app.mode in WORKFLOW_APP_MODES]
+ agent_app_ids = [app.id for app in apps if app.mode == AppMode.AGENT]
+ published: set[str] = set()
+ if workflow_app_ids:
+ published.update(
+ session.scalars(
+ sa.select(App.id)
+ .join(Workflow, sa.and_(Workflow.id == App.workflow_id, Workflow.app_id == App.id))
+ .where(App.id.in_(workflow_app_ids))
+ )
+ )
+ if agent_app_ids:
+ published.update(
+ session.scalars(
+ sa.select(App.id)
+ .join(Agent, _roster_agent_condition(App.tenant_id, App.id))
+ .join(
+ AgentConfigSnapshot,
+ sa.and_(
+ AgentConfigSnapshot.id == Agent.active_config_snapshot_id,
+ AgentConfigSnapshot.agent_id == Agent.id,
+ ),
+ )
+ .where(App.id.in_(agent_app_ids), workflow_callable_active_snapshot_filter())
+ )
+ )
+ return published
+
+ @classmethod
+ def _published_versions(cls, session: Session, app: App) -> tuple[EnterpriseAppPublishedVersion | None, int]:
+ """Return the served version and the size of the version history Studio shows."""
+ if app.mode in WORKFLOW_APP_MODES:
+ return cls._published_workflow(session, app)
+ if app.mode == AppMode.AGENT:
+ return cls._published_agent_snapshot(session, app)
+ return None, 0
+
+ @staticmethod
+ def _published_workflow(session: Session, app: App) -> tuple[EnterpriseAppPublishedVersion | None, int]:
+ # TODO: move to the workflow domain repository once it exists.
+ count = (
+ session.scalar(
+ sa.select(sa.func.count())
+ .select_from(Workflow)
+ .where(
+ Workflow.tenant_id == app.tenant_id,
+ Workflow.app_id == app.id,
+ Workflow.version != Workflow.VERSION_DRAFT,
+ )
+ )
+ or 0
+ )
+ if not app.workflow_id:
+ return None, count
+ row = session.execute(
+ sa.select(
+ Workflow.id,
+ Workflow.version,
+ Workflow.version_number,
+ Workflow.marked_name,
+ Workflow.marked_comment,
+ Workflow.created_at,
+ Account.id,
+ Account.name,
+ Account.email,
+ )
+ .outerjoin(Account, Account.id == Workflow.created_by)
+ .where(Workflow.id == app.workflow_id, Workflow.app_id == app.id)
+ ).one_or_none()
+ if row is None:
+ return None, count
+ workflow_id, version, version_number, marked_name, marked_comment, created_at, *creator = row
+ return (
+ EnterpriseAppPublishedVersion(
+ id=workflow_id,
+ version=version,
+ version_number=version_number,
+ marked_name=marked_name,
+ marked_comment=marked_comment,
+ created_by=_creator(*creator),
+ published_at=created_at,
+ ),
+ count,
+ )
+
+ @staticmethod
+ def _published_agent_snapshot(session: Session, app: App) -> tuple[EnterpriseAppPublishedVersion | None, int]:
+ # TODO: move to the Agent domain repository once it exists.
+ agent = session.scalar(sa.select(Agent).where(_roster_agent_condition(app.tenant_id, app.id)).limit(1))
+ if agent is None:
+ return None, 0
+ agent_id, snapshot_id = agent.id, agent.active_config_snapshot_id
+ operations = (
+ AGENT_APP_VERSION_OPERATIONS | {AgentConfigRevisionOperation.IMPORT_PACKAGE}
+ if agent.source == AgentSource.IMPORTED
+ else AGENT_APP_VERSION_OPERATIONS
+ )
+ history = session.scalars(
+ sa.select(AgentConfigSnapshot.id)
+ .where(
+ AgentConfigSnapshot.tenant_id == app.tenant_id,
+ AgentConfigSnapshot.agent_id == agent_id,
+ AgentConfigSnapshot.id.in_(
+ sa.select(AgentConfigRevision.current_snapshot_id).where(
+ AgentConfigRevision.tenant_id == app.tenant_id,
+ AgentConfigRevision.agent_id == agent_id,
+ AgentConfigRevision.operation.in_(operations),
+ )
+ ),
+ )
+ .order_by(AgentConfigSnapshot.version.asc())
+ ).all()
+ # Draft edits do not revoke the live snapshot, while a never-published
+ # seed snapshot is not served; match the runtime check.
+ if not snapshot_id or not agent_has_workflow_callable_active_snapshot(session=session, agent=agent):
+ return None, len(history)
+ snapshot = session.execute(
+ sa.select(
+ AgentConfigSnapshot.version_note,
+ AgentConfigSnapshot.created_at,
+ Account.id,
+ Account.name,
+ Account.email,
+ )
+ .outerjoin(Account, Account.id == AgentConfigSnapshot.created_by)
+ .where(
+ AgentConfigSnapshot.tenant_id == app.tenant_id,
+ AgentConfigSnapshot.agent_id == agent_id,
+ AgentConfigSnapshot.id == snapshot_id,
+ )
+ ).one_or_none()
+ if snapshot is None:
+ return None, len(history)
+ version_note, created_at, *creator = snapshot
+ # Restoring an older version re-serves an existing snapshot, so the
+ # latest revision pointing at it is when it went live.
+ published_at = session.scalar(
+ sa.select(sa.func.max(AgentConfigRevision.created_at)).where(
+ AgentConfigRevision.tenant_id == app.tenant_id,
+ AgentConfigRevision.agent_id == agent_id,
+ AgentConfigRevision.current_snapshot_id == snapshot_id,
+ )
+ )
+ # Studio numbers history entries from 1 in snapshot version order.
+ version_numbers = {history_id: number for number, history_id in enumerate(history, start=1)}
+ return (
+ EnterpriseAppPublishedVersion(
+ id=snapshot_id,
+ version=None,
+ version_number=version_numbers.get(snapshot_id),
+ marked_name=None,
+ marked_comment=version_note,
+ created_by=_creator(*creator),
+ published_at=published_at or created_at,
+ ),
+ len(history),
+ )
+
+ @staticmethod
+ def _mcp_server(session: Session, app: App) -> EnterpriseAppMCPServer | None:
+ # TODO: read through AppMCPServerRepository.find_server, which already returns status and server_code.
+ server = session.execute(
+ sa.select(AppMCPServer.status, AppMCPServer.server_code).where(
+ AppMCPServer.tenant_id == app.tenant_id, AppMCPServer.app_id == app.id
+ )
+ ).one_or_none()
+ return EnterpriseAppMCPServer(*server) if server else None
+
+ @staticmethod
+ def _triggers(session: Session, app: App) -> Sequence[EnterpriseAppTrigger]:
+ # TODO: move to the trigger domain repository once it exists.
+ if app.mode != AppMode.WORKFLOW:
+ return []
+ # Keyed loosely to match the nullable AppTrigger.node_id lookups below.
+ webhooks: dict[str | None, str] = {
+ webhook.node_id: webhook.webhook_url
+ for webhook in session.scalars(
+ sa.select(WorkflowWebhookTrigger).where(
+ WorkflowWebhookTrigger.tenant_id == app.tenant_id, WorkflowWebhookTrigger.app_id == app.id
+ )
+ )
+ }
+ triggers = session.scalars(
+ sa.select(AppTrigger)
+ .where(AppTrigger.tenant_id == app.tenant_id, AppTrigger.app_id == app.id)
+ .order_by(AppTrigger.created_at.desc(), AppTrigger.id.desc())
+ )
+ return [
+ EnterpriseAppTrigger(
+ id=trigger.id,
+ node_id=trigger.node_id,
+ title=trigger.title,
+ trigger_type=trigger.trigger_type,
+ provider_name=trigger.provider_name,
+ status=trigger.status,
+ webhook_url=(
+ webhooks.get(trigger.node_id) if trigger.trigger_type == AppTriggerType.TRIGGER_WEBHOOK else None
+ ),
+ )
+ for trigger in triggers
+ ]
diff --git a/api/repositories/sqlalchemy_api_workflow_run_repository.py b/api/repositories/sqlalchemy_api_workflow_run_repository.py
index 7ada8398837..e29bbbddc53 100644
--- a/api/repositories/sqlalchemy_api_workflow_run_repository.py
+++ b/api/repositories/sqlalchemy_api_workflow_run_repository.py
@@ -62,6 +62,7 @@ from models.human_input import HumanInputForm, HumanInputFormRecipient
from models.workflow import WorkflowAppLog, WorkflowArchiveLog, WorkflowPause, WorkflowPauseReason, WorkflowRun
from repositories.api_workflow_run_repository import (
APIWorkflowRunRepository,
+ AppWorkflowRunStats,
RunsWithRelatedCountsDict,
WorkflowRunCleanupRef,
)
@@ -379,6 +380,59 @@ class DifyAPISQLAlchemyWorkflowRunRepository(APIWorkflowRunRepository):
return {"total": total} | status_counts
+ @override
+ def get_stats_by_app_ids(
+ self,
+ tenant_id_by_app_id: Mapping[str, str],
+ triggered_from: Sequence[WorkflowRunTriggeredFrom],
+ created_since: datetime,
+ ) -> dict[str, AppWorkflowRunStats]:
+ if not tenant_id_by_app_id:
+ return {}
+ counts_stmt = (
+ select(WorkflowRun.tenant_id, WorkflowRun.app_id, WorkflowRun.status, func.count(WorkflowRun.id))
+ .where(
+ *self._app_run_conditions(tenant_id_by_app_id, triggered_from),
+ WorkflowRun.created_at >= created_since,
+ )
+ .group_by(WorkflowRun.tenant_id, WorkflowRun.app_id, WorkflowRun.status)
+ )
+ # One LIMIT 1 lookup per app, so each stops at that app's newest run instead of scanning its history.
+ latest_runs = [
+ select(WorkflowRun.app_id, WorkflowRun.created_at)
+ .where(
+ WorkflowRun.tenant_id == tenant_id,
+ WorkflowRun.app_id == app_id,
+ WorkflowRun.triggered_from.in_(triggered_from),
+ )
+ .order_by(WorkflowRun.created_at.desc())
+ .limit(1)
+ .subquery()
+ for app_id, tenant_id in tenant_id_by_app_id.items()
+ ]
+ last_stmt = sa.union_all(*(select(latest_run) for latest_run in latest_runs))
+ status_counts: dict[str, dict[WorkflowExecutionStatus, int]] = {}
+ with self._session_maker() as session:
+ for tenant_id, app_id, status, count in session.execute(counts_stmt):
+ # The IN filters match any tenant/app pairing, so keep only each app's own tenant.
+ if tenant_id_by_app_id[app_id] == tenant_id:
+ status_counts.setdefault(app_id, {})[WorkflowExecutionStatus(status)] = int(count)
+ last_created_at: dict[str, datetime] = dict(session.execute(last_stmt).tuples().all())
+ return {
+ app_id: AppWorkflowRunStats(status_counts=status_counts.get(app_id, {}), last_created_at=created_at)
+ for app_id, created_at in last_created_at.items()
+ }
+
+ @staticmethod
+ def _app_run_conditions(
+ tenant_id_by_app_id: Mapping[str, str], triggered_from: Sequence[WorkflowRunTriggeredFrom]
+ ) -> list[sa.ColumnElement[bool]]:
+ return [
+ WorkflowRun.tenant_id.in_(set(tenant_id_by_app_id.values())),
+ WorkflowRun.app_id.in_(list(tenant_id_by_app_id)),
+ WorkflowRun.triggered_from.in_(triggered_from),
+ ]
+
@override
def get_expired_runs_batch(
self,
diff --git a/api/services/agent/roster_service.py b/api/services/agent/roster_service.py
index 2f0b4e0295a..9dee3a7a53a 100644
--- a/api/services/agent/roster_service.py
+++ b/api/services/agent/roster_service.py
@@ -12,6 +12,7 @@ from core.app.entities.app_invoke_entities import InvokeFrom
from libs.datetime_utils import naive_utc_now
from libs.helper import to_timestamp
from models.agent import (
+ AGENT_APP_VERSION_OPERATIONS,
APP_BACKED_AGENT_SOURCES,
WORKFLOW_ONLY_AGENT_SOURCES,
Agent,
@@ -1308,12 +1309,7 @@ class AgentRosterService:
if agent.source == AgentSource.AGENT_APP or (
agent.source == AgentSource.IMPORTED and agent.scope == AgentScope.ROSTER and agent.app_id
):
- operations = {
- AgentConfigRevisionOperation.PUBLISH_DRAFT,
- AgentConfigRevisionOperation.SAVE_NEW_VERSION,
- AgentConfigRevisionOperation.SAVE_TO_ROSTER,
- AgentConfigRevisionOperation.RESTORE_VERSION,
- }
+ operations = set(AGENT_APP_VERSION_OPERATIONS)
if agent.source == AgentSource.IMPORTED:
operations.add(AgentConfigRevisionOperation.IMPORT_PACKAGE)
return operations
diff --git a/api/services/app/enterprise_app_service.py b/api/services/app/enterprise_app_service.py
new file mode 100644
index 00000000000..71921fcf51e
--- /dev/null
+++ b/api/services/app/enterprise_app_service.py
@@ -0,0 +1,297 @@
+"""Cross-workspace app reads for the trusted enterprise admin inner API.
+
+CE exposes the Studio-visible app metadata enterprise joins against by app id,
+plus what CE itself owns for each app: its published version, access points,
+and invocations.
+"""
+
+from collections.abc import Callable, Collection, Mapping, Sequence
+from dataclasses import dataclass
+from datetime import datetime, timedelta
+from typing import Literal, Protocol
+
+from graphon.enums import WorkflowExecutionStatus
+from libs.pagination import PaginatedResult
+from models.enums import MessageStatus, WorkflowRunTriggeredFrom
+from models.model import AppMode, IconType
+from repositories.api_workflow_run_repository import APIWorkflowRunRepository
+
+EnterpriseAppSortBy = Literal["created_at", "name"]
+EnterpriseAppSortOrder = Literal["asc", "desc"]
+
+# Window for the invocation counts shown on the admin list and detail pages.
+INVOCATION_WINDOW = timedelta(hours=24)
+
+
+@dataclass(frozen=True, slots=True)
+class EnterpriseAppListParams:
+ page: int
+ limit: int
+ # Empty sequences mean "no filter" for workspace_ids and modes.
+ workspace_ids: Sequence[str]
+ modes: Sequence[AppMode]
+ name: str | None
+ sort_by: EnterpriseAppSortBy
+ sort_order: EnterpriseAppSortOrder
+
+
+@dataclass(frozen=True, slots=True)
+class EnterpriseAppCreator:
+ id: str
+ name: str
+ email: str
+
+
+@dataclass(frozen=True, slots=True)
+class EnterpriseAppSummary:
+ id: str
+ name: str
+ description: str
+ mode: AppMode
+ icon_type: IconType | None
+ icon: str | None
+ icon_background: str | None
+ workspace_id: str
+ workspace_name: str | None
+ # None when the app has no recorded creator or the account was removed.
+ created_by: EnterpriseAppCreator | None
+ created_at: datetime
+ updated_at: datetime
+
+
+@dataclass(frozen=True, slots=True)
+class EnterpriseAppListItem:
+ """App state cheap enough to read for a whole list page."""
+
+ app: EnterpriseAppSummary
+ # True exactly when the detail reports a published_version.
+ published: bool
+ invocation_count: int
+
+
+@dataclass(frozen=True, slots=True)
+class EnterpriseAppPublishedVersion:
+ """The workflow or Agent config version the app currently serves."""
+
+ id: str
+ # Workflow version string; None for Agent config snapshots, which have none.
+ version: str | None
+ # The `#N` Studio shows in version history. None for workflows published
+ # before version numbering was introduced, and for Agent snapshots that
+ # are not in the user-facing history.
+ version_number: int | None
+ # Workflow version name; None for Agent snapshots, which have none.
+ marked_name: str | None
+ # Workflow version comment, or the Agent snapshot's version note.
+ marked_comment: str | None
+ # None when the publisher was not recorded or the account was removed.
+ created_by: EnterpriseAppCreator | None
+ published_at: datetime
+
+
+@dataclass(frozen=True, slots=True)
+class EnterpriseAppSite:
+ enabled: bool
+ # None when the app has no Site record.
+ code: str | None
+ # None when APP_WEB_URL is not configured; the request host is not used
+ # because inner API callers reach CE through an internal address.
+ app_base_url: str | None
+
+
+@dataclass(frozen=True, slots=True)
+class EnterpriseAppApi:
+ enabled: bool
+ # None when SERVICE_API_URL is not configured, for the same reason as Site.
+ base_url: str | None
+ api_key_count: int
+
+
+@dataclass(frozen=True, slots=True)
+class EnterpriseAppMCPServer:
+ # Only "active" servers accept MCP calls.
+ status: str
+ server_code: str
+
+
+@dataclass(frozen=True, slots=True)
+class EnterpriseAppTrigger:
+ id: str
+ node_id: str | None
+ title: str
+ trigger_type: str
+ provider_name: str | None
+ status: str
+ # Set only for webhook triggers.
+ webhook_url: str | None
+
+
+@dataclass(frozen=True, slots=True)
+class EnterpriseAppRecord:
+ """App state the app store reads; invocations come from run and message logs."""
+
+ app: EnterpriseAppSummary
+ # None when the app has never been published (workflow and Agent Apps) or
+ # has no version concept (legacy chat, completion, and agent-chat Apps).
+ # Agent Apps keep reporting the live snapshot after later draft edits, and
+ # report None while the active snapshot is a never-published seed, matching
+ # what the runtime serves.
+ published_version: EnterpriseAppPublishedVersion | None
+ # Size of the user-facing version history; 0 for Apps without versions.
+ published_version_count: int
+ # Web App, Service API, and MCP are None when the published workflow has a
+ # trigger entry, because such workflows cannot be run through them.
+ site: EnterpriseAppSite | None
+ api: EnterpriseAppApi | None
+ # Also None when no MCP server was ever created for the app.
+ mcp_server: EnterpriseAppMCPServer | None
+ triggers: Sequence[EnterpriseAppTrigger]
+
+
+@dataclass(frozen=True, slots=True)
+class EnterpriseAppDetail:
+ app: EnterpriseAppSummary
+ published_version: EnterpriseAppPublishedVersion | None
+ published_version_count: int
+ site: EnterpriseAppSite | None
+ api: EnterpriseAppApi | None
+ mcp_server: EnterpriseAppMCPServer | None
+ triggers: Sequence[EnterpriseAppTrigger]
+ # Debugger runs are excluded from all invocation fields. Unlike the counts,
+ # last_invoked_at is not limited to the invocation window.
+ last_invoked_at: datetime | None
+ invocation_count: int
+ failed_invocation_count: int
+
+
+@dataclass(frozen=True, slots=True)
+class EnterpriseAppListEntry:
+ app: EnterpriseAppSummary
+ # True exactly when the app's record has a published_version.
+ published: bool
+
+
+@dataclass(frozen=True, slots=True)
+class EnterpriseAppMessageStats:
+ # Messages created at or after the requested time, by status.
+ status_counts: Mapping[MessageStatus, int]
+ # Creation time of the newest message, with no time limit.
+ last_created_at: datetime
+
+
+class EnterpriseAppStore(Protocol):
+ def list_apps(self, params: EnterpriseAppListParams) -> PaginatedResult[EnterpriseAppListEntry]: ...
+
+ def get_app(self, app_id: str) -> EnterpriseAppRecord | None:
+ """Return None when the app does not exist or is hidden from Studio."""
+ ...
+
+ def get_message_stats_by_app_ids(
+ self, app_ids: Sequence[str], *, created_since: datetime
+ ) -> dict[str, EnterpriseAppMessageStats]:
+ """Summarize non-debugger messages per app; apps without messages are absent."""
+ ...
+
+
+# Workflow and advanced-chat Apps are invoked through workflow runs; every other
+# mode through messages.
+WORKFLOW_APP_MODES = frozenset({AppMode.WORKFLOW, AppMode.ADVANCED_CHAT})
+# Published workflow runs; debugging and RAG pipeline runs are excluded.
+INVOKED_RUN_SOURCES = (
+ WorkflowRunTriggeredFrom.APP_RUN,
+ WorkflowRunTriggeredFrom.WEBHOOK,
+ WorkflowRunTriggeredFrom.SCHEDULE,
+ WorkflowRunTriggeredFrom.PLUGIN,
+)
+# Every finished run that is neither succeeded nor stopped by the user.
+FAILED_RUN_STATUSES = frozenset({WorkflowExecutionStatus.FAILED, WorkflowExecutionStatus.PARTIAL_SUCCEEDED})
+FAILED_MESSAGE_STATUSES = frozenset({MessageStatus.ERROR})
+
+
+@dataclass(frozen=True, slots=True)
+class _Invocations:
+ count: int
+ failed_count: int
+ last_invoked_at: datetime | None
+
+
+_NO_INVOCATIONS = _Invocations(count=0, failed_count=0, last_invoked_at=None)
+
+
+def _invocations[StatusT](
+ status_counts: Mapping[StatusT, int], failed: Collection[StatusT], last_created_at: datetime
+) -> _Invocations:
+ return _Invocations(
+ count=sum(status_counts.values()),
+ failed_count=sum(count for status, count in status_counts.items() if status in failed),
+ last_invoked_at=last_created_at,
+ )
+
+
+class EnterpriseAppService:
+ """App queries across tenants, consumed by enterprise dashboard.
+
+ Invocation stats are collected from workflow runs and messages.
+ """
+
+ def __init__(
+ self, *, apps: EnterpriseAppStore, workflow_runs: APIWorkflowRunRepository, now: Callable[[], datetime]
+ ) -> None:
+ self._apps = apps
+ self._workflow_runs = workflow_runs
+ self._now = now
+
+ def list_apps(self, params: EnterpriseAppListParams) -> PaginatedResult[EnterpriseAppListItem]:
+ page = self._apps.list_apps(params)
+ invocations = self._invocations([entry.app for entry in page.items])
+ items = [
+ EnterpriseAppListItem(
+ app=entry.app,
+ published=entry.published,
+ invocation_count=invocations.get(entry.app.id, _NO_INVOCATIONS).count,
+ )
+ for entry in page.items
+ ]
+ return PaginatedResult(items=items, total=page.total, page=page.page, per_page=page.per_page)
+
+ def get_app(self, app_id: str) -> EnterpriseAppDetail | None:
+ record = self._apps.get_app(app_id)
+ if record is None:
+ return None
+ invocations = self._invocations([record.app]).get(record.app.id, _NO_INVOCATIONS)
+ return EnterpriseAppDetail(
+ app=record.app,
+ published_version=record.published_version,
+ published_version_count=record.published_version_count,
+ site=record.site,
+ api=record.api,
+ mcp_server=record.mcp_server,
+ triggers=record.triggers,
+ last_invoked_at=invocations.last_invoked_at,
+ invocation_count=invocations.count,
+ failed_invocation_count=invocations.failed_count,
+ )
+
+ def _invocations(self, apps: Sequence[EnterpriseAppSummary]) -> dict[str, _Invocations]:
+ """Read invocations: workflow runs for workflow Apps, messages otherwise."""
+ since = self._now() - INVOCATION_WINDOW
+ workflow_apps = {app.id: app.workspace_id for app in apps if app.mode in WORKFLOW_APP_MODES}
+ message_app_ids = [app.id for app in apps if app.mode not in WORKFLOW_APP_MODES]
+ result: dict[str, _Invocations] = {}
+ if workflow_apps:
+ run_stats = self._workflow_runs.get_stats_by_app_ids(workflow_apps, INVOKED_RUN_SOURCES, since)
+ result.update(
+ {
+ app_id: _invocations(stats.status_counts, FAILED_RUN_STATUSES, stats.last_created_at)
+ for app_id, stats in run_stats.items()
+ }
+ )
+ if message_app_ids:
+ message_stats = self._apps.get_message_stats_by_app_ids(message_app_ids, created_since=since)
+ result.update(
+ {
+ app_id: _invocations(stats.status_counts, FAILED_MESSAGE_STATUSES, stats.last_created_at)
+ for app_id, stats in message_stats.items()
+ }
+ )
+ return result
diff --git a/api/services/app_generate_service.py b/api/services/app_generate_service.py
index a22a7ba5d47..272eb29eb31 100644
--- a/api/services/app_generate_service.py
+++ b/api/services/app_generate_service.py
@@ -21,7 +21,6 @@ from core.app.features.rate_limiting import RateLimit
from core.app.features.rate_limiting.rate_limit import rate_limit_context
from core.app.layers.pause_state_persist_layer import PauseStateLayerConfig
from core.db import session_factory
-from core.trigger.constants import is_trigger_node_type
from enums import DeploymentEdition, QuotaType
from extensions.otel import AppGenerateHandler, trace_span
from models.model import Account, App, AppMode, EndUser
@@ -359,13 +358,8 @@ class AppGenerateService:
@staticmethod
def _ensure_workflow_service_mode_available(*, workflow: Workflow, invoke_from: InvokeFrom) -> None:
- if invoke_from not in _MANUAL_WORKFLOW_INVOKE_SOURCES:
- return
-
- for _, node_data in workflow.walk_nodes():
- node_type = node_data.get("type")
- if isinstance(node_type, str) and is_trigger_node_type(node_type):
- raise TriggerWorkflowServiceModeUnavailableError()
+ if invoke_from in _MANUAL_WORKFLOW_INVOKE_SOURCES and workflow.has_trigger_node():
+ raise TriggerWorkflowServiceModeUnavailableError()
@staticmethod
def _get_max_active_requests(app: App) -> int:
diff --git a/api/tests/unit_tests/controllers/inner_api/app/test_app.py b/api/tests/unit_tests/controllers/inner_api/app/test_app.py
new file mode 100644
index 00000000000..a8099744e15
--- /dev/null
+++ b/api/tests/unit_tests/controllers/inner_api/app/test_app.py
@@ -0,0 +1,718 @@
+"""Unit tests for the inner_api enterprise app list and detail endpoints.
+
+Auth/setup decorators are tested in test_auth_wraps.py; handler tests use inspect.unwrap() to bypass them.
+"""
+
+import inspect
+import json
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass
+from datetime import datetime, timedelta
+from decimal import Decimal
+from typing import Protocol, cast
+from uuid import UUID, uuid4
+
+import pytest
+from flask import Flask
+from sqlalchemy import select
+from sqlalchemy.orm import Session, sessionmaker
+from werkzeug.exceptions import BadRequest
+
+from controllers.inner_api.app.app import (
+ EnterpriseAppDetail,
+ EnterpriseAppDetailResponse,
+ EnterpriseAppList,
+ EnterpriseAppPaginationResponse,
+)
+from graphon.enums import WorkflowExecutionStatus
+from models import Account, App, Tenant
+from models.account import AccountStatus
+from models.agent import (
+ Agent,
+ AgentConfigRevision,
+ AgentConfigRevisionOperation,
+ AgentConfigSnapshot,
+ AgentScope,
+ AgentSource,
+ AgentStatus,
+)
+from models.enums import (
+ ApiTokenType,
+ AppTriggerStatus,
+ AppTriggerType,
+ ConversationFromSource,
+ CreatorUserRole,
+ CustomizeTokenStrategy,
+ InvokeFrom,
+ MessageStatus,
+ WorkflowRunTriggeredFrom,
+)
+from models.model import ApiToken, AppMCPServer, AppMode, Message, Site
+from models.trigger import AppTrigger, WorkflowWebhookTrigger
+from models.workflow import Workflow, WorkflowRun, WorkflowType
+from repositories.api_workflow_run_repository import APIWorkflowRunRepository, AppWorkflowRunStats
+from repositories.app.enterprise_app_repository import EnterpriseAppRepository
+from repositories.sqlalchemy_api_workflow_run_repository import DifyAPISQLAlchemyWorkflowRunRepository
+from services.app.enterprise_app_service import EnterpriseAppService
+
+WS_A = "11111111-1111-1111-1111-111111111111"
+WS_B = "22222222-2222-2222-2222-222222222222"
+NOW = datetime(2026, 10, 14, 12)
+
+
+class DocumentedView(Protocol):
+ __apidoc__: dict[str, dict[str, dict[str, object]]]
+
+
+@dataclass(frozen=True)
+class _Apps:
+ enterprise: EnterpriseAppService
+
+
+@dataclass(frozen=True)
+class _Services:
+ apps: _Apps
+
+
+def _install_service(
+ app: Flask,
+ session_factory: sessionmaker[Session],
+ monkeypatch: pytest.MonkeyPatch,
+ *,
+ app_web_url: str = "https://apps.example.com/",
+ service_api_url: str = "https://api.example.com",
+) -> None:
+ service = EnterpriseAppService(
+ apps=EnterpriseAppRepository(
+ session_factory=session_factory, app_web_url=app_web_url, service_api_url=service_api_url
+ ),
+ workflow_runs=DifyAPISQLAlchemyWorkflowRunRepository(session_factory),
+ now=lambda: NOW,
+ )
+ monkeypatch.setitem(app.extensions, "application_services", _Services(apps=_Apps(service)))
+
+
+def enterprise_apps(app: Flask, sqlite_session_factory: sessionmaker[Session], monkeypatch: pytest.MonkeyPatch) -> None:
+ _install_service(app, sqlite_session_factory, monkeypatch)
+
+
+def _app(tenant_id: str, name: str, *, mode: AppMode = AppMode.WORKFLOW, created_at: datetime, **kwargs: object) -> App:
+ app = App(
+ tenant_id=tenant_id,
+ name=name,
+ mode=mode,
+ enable_site=False,
+ enable_api=False,
+ created_at=created_at,
+ updated_at=created_at,
+ **kwargs,
+ )
+ app.id = str(uuid4())
+ return app
+
+
+def _agent(tenant_id: str, *, scope: AgentScope, status: AgentStatus = AgentStatus.ACTIVE, **kwargs: object) -> Agent:
+ return Agent(
+ tenant_id=tenant_id,
+ name=f"agent-{uuid4()}",
+ scope=scope,
+ source=AgentSource.AGENT_APP if scope == AgentScope.ROSTER else AgentSource.WORKFLOW,
+ status=status,
+ **kwargs,
+ )
+
+
+def _workflow(app: App, *, version: str, created_by: str, entry_node_type: str = "start", **kwargs: object) -> Workflow:
+ return Workflow(
+ tenant_id=app.tenant_id,
+ app_id=app.id,
+ type=WorkflowType.WORKFLOW,
+ version=version,
+ graph=json.dumps({"nodes": [{"id": "entry", "data": {"type": entry_node_type}}], "edges": []}),
+ features="{}",
+ environment_variables=[],
+ conversation_variables=[],
+ created_by=created_by,
+ **kwargs,
+ )
+
+
+def _snapshot(agent: Agent, version: int, created_at: datetime, **kwargs: object) -> AgentConfigSnapshot:
+ snapshot = AgentConfigSnapshot(
+ tenant_id=agent.tenant_id, agent_id=agent.id, version=version, config_snapshot={}, **kwargs
+ )
+ snapshot.created_at = created_at
+ return snapshot
+
+
+def _revision(
+ snapshot: AgentConfigSnapshot, revision: int, operation: AgentConfigRevisionOperation, created_at: datetime
+) -> AgentConfigRevision:
+ return AgentConfigRevision(
+ tenant_id=snapshot.tenant_id,
+ agent_id=snapshot.agent_id,
+ current_snapshot_id=snapshot.id,
+ revision=revision,
+ operation=operation,
+ created_at=created_at,
+ )
+
+
+def _publish_agent(session: Session, app_id: str) -> Agent:
+ """Publish one snapshot for the roster Agent bound to the App."""
+ agent = session.scalar(select(Agent).where(Agent.app_id == app_id))
+ assert agent is not None
+ snapshot = _snapshot(agent, 1, datetime(2026, 2, 1))
+ session.add(snapshot)
+ session.flush()
+ session.add(_revision(snapshot, 1, AgentConfigRevisionOperation.PUBLISH_DRAFT, datetime(2026, 2, 1)))
+ agent.active_config_snapshot_id = snapshot.id
+ agent.active_config_is_published = True
+ session.flush()
+ return agent
+
+
+def seeded(sqlite_session: Session) -> dict[str, str]:
+ creator = Account(name="Creator", email="[email protected]", status=AccountStatus.ACTIVE)
+ ws_a, ws_b = Tenant(name="Support"), Tenant(name="Sales")
+ ws_a.id, ws_b.id = WS_A, WS_B
+ sqlite_session.add_all([creator, ws_a, ws_b])
+ sqlite_session.flush()
+
+ alpha = _app(WS_A, "Alpha 100%", created_at=datetime(2026, 1, 1), created_by=creator.id, description="d")
+ beta = _app(WS_A, "beta", mode=AppMode.ADVANCED_CHAT, created_at=datetime(2026, 1, 3))
+ gamma = _app(WS_B, "Gamma", mode=AppMode.CHAT, created_at=datetime(2026, 1, 2), created_by=str(uuid4()))
+ roster = _app(WS_B, "Roster Agent", mode=AppMode.AGENT, created_at=datetime(2026, 1, 4))
+ archived = _app(WS_B, "Archived Agent", mode=AppMode.AGENT, created_at=datetime(2026, 1, 5))
+ backing = _app(WS_B, "Backing", mode=AppMode.AGENT, created_at=datetime(2026, 1, 6))
+ hidden = [
+ archived,
+ backing,
+ _app(WS_A, "Pipeline", mode=AppMode.RAG_PIPELINE, created_at=datetime(2026, 1, 7)),
+ _app(WS_A, "Channel", mode=AppMode.CHANNEL, created_at=datetime(2026, 1, 8)),
+ _app(WS_A, "Universal", created_at=datetime(2026, 1, 9), is_universal=True),
+ ]
+ sqlite_session.add_all([alpha, beta, gamma, roster, *hidden])
+ sqlite_session.add_all(
+ [
+ _agent(WS_B, scope=AgentScope.ROSTER, app_id=roster.id),
+ _agent(WS_B, scope=AgentScope.ROSTER, status=AgentStatus.ARCHIVED, app_id=archived.id),
+ _agent(WS_B, scope=AgentScope.WORKFLOW_ONLY, backing_app_id=backing.id),
+ ]
+ )
+ sqlite_session.commit()
+ return {"alpha": alpha.id, "beta": beta.id, "gamma": gamma.id, "roster": roster.id, "creator": creator.id}
+
+
+def _list(app: Flask, query: str = "") -> EnterpriseAppPaginationResponse:
+ with app.test_request_context(f"/enterprise/apps{query}"):
+ body = inspect.unwrap(EnterpriseAppList.get)(EnterpriseAppList())
+ return EnterpriseAppPaginationResponse.model_validate(body)
+
+
[email protected]("enterprise_apps")
+class TestEnterpriseAppList:
+ @pytest.mark.usefixtures("seeded")
+ def test_lists_studio_visible_apps_newest_first(self, app: Flask) -> None:
+ body = _list(app)
+
+ assert [item.name for item in body.data] == ["Roster Agent", "beta", "Gamma", "Alpha 100%"]
+ assert (body.page, body.limit, body.total, body.has_more) == (1, 20, 4, False)
+
+ def test_item_shape(self, app: Flask, seeded: dict[str, str]) -> None:
+ items = {item.name: item for item in _list(app).data}
+
+ assert items["Alpha 100%"].model_dump(mode="json") == {
+ "id": seeded["alpha"],
+ "name": "Alpha 100%",
+ "description": "d",
+ "mode": "workflow",
+ "icon_type": None,
+ "icon": None,
+ "icon_background": None,
+ "workspace_id": WS_A,
+ "workspace_name": "Support",
+ "created_by": {"id": seeded["creator"], "name": "Creator", "email": "[email protected]"},
+ "created_at": int(datetime(2026, 1, 1).timestamp()),
+ "updated_at": int(datetime(2026, 1, 1).timestamp()),
+ "published": False,
+ "invocation_count_24h": 0,
+ }
+ # A creator whose account no longer exists is reported as missing.
+ assert items["Gamma"].created_by is None
+
+ def test_item_publish_and_invocation_summary(
+ self, app: Flask, sqlite_session: Session, seeded: dict[str, str]
+ ) -> None:
+ workflow_app = sqlite_session.get(App, seeded["alpha"])
+ assert workflow_app is not None
+ published = _workflow(workflow_app, version="2026-01-02 00:00:00", created_by=seeded["creator"])
+ sqlite_session.add(published)
+ sqlite_session.flush()
+ workflow_app.workflow_id = published.id
+ # beta points at a workflow that no longer exists, so it is not published.
+ beta = sqlite_session.get(App, seeded["beta"])
+ assert beta is not None
+ beta.workflow_id = str(uuid4())
+ _publish_agent(sqlite_session, seeded["roster"])
+ sqlite_session.add_all(
+ [
+ _run(workflow_app, WorkflowExecutionStatus.SUCCEEDED, NOW - timedelta(hours=1)),
+ _run(workflow_app, WorkflowExecutionStatus.FAILED, NOW - timedelta(hours=2)),
+ _run(workflow_app, WorkflowExecutionStatus.SUCCEEDED, NOW - timedelta(hours=25)),
+ _run(
+ workflow_app,
+ WorkflowExecutionStatus.SUCCEEDED,
+ NOW - timedelta(minutes=1),
+ triggered_from=WorkflowRunTriggeredFrom.DEBUGGING,
+ ),
+ _message(seeded["gamma"], MessageStatus.NORMAL, NOW - timedelta(hours=1), InvokeFrom.WEB_APP),
+ _message(seeded["gamma"], MessageStatus.NORMAL, NOW - timedelta(hours=1), InvokeFrom.DEBUGGER),
+ _message(seeded["roster"], MessageStatus.ERROR, NOW - timedelta(hours=3), InvokeFrom.SERVICE_API),
+ ]
+ )
+ sqlite_session.commit()
+
+ items = _list(app).data
+
+ assert {item.name: (item.published, item.invocation_count_24h) for item in items} == {
+ "Alpha 100%": (True, 2),
+ "beta": (False, 0),
+ "Gamma": (False, 1),
+ "Roster Agent": (True, 1),
+ }
+ for item in items:
+ detail = _detail(app, item.id)
+ assert item.published == (detail.published_version is not None)
+ assert item.invocation_count_24h == detail.invocation_count_24h
+
+ def test_agent_draft_edits_keep_live_publication(
+ self, app: Flask, sqlite_session: Session, seeded: dict[str, str]
+ ) -> None:
+ agent = _publish_agent(sqlite_session, seeded["roster"])
+ # Saving draft edits after publishing marks the draft dirty, but the
+ # active snapshot keeps serving public requests.
+ agent.active_config_is_published = False
+ sqlite_session.commit()
+
+ items = {item.name: item for item in _list(app).data}
+ detail = _detail(app, seeded["roster"])
+
+ assert items["Roster Agent"].published is True
+ assert detail.published_version is not None
+ assert detail.published_version.id == agent.active_config_snapshot_id
+
+ def test_agent_seed_snapshot_is_not_published(
+ self, app: Flask, sqlite_session: Session, seeded: dict[str, str]
+ ) -> None:
+ agent = sqlite_session.scalar(select(Agent).where(Agent.app_id == seeded["roster"]))
+ assert agent is not None
+ seed = _snapshot(agent, 1, datetime(2026, 1, 15))
+ sqlite_session.add(seed)
+ sqlite_session.flush()
+ sqlite_session.add(_revision(seed, 1, AgentConfigRevisionOperation.CREATE_VERSION, datetime(2026, 1, 15)))
+ # The seed matches the draft, so the flag alone would report it published.
+ agent.active_config_snapshot_id = seed.id
+ agent.active_config_is_published = True
+ sqlite_session.commit()
+
+ items = {item.name: item for item in _list(app).data}
+
+ assert items["Roster Agent"].published is False
+ assert _detail(app, seeded["roster"]).published_version is None
+
+ @pytest.mark.parametrize(
+ ("query", "expected"),
+ [
+ (f"?workspace_ids={WS_B}", ["Roster Agent", "Gamma"]),
+ (f"?workspace_ids={WS_A}&workspace_ids={WS_B}", ["Roster Agent", "beta", "Gamma", "Alpha 100%"]),
+ ("?modes=workflow&modes=chat", ["Gamma", "Alpha 100%"]),
+ ("?modes=agent", ["Roster Agent"]),
+ ("?name=A", ["Roster Agent", "beta", "Gamma", "Alpha 100%"]),
+ ("?name=100%25", ["Alpha 100%"]),
+ ("?name=%25", ["Alpha 100%"]),
+ ("?name=%20%20", ["Roster Agent", "beta", "Gamma", "Alpha 100%"]),
+ ("?sort_by=name&sort_order=asc", ["Alpha 100%", "beta", "Gamma", "Roster Agent"]),
+ ("?sort_by=created_at&sort_order=asc", ["Alpha 100%", "Gamma", "beta", "Roster Agent"]),
+ ],
+ )
+ @pytest.mark.usefixtures("seeded")
+ def test_filters_and_sorting(self, app: Flask, query: str, expected: list[str]) -> None:
+ assert [item.name for item in _list(app, query).data] == expected
+
+ @pytest.mark.usefixtures("seeded")
+ def test_pagination(self, app: Flask) -> None:
+ first = _list(app, "?limit=3")
+ second = _list(app, "?limit=3&page=2")
+
+ assert (first.total, first.has_more, len(first.data)) == (4, True, 3)
+ assert (second.total, second.has_more, [item.name for item in second.data]) == (
+ 4,
+ False,
+ ["Alpha 100%"],
+ )
+
+ @pytest.mark.parametrize(
+ "query", ["?workspace_ids=not-a-uuid", "?modes=rag-pipeline", "?limit=0", "?limit=101", "?sort_by=calls"]
+ )
+ def test_invalid_query_is_rejected(self, app: Flask, query: str) -> None:
+ with pytest.raises(BadRequest):
+ _list(app, query)
+
+ def test_documents_query_parameters(self) -> None:
+ params = cast(DocumentedView, EnterpriseAppList.get).__apidoc__["params"]
+ for name in ("page", "limit", "workspace_ids", "modes", "name", "sort_by", "sort_order"):
+ assert params[name]["in"] == "query"
+
+
+def _detail_raw(app: Flask, app_id: str) -> object:
+ with app.test_request_context(f"/enterprise/apps/{app_id}"):
+ return inspect.unwrap(EnterpriseAppDetail.get)(EnterpriseAppDetail(), app_id=UUID(app_id))
+
+
+def _detail(app: Flask, app_id: str) -> EnterpriseAppDetailResponse:
+ return EnterpriseAppDetailResponse.model_validate(_detail_raw(app, app_id))
+
+
+def _run(app: App, status: WorkflowExecutionStatus, created_at: datetime, **kwargs: object) -> WorkflowRun:
+ return WorkflowRun(
+ tenant_id=app.tenant_id,
+ app_id=app.id,
+ workflow_id=app.workflow_id or str(uuid4()),
+ type=WorkflowType.WORKFLOW,
+ triggered_from=kwargs.pop("triggered_from", WorkflowRunTriggeredFrom.APP_RUN),
+ version="v",
+ graph="{}",
+ inputs="{}",
+ status=status,
+ created_by_role=CreatorUserRole.END_USER,
+ created_by=str(uuid4()),
+ created_at=created_at,
+ )
+
+
+def _message(app_id: str, status: MessageStatus, created_at: datetime, invoke_from: InvokeFrom) -> Message:
+ message = Message(
+ app_id=app_id,
+ conversation_id=str(uuid4()),
+ inputs={},
+ query="q",
+ message={},
+ message_unit_price=Decimal(0),
+ answer="a",
+ answer_unit_price=Decimal(0),
+ currency="USD",
+ from_source=ConversationFromSource.API,
+ status=status,
+ invoke_from=invoke_from,
+ )
+ message.created_at = created_at
+ return message
+
+
[email protected]("enterprise_apps")
+class TestEnterpriseAppDetail:
+ def test_workflow_app_state(self, app: Flask, sqlite_session: Session, seeded: dict[str, str]) -> None:
+ workflow_app = sqlite_session.get(App, seeded["alpha"])
+ assert workflow_app is not None
+ published = _workflow(
+ workflow_app,
+ version="2026-01-02 00:00:00",
+ version_number=3,
+ marked_name="Launch",
+ marked_comment="First release",
+ created_by=seeded["creator"],
+ created_at=datetime(2026, 1, 2),
+ )
+ sqlite_session.add_all(
+ [
+ published,
+ _workflow(workflow_app, version="2026-01-03 00:00:00", version_number=4, created_by=seeded["creator"]),
+ _workflow(workflow_app, version=Workflow.VERSION_DRAFT, created_by=seeded["creator"]),
+ ]
+ )
+ sqlite_session.flush()
+ workflow_app.workflow_id = published.id
+ workflow_app.enable_site = True
+ webhook = AppTrigger(
+ tenant_id=WS_A,
+ app_id=workflow_app.id,
+ node_id="hook",
+ trigger_type=AppTriggerType.TRIGGER_WEBHOOK,
+ title="Hook",
+ )
+ schedule = AppTrigger(
+ tenant_id=WS_A,
+ app_id=workflow_app.id,
+ node_id="cron",
+ trigger_type=AppTriggerType.TRIGGER_SCHEDULE,
+ title="Cron",
+ status=AppTriggerStatus.DISABLED,
+ )
+ sqlite_session.add_all(
+ [
+ Site(
+ app_id=workflow_app.id,
+ title="t",
+ default_language="en-US",
+ customize_token_strategy=CustomizeTokenStrategy.NOT_ALLOW,
+ code="site-code",
+ ),
+ ApiToken(app_id=workflow_app.id, tenant_id=WS_A, type=ApiTokenType.APP, token="app-1"),
+ ApiToken(app_id=workflow_app.id, tenant_id=WS_A, type=ApiTokenType.APP, token="app-2"),
+ AppMCPServer(
+ tenant_id=WS_A,
+ app_id=workflow_app.id,
+ name="n",
+ description="d",
+ server_code="mcp-code",
+ status="active",
+ parameters="{}",
+ ),
+ webhook,
+ schedule,
+ WorkflowWebhookTrigger(
+ app_id=workflow_app.id,
+ node_id="hook",
+ tenant_id=WS_A,
+ webhook_id="whk",
+ created_by=seeded["creator"],
+ ),
+ _run(workflow_app, WorkflowExecutionStatus.SUCCEEDED, NOW - timedelta(hours=1)),
+ _run(workflow_app, WorkflowExecutionStatus.FAILED, NOW - timedelta(hours=2)),
+ _run(workflow_app, WorkflowExecutionStatus.PARTIAL_SUCCEEDED, NOW - timedelta(hours=3)),
+ _run(workflow_app, WorkflowExecutionStatus.STOPPED, NOW - timedelta(hours=4)),
+ # Outside the 24h window.
+ _run(workflow_app, WorkflowExecutionStatus.FAILED, NOW - timedelta(hours=25)),
+ # Debugger runs are not invocations, even when newest.
+ _run(
+ workflow_app,
+ WorkflowExecutionStatus.FAILED,
+ NOW - timedelta(minutes=1),
+ triggered_from=WorkflowRunTriggeredFrom.DEBUGGING,
+ ),
+ ]
+ )
+ sqlite_session.commit()
+
+ body = _detail(app, seeded["alpha"])
+
+ assert (body.id, body.workspace_name) == (seeded["alpha"], "Support")
+ detail = body.model_dump(mode="json")
+ assert detail["published_version"] == {
+ "id": published.id,
+ "version": "2026-01-02 00:00:00",
+ "version_number": 3,
+ "marked_name": "Launch",
+ "marked_comment": "First release",
+ "created_by": {"id": seeded["creator"], "name": "Creator", "email": "[email protected]"},
+ "published_at": int(datetime(2026, 1, 2).timestamp()),
+ }
+ assert detail["published_version_count"] == 2
+ assert detail["site"] == {"enabled": True, "code": "site-code", "app_base_url": "https://apps.example.com"}
+ assert detail["api"] == {"enabled": False, "base_url": "https://api.example.com/v1", "api_key_count": 2}
+ assert detail["mcp_server"] == {"status": "active", "server_code": "mcp-code"}
+ triggers = {trigger.node_id: trigger for trigger in body.triggers}
+ assert (triggers["hook"].webhook_url or "").endswith("/triggers/webhook/whk")
+ assert triggers["cron"].model_dump(mode="json") | {"id": None} == {
+ "id": None,
+ "node_id": "cron",
+ "title": "Cron",
+ "trigger_type": "trigger-schedule",
+ "provider_name": "",
+ "status": "disabled",
+ "webhook_url": None,
+ }
+ assert detail["last_invoked_at"] == int((NOW - timedelta(hours=1)).timestamp())
+ assert (detail["invocation_count_24h"], detail["failed_invocation_count_24h"]) == (4, 2)
+
+ def test_chat_app_counts_messages_and_has_no_version(
+ self, app: Flask, sqlite_session: Session, seeded: dict[str, str]
+ ) -> None:
+ sqlite_session.add_all(
+ [
+ _message(seeded["gamma"], MessageStatus.NORMAL, NOW - timedelta(hours=1), InvokeFrom.WEB_APP),
+ _message(seeded["gamma"], MessageStatus.ERROR, NOW - timedelta(hours=2), InvokeFrom.SERVICE_API),
+ _message(seeded["gamma"], MessageStatus.ERROR, NOW - timedelta(minutes=1), InvokeFrom.DEBUGGER),
+ _message(seeded["gamma"], MessageStatus.NORMAL, NOW - timedelta(hours=30), InvokeFrom.WEB_APP),
+ ]
+ )
+ sqlite_session.commit()
+
+ detail = _detail(app, seeded["gamma"]).model_dump(mode="json")
+
+ assert (detail["published_version"], detail["published_version_count"]) == (None, 0)
+ assert detail["site"] == {"enabled": False, "code": None, "app_base_url": "https://apps.example.com"}
+ assert detail["mcp_server"] is None
+ assert detail["triggers"] == []
+ assert detail["last_invoked_at"] == int((NOW - timedelta(hours=1)).timestamp())
+ assert (detail["invocation_count_24h"], detail["failed_invocation_count_24h"]) == (2, 1)
+
+ @pytest.mark.usefixtures("seeded")
+ def test_app_without_invocations(self, app: Flask, seeded: dict[str, str]) -> None:
+ detail = _detail(app, seeded["beta"])
+
+ assert detail.published_version is None
+ assert (detail.last_invoked_at, detail.invocation_count_24h) == (None, 0)
+
+ def test_agent_app_published_version_uses_latest_revision(
+ self, app: Flask, sqlite_session: Session, seeded: dict[str, str]
+ ) -> None:
+ agent = sqlite_session.scalar(select(Agent).where(Agent.app_id == seeded["roster"]))
+ assert agent is not None
+ # The initial snapshot is not in an Agent App's version history.
+ initial = _snapshot(agent, 1, datetime(2026, 1, 15))
+ served = _snapshot(agent, 2, datetime(2026, 2, 1), version_note="Tuned prompt", created_by=seeded["creator"])
+ newer = _snapshot(agent, 3, datetime(2026, 2, 15))
+ sqlite_session.add_all([initial, served, newer])
+ sqlite_session.flush()
+ agent.active_config_snapshot_id = served.id
+ agent.active_config_is_published = True
+ sqlite_session.add_all(
+ [
+ _revision(initial, 1, AgentConfigRevisionOperation.CREATE_VERSION, datetime(2026, 1, 15)),
+ _revision(served, 2, AgentConfigRevisionOperation.PUBLISH_DRAFT, datetime(2026, 2, 1)),
+ _revision(newer, 3, AgentConfigRevisionOperation.PUBLISH_DRAFT, datetime(2026, 2, 15)),
+ _revision(served, 4, AgentConfigRevisionOperation.RESTORE_VERSION, datetime(2026, 3, 1)),
+ ]
+ )
+ sqlite_session.commit()
+
+ detail = _detail(app, seeded["roster"]).model_dump(mode="json")
+
+ assert detail["published_version"] == {
+ "id": served.id,
+ "version": None,
+ "version_number": 1,
+ "marked_name": None,
+ "marked_comment": "Tuned prompt",
+ "created_by": {"id": seeded["creator"], "name": "Creator", "email": "[email protected]"},
+ "published_at": int(datetime(2026, 3, 1).timestamp()),
+ }
+ assert detail["published_version_count"] == 2
+
+ @pytest.mark.usefixtures("seeded")
+ def test_missing_or_hidden_app_returns_404(self, app: Flask, sqlite_session: Session) -> None:
+ hidden_ids = sqlite_session.scalars(select(App.id).where(App.name.in_(["Archived Agent", "Universal"]))).all()
+ assert len(hidden_ids) == 2
+ listed_ids = {item.id for item in _list(app).data}
+ for app_id in (str(uuid4()), *hidden_ids):
+ assert app_id not in listed_ids
+ assert _detail_raw(app, app_id) == ({"message": "app not found"}, 404)
+
+ def test_trigger_entry_workflow_has_no_manual_access_points(
+ self, app: Flask, sqlite_session: Session, seeded: dict[str, str]
+ ) -> None:
+ workflow_app = sqlite_session.get(App, seeded["alpha"])
+ assert workflow_app is not None
+ published = _workflow(
+ workflow_app, version="2026-01-02 00:00:00", created_by=seeded["creator"], entry_node_type="trigger-webhook"
+ )
+ sqlite_session.add(published)
+ sqlite_session.flush()
+ workflow_app.workflow_id = published.id
+ workflow_app.enable_site = True
+ workflow_app.enable_api = True
+ sqlite_session.add_all(
+ [
+ AppTrigger(
+ tenant_id=WS_A,
+ app_id=workflow_app.id,
+ node_id="entry",
+ trigger_type=AppTriggerType.TRIGGER_WEBHOOK,
+ title="Hook",
+ ),
+ AppMCPServer(
+ tenant_id=WS_A,
+ app_id=workflow_app.id,
+ name="n",
+ description="d",
+ server_code="mcp-code",
+ status="active",
+ parameters="{}",
+ ),
+ ]
+ )
+ sqlite_session.commit()
+
+ detail = _detail(app, seeded["alpha"])
+
+ assert (detail.site, detail.api, detail.mcp_server) == (None, None, None)
+ assert [trigger.node_id for trigger in detail.triggers] == ["entry"]
+ assert detail.published_version is not None
+
+ def test_base_urls_are_null_when_not_configured(
+ self,
+ app: Flask,
+ sqlite_session_factory: sessionmaker[Session],
+ monkeypatch: pytest.MonkeyPatch,
+ seeded: dict[str, str],
+ ) -> None:
+ _install_service(app, sqlite_session_factory, monkeypatch, app_web_url="", service_api_url="")
+
+ detail = _detail(app, seeded["alpha"])
+
+ assert detail.site is not None
+ assert detail.api is not None
+ assert detail.site.app_base_url is None
+ assert detail.api.base_url is None
+
+
+class _StubWorkflowRuns:
+ """Stands in for a workflow run store outside the database, such as LogStore."""
+
+ def __init__(self, app_id: str) -> None:
+ self.app_id = app_id
+ self.calls: list[tuple[dict[str, str], list[WorkflowRunTriggeredFrom]]] = []
+
+ def get_stats_by_app_ids(
+ self,
+ tenant_id_by_app_id: Mapping[str, str],
+ triggered_from: Sequence[WorkflowRunTriggeredFrom],
+ created_since: datetime,
+ ) -> dict[str, AppWorkflowRunStats]:
+ assert created_since == NOW - timedelta(hours=24)
+ self.calls.append((dict(tenant_id_by_app_id), list(triggered_from)))
+ return {
+ self.app_id: AppWorkflowRunStats(
+ status_counts={
+ WorkflowExecutionStatus.SUCCEEDED: 3,
+ WorkflowExecutionStatus.RUNNING: 1,
+ WorkflowExecutionStatus.STOPPED: 1,
+ WorkflowExecutionStatus.FAILED: 2,
+ WorkflowExecutionStatus.PARTIAL_SUCCEEDED: 1,
+ },
+ last_created_at=NOW - timedelta(minutes=5),
+ )
+ }
+
+
+def test_workflow_invocations_come_from_the_workflow_run_repository(
+ app: Flask, sqlite_session_factory: sessionmaker[Session], monkeypatch: pytest.MonkeyPatch, seeded: dict[str, str]
+) -> None:
+ runs = _StubWorkflowRuns(seeded["alpha"])
+ service = EnterpriseAppService(
+ apps=EnterpriseAppRepository(session_factory=sqlite_session_factory, app_web_url="", service_api_url=""),
+ workflow_runs=cast(APIWorkflowRunRepository, runs),
+ now=lambda: NOW,
+ )
+ monkeypatch.setitem(app.extensions, "application_services", _Services(apps=_Apps(service)))
+
+ items = {item.name: item for item in _list(app).data}
+ detail = _detail(app, seeded["alpha"])
+
+ assert items["Alpha 100%"].invocation_count_24h == 8
+ assert (detail.invocation_count_24h, detail.failed_invocation_count_24h) == (8, 3)
+ assert detail.last_invoked_at == int((NOW - timedelta(minutes=5)).timestamp())
+ sources = [
+ WorkflowRunTriggeredFrom.APP_RUN,
+ WorkflowRunTriggeredFrom.WEBHOOK,
+ WorkflowRunTriggeredFrom.SCHEDULE,
+ WorkflowRunTriggeredFrom.PLUGIN,
+ ]
+ assert runs.calls == [
+ ({seeded["beta"]: WS_A, seeded["alpha"]: WS_A}, sources),
+ ({seeded["alpha"]: WS_A}, sources),
+ ]
diff --git a/api/tests/unit_tests/controllers/inner_api/test_schema.py b/api/tests/unit_tests/controllers/inner_api/test_schema.py
index d20f1ac007d..90b1ccd3fc3 100644
--- a/api/tests/unit_tests/controllers/inner_api/test_schema.py
+++ b/api/tests/unit_tests/controllers/inner_api/test_schema.py
@@ -22,8 +22,10 @@ EXPECTED_ENTERPRISE_OPERATION_IDS = {
"create_enterprise_workspace",
"create_enterprise_workspace_ownerless",
"delete_enterprise_workspace_resources",
+ "enterprise_app_detail",
"enterprise_app_dsl_export",
"enterprise_app_dsl_import",
+ "enterprise_app_list",
"enterprise_mint_file_grant",
"enterprise_runtime_credentials_resolve",
"join_enterprise_workspace_member",
diff --git a/api/tests/unit_tests/extensions/logstore/repositories/test_logstore_api_workflow_run_repository.py b/api/tests/unit_tests/extensions/logstore/repositories/test_logstore_api_workflow_run_repository.py
index bf90bf1801f..bbc9d00a857 100644
--- a/api/tests/unit_tests/extensions/logstore/repositories/test_logstore_api_workflow_run_repository.py
+++ b/api/tests/unit_tests/extensions/logstore/repositories/test_logstore_api_workflow_run_repository.py
@@ -1,10 +1,18 @@
import datetime
import time
from collections.abc import Generator
+from typing import cast, override
import pytest
-from extensions.logstore.repositories.logstore_api_workflow_run_repository import _dict_to_workflow_run
+from extensions.logstore.aliyun_logstore import AliyunLogStore
+from extensions.logstore.repositories.logstore_api_workflow_run_repository import (
+ LogstoreAPIWorkflowRunRepository,
+ _dict_to_workflow_run,
+)
+from graphon.enums import WorkflowExecutionStatus
+from models.enums import WorkflowRunTriggeredFrom
+from repositories.api_workflow_run_repository import AppWorkflowRunStats
_START = datetime.datetime(2026, 8, 18, 2, 0, 0, tzinfo=datetime.UTC)
_FINISH = _START + datetime.timedelta(seconds=30)
@@ -54,6 +62,85 @@ def test_dict_to_workflow_run_defaults_missing_started_at_to_naive_utc_now() ->
assert abs((model.created_at - datetime.datetime.now(tz=datetime.UTC).replace(tzinfo=None)).total_seconds()) < 60
+class _FakeLogStore:
+ def __init__(self, rows: list[dict[str, object]]) -> None:
+ self.rows = rows
+ self.sql: list[str] = []
+
+ def execute_sql(self, sql: str, logstore: str | None = None, **_options: object) -> list[dict[str, object]]:
+ assert logstore == AliyunLogStore.workflow_execution_logstore
+ self.sql.append(sql)
+ return self.rows
+
+
+def _repository(rows: list[dict[str, object]]) -> tuple[LogstoreAPIWorkflowRunRepository, _FakeLogStore]:
+ repository = LogstoreAPIWorkflowRunRepository.__new__(LogstoreAPIWorkflowRunRepository)
+ client = _FakeLogStore(rows)
+ repository.logstore_client = cast(AliyunLogStore, client)
+ return repository, client
+
+
+_APPS = {"app-1": "tenant-1", "app-'2": "tenant-1"}
+_SOURCES = [WorkflowRunTriggeredFrom.APP_RUN, WorkflowRunTriggeredFrom.WEBHOOK]
+
+
+class _RoutingLogStore(_FakeLogStore):
+ """Answer the windowed count query and the newest-start query with separate rows."""
+
+ def __init__(self, counts: list[dict[str, object]], last: list[dict[str, object]]) -> None:
+ super().__init__([])
+ self.counts = counts
+ self.last = last
+
+ @override
+ def execute_sql(self, sql: str, logstore: str | None = None, **_options: object) -> list[dict[str, object]]:
+ super().execute_sql(sql, logstore)
+ return self.last if "MAX(started_at)" in sql else self.counts
+
+
+def test_stats_by_app_ids_dedupes_versions_and_keeps_each_apps_tenant() -> None:
+ repository = LogstoreAPIWorkflowRunRepository.__new__(LogstoreAPIWorkflowRunRepository)
+ client = _RoutingLogStore(
+ counts=[
+ {"tenant_id": "tenant-1", "app_id": "app-1", "status": "succeeded", "count": "3"},
+ {"tenant_id": "tenant-1", "app_id": "app-1", "status": "running", "count": 1},
+ {"tenant_id": "tenant-2", "app_id": "app-1", "status": "failed", "count": 9},
+ {"tenant_id": "tenant-1", "app_id": "app-1", "status": "bogus", "count": 9},
+ ],
+ last=[
+ {"tenant_id": "tenant-1", "app_id": "app-1", "last_started_at": "2026-10-14T12:30:00"},
+ {"tenant_id": "tenant-1", "app_id": "app-'2", "last_started_at": "2026-01-01T00:00:00"},
+ {"tenant_id": "tenant-2", "app_id": "app-'2", "last_started_at": "2026-10-14T13:00:00"},
+ ],
+ )
+ repository.logstore_client = cast(AliyunLogStore, client)
+ since = datetime.datetime(2026, 10, 14, 12)
+
+ stats = repository.get_stats_by_app_ids(_APPS, _SOURCES, since)
+
+ assert stats == {
+ "app-1": AppWorkflowRunStats(
+ status_counts={WorkflowExecutionStatus.SUCCEEDED: 3, WorkflowExecutionStatus.RUNNING: 1},
+ last_created_at=datetime.datetime(2026, 10, 14, 12, 30),
+ ),
+ "app-'2": AppWorkflowRunStats(status_counts={}, last_created_at=datetime.datetime(2026, 1, 1)),
+ }
+ counts_sql, last_sql = client.sql
+ assert "ROW_NUMBER() OVER (PARTITION BY id ORDER BY log_version DESC)" in counts_sql
+ assert "app_id IN ('app-1', 'app-''2')" in counts_sql
+ assert "triggered_from IN ('app-run', 'webhook')" in counts_sql
+ assert f"__time__ >= {int(since.replace(tzinfo=datetime.UTC).timestamp())}" in counts_sql
+ assert "started_at >= '2026-10-14T12:00:00'" in counts_sql
+ assert "app_id IN ('app-1', 'app-''2')" in last_sql
+
+
+def test_stats_by_app_ids_skips_the_queries_without_apps() -> None:
+ repository, client = _repository([])
+
+ assert repository.get_stats_by_app_ids({}, _SOURCES, datetime.datetime(2026, 10, 14)) == {}
+ assert client.sql == []
+
+
@pytest.mark.parametrize("elapsed_time", ["0.0", "5.5"])
def test_dict_to_workflow_run_prefers_stored_active_duration(elapsed_time: str) -> None:
model = _dict_to_workflow_run({**_BASE, "started_at": _START, "finished_at": _FINISH, "elapsed_time": elapsed_time})
diff --git a/api/tests/unit_tests/repositories/test_sqlalchemy_api_workflow_run_repository.py b/api/tests/unit_tests/repositories/test_sqlalchemy_api_workflow_run_repository.py
index 9dab2c7a157..6edbda75e83 100644
--- a/api/tests/unit_tests/repositories/test_sqlalchemy_api_workflow_run_repository.py
+++ b/api/tests/unit_tests/repositories/test_sqlalchemy_api_workflow_run_repository.py
@@ -4,6 +4,7 @@ import logging
from datetime import UTC, datetime
from decimal import Decimal
from unittest.mock import patch
+from uuid import uuid4
import pytest
from sqlalchemy.orm import Session, sessionmaker
@@ -17,6 +18,7 @@ from models import Message
from models.enums import ConversationFromSource, CreatorUserRole, WorkflowRunTriggeredFrom
from models.human_input import HumanInputForm, HumanInputFormRecipient, RecipientType
from models.workflow import WorkflowPause, WorkflowPauseReason, WorkflowRun
+from repositories.api_workflow_run_repository import AppWorkflowRunStats
from repositories.sqlalchemy_api_workflow_run_repository import (
DifyAPISQLAlchemyWorkflowRunRepository,
WorkflowRunMessageRef,
@@ -322,3 +324,71 @@ def test_delete_pause_model_deletes_record_when_state_object_delete_fails(
assert "workflow_run_id=run-1" in caplog.text
assert "object_key=workflow-state.json" in caplog.text
assert caplog.records[-1].exc_info is not None
+
+
+def _app_run(
+ *,
+ tenant_id: str,
+ app_id: str,
+ status: WorkflowExecutionStatus,
+ created_at: datetime,
+ triggered_from: WorkflowRunTriggeredFrom = WorkflowRunTriggeredFrom.APP_RUN,
+) -> WorkflowRun:
+ run = _workflow_run(run_id=str(uuid4()), tenant_id=tenant_id, status=status)
+ run.app_id = app_id
+ run.triggered_from = triggered_from
+ run.created_at = created_at
+ return run
+
+
+def test_app_run_stats_scope_runs_by_app_tenant_source_and_window(
+ sqlite_session: Session,
+ sqlite_session_factory: sessionmaker[Session],
+) -> None:
+ since = datetime(2026, 10, 14, 12)
+ sqlite_session.add_all(
+ [
+ _app_run(tenant_id="t-1", app_id="a-1", status=WorkflowExecutionStatus.SUCCEEDED, created_at=since),
+ _app_run(
+ tenant_id="t-1",
+ app_id="a-1",
+ status=WorkflowExecutionStatus.FAILED,
+ created_at=datetime(2026, 10, 14, 13),
+ triggered_from=WorkflowRunTriggeredFrom.WEBHOOK,
+ ),
+ # Before the window: neither counted nor newer than a-1's windowed runs.
+ _app_run(
+ tenant_id="t-1", app_id="a-1", status=WorkflowExecutionStatus.FAILED, created_at=datetime(2026, 1, 1)
+ ),
+ # Before the window: only the last-run lookup sees it.
+ _app_run(
+ tenant_id="t-1", app_id="a-2", status=WorkflowExecutionStatus.SUCCEEDED, created_at=datetime(2026, 1, 1)
+ ),
+ # Excluded source, even though it is the newest run.
+ _app_run(
+ tenant_id="t-1",
+ app_id="a-2",
+ status=WorkflowExecutionStatus.FAILED,
+ created_at=datetime(2026, 10, 15),
+ triggered_from=WorkflowRunTriggeredFrom.DEBUGGING,
+ ),
+ # Another tenant's run for a requested app id is not that app's run.
+ _app_run(
+ tenant_id="t-2", app_id="a-1", status=WorkflowExecutionStatus.FAILED, created_at=datetime(2026, 10, 15)
+ ),
+ ]
+ )
+ sqlite_session.commit()
+ repository = DifyAPISQLAlchemyWorkflowRunRepository(session_maker=sqlite_session_factory)
+ apps = {"a-1": "t-1", "a-2": "t-1"}
+ sources = [WorkflowRunTriggeredFrom.APP_RUN, WorkflowRunTriggeredFrom.WEBHOOK]
+
+ assert repository.get_stats_by_app_ids(apps, sources, since) == {
+ "a-1": AppWorkflowRunStats(
+ status_counts={WorkflowExecutionStatus.SUCCEEDED: 1, WorkflowExecutionStatus.FAILED: 1},
+ last_created_at=datetime(2026, 10, 14, 13),
+ ),
+ # Only runs before the window: no counts, but still the newest run time.
+ "a-2": AppWorkflowRunStats(status_counts={}, last_created_at=datetime(2026, 1, 1)),
+ }
+ assert repository.get_stats_by_app_ids({}, sources, since) == {}