Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
refactor: centralize deployment edition in system features (#39454)
yyh66a545fc6d11
diff --git a/api/commands/system.py b/api/commands/system.pyindex c1f91b43869..699e0c199c9 100644--- a/api/commands/system.py+++ b/api/commands/system.py@@ -6,6 +6,7 @@ from sqlalchemy import delete, select, updatefrom sqlalchemy.orm import sessionmakerfrom configs import dify_config+from enums.deployment_edition import DeploymentEditionfrom events.app_event import app_was_createdfrom extensions.ext_database import dbfrom extensions.ext_redis import redis_client@@ -42,7 +43,7 @@ def reset_encrypt_key_pair():After the reset, all LLM credentials will become invalid, requiring re-entry.Only support SELF_HOSTED mode."""- if dify_config.EDITION != "SELF_HOSTED":+ if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:click.echo(click.style("This command is only for SELF_HOSTED installations.", fg="red"))returnwith sessionmaker(db.engine, expire_on_commit=False).begin() as session:diff --git a/api/configs/app_config.py b/api/configs/app_config.pyindex 29828a3be0d..be2f3c7c0e5 100644--- a/api/configs/app_config.py+++ b/api/configs/app_config.py@@ -5,6 +5,7 @@ from typing import Any, overridefrom pydantic.fields import FieldInfofrom pydantic_settings import BaseSettings, PydanticBaseSettingsSource, SettingsConfigDict, TomlConfigSettingsSource+from enums.deployment_edition import DeploymentEditionfrom libs.file_utils import search_file_upwardsfrom .deploy import DeploymentConfig@@ -116,3 +117,11 @@ class DifyConfig(),),)++ @property+ def DEPLOYMENT_EDITION(self) -> DeploymentEdition:+ if self.EDITION == "CLOUD":+ return DeploymentEdition.CLOUD+ if self.ENTERPRISE_ENABLED:+ return DeploymentEdition.ENTERPRISE+ return DeploymentEdition.COMMUNITYdiff --git a/api/configs/feature/__init__.py b/api/configs/feature/__init__.pyindex 5897698d1c8..c28716e3b0e 100644--- a/api/configs/feature/__init__.py+++ b/api/configs/feature/__init__.py@@ -1497,6 +1497,11 @@ class LoginConfig(BaseSettings):class AccountConfig(BaseSettings):+ ENABLE_CHANGE_EMAIL: bool = Field(+ description="whether users can change their email address",+ default=True,+ )+ACCOUNT_DELETION_TOKEN_EXPIRY_MINUTES: PositiveInt = Field(description="Duration in minutes for which a account deletion token remains valid",default=5,diff --git a/api/controllers/console/auth/login.py b/api/controllers/console/auth/login.pyindex e022c9dd28b..637f9ca0825 100644--- a/api/controllers/console/auth/login.py+++ b/api/controllers/console/auth/login.py@@ -162,9 +162,10 @@ class LoginApi(Resource):# SELF_HOSTED only have one workspacetenants = TenantService.get_join_tenants(account, session=db.session())if len(tenants) == 0:- system_features = FeatureService.get_system_features()-- if system_features.is_allow_create_workspace and not system_features.license.workspaces.is_available():+ if (+ FeatureService.get_system_features().is_allow_create_workspace+ and not FeatureService.get_license().workspaces.is_available()+ ):raise WorkspacesLimitExceeded()else:return SimpleResultOptionalDataResponse(@@ -310,7 +311,7 @@ class EmailCodeLoginApi(Resource):if account:tenants = TenantService.get_join_tenants(account, session=db.session())if not tenants:- workspaces = FeatureService.get_system_features().license.workspaces+ workspaces = FeatureService.get_license().workspacesif not workspaces.is_available():raise WorkspacesLimitExceeded()if not FeatureService.get_system_features().is_allow_create_workspace:diff --git a/api/controllers/console/feature.py b/api/controllers/console/feature.pyindex 3b1b414150a..587871e7a97 100644--- a/api/controllers/console/feature.py+++ b/api/controllers/console/feature.py@@ -3,10 +3,11 @@ from flask_restx import Resourcefrom controllers.common.schema import register_response_schema_modelsfrom fields.base import ResponseModelfrom libs.helper import dump_response-from libs.login import current_account_with_tenant_optional, login_required+from libs.login import login_requiredfrom services.feature_service import (FeatureModel,FeatureService,+ LicenseModel,LimitationModel,SystemFeatureModel,)@@ -32,6 +33,7 @@ register_response_schema_models(console_ns,AppDslVersionResponse,FeatureModel,+ LicenseModel,LimitationModel,SystemFeatureModel,TrialModelsResponse,@@ -135,8 +137,28 @@ class SystemFeatureApi(Resource):Authentication would create circular dependency (can't login without dashboard loading).- Only non-sensitive configuration data should be returned by this endpoint.+ Only non-sensitive configuration data should be returned by this endpoint. Authenticated+ license detail is served separately by SystemFeatureLicenseApi."""- current_user, _ = current_account_with_tenant_optional()- is_authenticated = current_user is not None- return FeatureService.get_system_features(is_authenticated=is_authenticated).model_dump()+ return FeatureService.get_system_features().model_dump()+++@console_ns.route("/system-features/license")+class SystemFeatureLicenseApi(Resource):+ @console_ns.doc("get_system_license")+ @console_ns.doc(description="Get license status and usage detail")+ @console_ns.response(+ 200,+ "Success",+ console_ns.models[LicenseModel.__name__],+ )+ @setup_required+ @login_required+ @account_initialization_required+ def get(self):+ """Get full license detail (status, expiry, workspace/seat usage).++ Authenticated counterpart to the license *status* exposed on the public+ system-features endpoint.+ """+ return FeatureService.get_license().model_dump()diff --git a/api/controllers/console/init_validate.py b/api/controllers/console/init_validate.pyindex f155f222e19..aca22c67f8e 100644--- a/api/controllers/console/init_validate.py+++ b/api/controllers/console/init_validate.py@@ -8,6 +8,7 @@ from sqlalchemy.orm import Sessionfrom configs import dify_configfrom controllers.fastopenapi import console_router+from enums.deployment_edition import DeploymentEditionfrom extensions.ext_database import dbfrom models.model import DifySetupfrom services.account_service import TenantService@@ -63,7 +64,7 @@ def validate_init_password(payload: InitValidatePayload) -> InitValidateResponsedef get_init_validate_status() -> bool:- if dify_config.EDITION == "SELF_HOSTED":+ if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.CLOUD:if os.environ.get("INIT_PASSWORD"):if session.get("is_init_validated"):return Truediff --git a/api/controllers/console/setup.py b/api/controllers/console/setup.pyindex e0a0fba3329..825cfb02c3e 100644--- a/api/controllers/console/setup.py+++ b/api/controllers/console/setup.py@@ -6,6 +6,7 @@ from sqlalchemy import selectfrom configs import dify_configfrom controllers.fastopenapi import console_router+from enums.deployment_edition import DeploymentEditionfrom libs.helper import EmailStr, extract_remote_ipfrom libs.password import valid_passwordfrom models.model import DifySetup, db@@ -52,7 +53,7 @@ def get_setup_status_api() -> SetupStatusResponse:Only bootstrap-safe status information should be returned by this endpoint."""- if dify_config.EDITION == "SELF_HOSTED":+ if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.CLOUD:setup_status = get_setup_status()if setup_status and not isinstance(setup_status, bool):return SetupStatusResponse(step="finished", setup_at=setup_status.setup_at.isoformat())@@ -102,7 +103,7 @@ def setup_system(payload: SetupRequestPayload) -> SetupResponse:def get_setup_status() -> DifySetup | bool | None:- if dify_config.EDITION == "SELF_HOSTED":+ if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.CLOUD:return db.session.scalar(select(DifySetup).limit(1))return Truediff --git a/api/controllers/console/workspace/account.py b/api/controllers/console/workspace/account.pyindex 6a06ed2d3e6..a37476953c4 100644--- a/api/controllers/console/workspace/account.py+++ b/api/controllers/console/workspace/account.py@@ -46,6 +46,7 @@ from controllers.console.wraps import (with_current_tenant_id,with_current_user,)+from enums.deployment_edition import DeploymentEditionfrom extensions.ext_database import dbfrom fields.base import ResponseModelfrom fields.member_fields import AccountResponse@@ -262,7 +263,7 @@ class AccountInitApi(Resource):payload = console_ns.payload or {}args = AccountInitPayload.model_validate(payload)- if dify_config.EDITION == "CLOUD":+ if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:if not args.invitation_code:raise ValueError("invitation_code is required")diff --git a/api/controllers/console/workspace/members.py b/api/controllers/console/workspace/members.pyindex 3e70de05347..9d40d32aaa2 100644--- a/api/controllers/console/workspace/members.py+++ b/api/controllers/console/workspace/members.py@@ -198,7 +198,7 @@ def _check_member_invite_limits(tenant_id: str, new_member_count: int, new_accouif workspace_members.enabled is True and not workspace_members.is_available(new_member_count):raise WorkspaceMembersLimitExceeded()if new_account_count > 0:- seats = FeatureService.get_system_features(is_authenticated=True).license.seats+ seats = FeatureService.get_license().seatsif not seats.is_available(new_account_count):raise SeatsLimitExceeded()returndiff --git a/api/controllers/console/workspace/workspace.py b/api/controllers/console/workspace/workspace.pyindex 6d67960f622..dbb9047e0ec 100644--- a/api/controllers/console/workspace/workspace.py+++ b/api/controllers/console/workspace/workspace.py@@ -37,6 +37,7 @@ from controllers.console.wraps import (with_current_user,)from enums.cloud_plan import CloudPlan+from enums.deployment_edition import DeploymentEditionfrom extensions.ext_database import dbfrom fields.base import ResponseModelfrom libs.helper import dump_response, to_timestamp@@ -233,7 +234,7 @@ class TenantListApi(Resource):tenants = [tenant for tenant, _ in tenant_rows]tenant_dicts = []is_enterprise_only = dify_config.ENTERPRISE_ENABLED and not dify_config.BILLING_ENABLED- is_saas = dify_config.EDITION == "CLOUD" and dify_config.BILLING_ENABLED+ is_saas = dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD and dify_config.BILLING_ENABLEDtenant_plans: dict[str, SubscriptionPlan] = {}if is_saas:diff --git a/api/controllers/console/wraps.py b/api/controllers/console/wraps.pyindex 4e22d334bec..b77c78761a0 100644--- a/api/controllers/console/wraps.py+++ b/api/controllers/console/wraps.py@@ -20,6 +20,7 @@ from controllers.common.wraps import (from controllers.console.auth.error import AuthenticationFailedError, EmailCodeErrorfrom controllers.console.workspace.error import AccountNotInitializedErrorfrom enums.cloud_plan import CloudPlan+from enums.deployment_edition import DeploymentEditionfrom extensions.ext_database import dbfrom extensions.ext_redis import redis_clientfrom libs.encryption import FieldEncryption@@ -129,7 +130,7 @@ def account_initialization_required[R](view: Callable[..., R]) -> Callable[...,def only_edition_cloud[**P, R](view: Callable[P, R]) -> Callable[P, R]:@wraps(view)def decorated(*args: P.args, **kwargs: P.kwargs):- if dify_config.EDITION != "CLOUD":+ if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.CLOUD:abort(404)return view(*args, **kwargs)@@ -151,7 +152,7 @@ def only_edition_enterprise[**P, R](view: Callable[P, R]) -> Callable[P, R]:def only_edition_self_hosted[**P, R](view: Callable[P, R]) -> Callable[P, R]:@wraps(view)def decorated(*args: P.args, **kwargs: P.kwargs):- if dify_config.EDITION != "SELF_HOSTED":+ if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:abort(404)return view(*args, **kwargs)@@ -327,7 +328,7 @@ def setup_required[R](view: Callable[..., R]) -> Callable[..., R]:# The overloads keep Resource methods method-aware for pyrefly while# preserving support for plain functions used in tests and utilities.# check setup- if dify_config.EDITION == "SELF_HOSTED" and not _is_setup_completed():+ if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.CLOUD and not _is_setup_completed():if os.environ.get("INIT_PASSWORD"):raise NotInitValidateError()raise NotSetupError()diff --git a/api/controllers/openapi/auth/data.py b/api/controllers/openapi/auth/data.pyindex fa68b48d975..898a9eb8f87 100644--- a/api/controllers/openapi/auth/data.py+++ b/api/controllers/openapi/auth/data.py@@ -8,6 +8,7 @@ from werkzeug.exceptions import InternalServerErrorfrom configs import dify_configfrom core.rbac import RBACPermission, RBACResourceScope+from enums.deployment_edition import DeploymentEditionfrom libs.oauth_bearer import Scope, TokenTypefrom models.account import Account, Tenant, TenantAccountRolefrom models.model import App, EndUser@@ -26,7 +27,7 @@ class CallerKind(StrEnum):def current_edition() -> Edition:- if dify_config.EDITION == "CLOUD":+ if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:return Edition.SAASif dify_config.ENTERPRISE_ENABLED:return Edition.EEdiff --git a/api/controllers/web/site.py b/api/controllers/web/site.pyindex b5999bc093d..f6c4af013a1 100644--- a/api/controllers/web/site.py+++ b/api/controllers/web/site.py@@ -8,6 +8,7 @@ from configs import dify_configfrom controllers.common.schema import register_response_schema_modelsfrom controllers.web import web_nsfrom controllers.web.wraps import WebApiResource+from enums.deployment_edition import DeploymentEditionfrom extensions.ext_database import dbfrom extensions.storage.storage_type import StorageTypefrom fields.base import ResponseModel@@ -127,7 +128,9 @@ def _build_site_icon_url(*, site: Site, tenant_id: str) -> str | None:"""Use direct S3 URLs only in Cloud Mode and preserve preview URLs elsewhere."""if site.icon_type != IconType.IMAGE or not site.icon:return None- if dify_config.EDITION == "CLOUD" and StorageType(dify_config.STORAGE_TYPE) == StorageType.S3:+ if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD and (+ StorageType(dify_config.STORAGE_TYPE) == StorageType.S3+ ):return FileService(db.engine).get_file_presigned_url(file_id=site.icon, tenant_id=tenant_id)return build_icon_url(site.icon_type, site.icon)diff --git a/api/core/hosting_configuration.py b/api/core/hosting_configuration.pyindex 1a25c23d404..09473b8b78f 100644--- a/api/core/hosting_configuration.py+++ b/api/core/hosting_configuration.py@@ -6,6 +6,7 @@ from pydantic import BaseModelfrom configs import dify_configfrom core.entities import DEFAULT_PLUGIN_IDfrom core.entities.provider_entities import ProviderQuotaType, QuotaUnit, RestrictModel+from enums.deployment_edition import DeploymentEditionfrom graphon.model_runtime.entities.model_entities import ModelType@@ -49,7 +50,7 @@ class HostingConfiguration:self.moderation_config = Nonedef init_app(self, app: Flask):- if dify_config.EDITION != "CLOUD":+ if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.CLOUD:returnself.provider_map[f"{DEFAULT_PLUGIN_ID}/azure_openai/azure_openai"] = self.init_azure_openai()diff --git a/api/core/provider_manager.py b/api/core/provider_manager.pyindex ebfe77e8f30..0064252b64a 100644--- a/api/core/provider_manager.py+++ b/api/core/provider_manager.py@@ -34,6 +34,7 @@ from core.entities.provider_entities import (from core.helper import encrypterfrom core.helper.model_provider_cache import ProviderCredentialsCache, ProviderCredentialsCacheTypefrom core.helper.position_helper import is_filtered+from enums.deployment_edition import DeploymentEditionfrom extensions import ext_hosting_providerfrom extensions.ext_database import dbfrom extensions.ext_redis import redis_client@@ -743,7 +744,7 @@ class ProviderManager:if preferred_provider_type_record:preferred_provider_type = preferred_provider_type_record.preferred_provider_type- elif dify_config.EDITION == "CLOUD" and system_configuration.enabled:+ elif dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD and system_configuration.enabled:preferred_provider_type = ProviderType.SYSTEMelif custom_configuration.provider or custom_configuration.models:preferred_provider_type = ProviderType.CUSTOM@@ -1538,7 +1539,7 @@ class ProviderManager:quota_type_to_provider_records_dict[provider_record.quota_type] = provider_record # type: ignore[index]quota_configurations = []- if dify_config.EDITION == "CLOUD":+ if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:from services.credit_pool_service import CreditPoolServicetrail_pool = CreditPoolService.get_pool(diff --git a/api/enums/deployment_edition.py b/api/enums/deployment_edition.pynew file mode 100644index 00000000000..5541651b576--- /dev/null+++ b/api/enums/deployment_edition.py@@ -0,0 +1,11 @@+from enum import StrEnum+++class DeploymentEdition(StrEnum):+ """+ Enum representing the deployment edition of the platform.+ """++ COMMUNITY = "COMMUNITY"+ ENTERPRISE = "ENTERPRISE"+ CLOUD = "CLOUD"diff --git a/api/openapi/markdown/console-openapi.md b/api/openapi/markdown/console-openapi.mdindex 2643812c6bf..55b983deb5a 100644--- a/api/openapi/markdown/console-openapi.md+++ b/api/openapi/markdown/console-openapi.md@@ -9483,7 +9483,8 @@ data required for dashboard initialization.Authentication would create circular dependency (can't login without dashboard loading).-Only non-sensitive configuration data should be returned by this endpoint.+Only non-sensitive configuration data should be returned by this endpoint. Authenticated+license detail is served separately by SystemFeatureLicenseApi.#### Responses@@ -9491,6 +9492,19 @@ Only non-sensitive configuration data should be returned by this endpoint.| ---- | ----------- | ------ || 200 | Success | **application/json**: [SystemFeatureModel](#systemfeaturemodel)<br> |+### [GET] /system-features/license+**Get full license detail (status, expiry, workspace/seat usage)**++Get license status and usage detail+Authenticated counterpart to the license *status* exposed on the public+system-features endpoint.++#### Responses++| Code | Description | Schema |+| ---- | ----------- | ------ |+| 200 | Success | **application/json**: [LicenseModel](#licensemodel)<br> |+### [POST] /tag-bindings#### Request Body@@ -17318,6 +17332,14 @@ Default model entity.| tool_name | string | | Yes || type | string | | Yes |+#### DeploymentEdition++Enum representing the deployment edition of the platform.++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| DeploymentEdition | string | Enum representing the deployment edition of the platform. | |+#### DismissNotificationPayload| Name | Type | Description | Required |@@ -18815,6 +18837,12 @@ Enum class for large language model mode.| ---- | ---- | ----------- | -------- || LicenseStatus | string | | |+#### LicenseStatusModel++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| status | [LicenseStatus](#licensestatus) | | Yes |+#### LimitationModel| Name | Type | Description | Required |@@ -22027,6 +22055,7 @@ Model class for provider system configuration response.| Name | Type | Description | Required || ---- | ---- | ----------- | -------- || branding | [BrandingModel](#brandingmodel) | | Yes |+| deployment_edition | [DeploymentEdition](#deploymentedition) | | Yes || enable_app_deploy | boolean | | Yes || enable_change_email | boolean, <br>**Default:** true | | Yes || enable_collaboration_mode | boolean, <br>**Default:** true | | Yes |@@ -22043,7 +22072,7 @@ Model class for provider system configuration response.| is_allow_register | boolean | | Yes || is_email_setup | boolean | | Yes || knowledge_fs_enabled | boolean | | Yes |-| license | [LicenseModel](#licensemodel) | | Yes |+| license | [LicenseStatusModel](#licensestatusmodel) | | Yes || max_plugin_package_size | integer, <br>**Default:** 15728640 | | Yes || plugin_installation_permission | [PluginInstallationPermissionModel](#plugininstallationpermissionmodel) | | Yes || plugin_manager | [PluginManagerModel](#pluginmanagermodel) | | Yes |diff --git a/api/openapi/markdown/web-openapi.md b/api/openapi/markdown/web-openapi.mdindex b826b5fe8e0..954e7c17e8a 100644--- a/api/openapi/markdown/web-openapi.md+++ b/api/openapi/markdown/web-openapi.md@@ -1058,6 +1058,14 @@ Button styles for user actions.| auto_generate | boolean | Automatically generate the conversation name. When `true`, the `name` field is ignored. | No || name | string | Conversation name. Required when `auto_generate` is `false`. | No |+#### DeploymentEdition++Enum representing the deployment edition of the platform.++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| DeploymentEdition | string | Enum representing the deployment edition of the platform. | |+#### EmailCodeLoginSendPayload| Name | Type | Description | Required |@@ -1284,32 +1292,17 @@ Parsed multipart form fields for HITL uploads.| ---- | ---- | ----------- | -------- || JsonValue | | | |-#### LicenseLimitationModel--- enabled: whether this limit is enforced-- size: current usage count-- limit: maximum allowed count; 0 means unlimited+#### LicenseStatus| Name | Type | Description | Required || ---- | ---- | ----------- | -------- |-| enabled | boolean | Whether this limit is currently active | Yes |-| limit | integer | Maximum number of resources allowed; 0 means no limit | Yes |-| size | integer | Number of resources already consumed | Yes |+| LicenseStatus | string | | |-#### LicenseModel+#### LicenseStatusModel| Name | Type | Description | Required || ---- | ---- | ----------- | -------- |-| expired_at | string | | Yes |-| seats | [LicenseLimitationModel](#licenselimitationmodel) | | Yes || status | [LicenseStatus](#licensestatus) | | Yes |-| workspaces | [LicenseLimitationModel](#licenselimitationmodel) | | Yes |--#### LicenseStatus--| Name | Type | Description | Required |-| ---- | ---- | ----------- | -------- |-| LicenseStatus | string | | |#### LoginPayload@@ -1567,6 +1560,7 @@ Default configuration for form inputs.| Name | Type | Description | Required || ---- | ---- | ----------- | -------- || branding | [BrandingModel](#brandingmodel) | | Yes |+| deployment_edition | [DeploymentEdition](#deploymentedition) | | Yes || enable_app_deploy | boolean | | Yes || enable_change_email | boolean, <br>**Default:** true | | Yes || enable_collaboration_mode | boolean, <br>**Default:** true | | Yes |@@ -1583,7 +1577,7 @@ Default configuration for form inputs.| is_allow_register | boolean | | Yes || is_email_setup | boolean | | Yes || knowledge_fs_enabled | boolean | | Yes |-| license | [LicenseModel](#licensemodel) | | Yes |+| license | [LicenseStatusModel](#licensestatusmodel) | | Yes || max_plugin_package_size | integer, <br>**Default:** 15728640 | | Yes || plugin_installation_permission | [PluginInstallationPermissionModel](#plugininstallationpermissionmodel) | | Yes || plugin_manager | [PluginManagerModel](#pluginmanagermodel) | | Yes |diff --git a/api/services/account_service.py b/api/services/account_service.pyindex 432a2484ed6..5784f19a3a2 100644--- a/api/services/account_service.py+++ b/api/services/account_service.py@@ -442,9 +442,9 @@ class AccountService:# A licensed seat is one Account row, deployment-wide; joining an existing# account into another workspace does not pass through here and costs no seat.- # is_authenticated=True: server-side enforcement needs the full license payload,- # which the enterprise fill withholds from unauthenticated (browser-facing) calls.- if not FeatureService.get_system_features(is_authenticated=True).license.seats.is_available():+ # get_license() carries the full license payload that server-side enforcement needs;+ # the public system-features endpoint exposes only license status.+ if not FeatureService.get_license().seats.is_available():raise SeatsLimitExceededError("licensed seats limit exceeded")if dify_config.BILLING_ENABLED and BillingService.is_email_in_freeze(email):@@ -1332,7 +1332,7 @@ class TenantService:):raise WorkSpaceNotAllowedCreateError()- workspaces = FeatureService.get_system_features().license.workspaces+ workspaces = FeatureService.get_license().workspacesif not workspaces.is_available():raise WorkspacesLimitExceededError()@@ -2012,7 +2012,7 @@ class RegisterService:if (FeatureService.get_system_features().is_allow_create_workspaceand create_workspace_required- and FeatureService.get_system_features().license.workspaces.is_available()+ and FeatureService.get_license().workspaces.is_available()):try:TenantService.create_owner_tenant(account, session=session)diff --git a/api/services/feature_service.py b/api/services/feature_service.pyindex b23638bba20..8a4b56b672c 100644--- a/api/services/feature_service.py+++ b/api/services/feature_service.py@@ -5,6 +5,7 @@ from pydantic import BaseModel, ConfigDict, Fieldfrom configs import dify_configfrom constants.dsl_version import CURRENT_APP_DSL_VERSIONfrom enums.cloud_plan import CloudPlan+from enums.deployment_edition import DeploymentEditionfrom enums.hosted_provider import HostedTrialProviderfrom services.billing_service import BillingInfo, BillingServicefrom services.enterprise.enterprise_service import EnterpriseService@@ -75,8 +76,11 @@ class LicenseStatus(StrEnum):LOST = "lost"-class LicenseModel(FeatureResponseModel):+class LicenseStatusModel(FeatureResponseModel):status: LicenseStatus = LicenseStatus.NONE+++class LicenseModel(LicenseStatusModel):expired_at: str = ""workspaces: LicenseLimitationModel = LicenseLimitationModel(enabled=False, size=0, limit=0)seats: LicenseLimitationModel = LicenseLimitationModel(enabled=False, size=0, limit=0)@@ -162,6 +166,7 @@ class PluginManagerModel(FeatureResponseModel):class SystemFeatureModel(FeatureResponseModel):+ deployment_edition: DeploymentEditionenable_app_deploy: bool = Falsesso_enforced_for_signin: bool = Falsesso_enforced_for_signin_protocol: str = ""@@ -174,7 +179,7 @@ class SystemFeatureModel(FeatureResponseModel):is_allow_register: bool = Falseis_allow_create_workspace: bool = Falseis_email_setup: bool = False- license: LicenseModel = LicenseModel()+ license: LicenseStatusModel = LicenseStatusModel()branding: BrandingModel = BrandingModel()webapp_auth: WebAppAuthModel = WebAppAuthModel()plugin_installation_permission: PluginInstallationPermissionModel = PluginInstallationPermissionModel()@@ -251,8 +256,8 @@ class FeatureService:)@classmethod- def get_system_features(cls, is_authenticated: bool = False) -> SystemFeatureModel:- system_features = SystemFeatureModel()+ def get_system_features(cls) -> SystemFeatureModel:+ system_features = SystemFeatureModel(deployment_edition=dify_config.DEPLOYMENT_EDITION)system_features.rbac_enabled = dify_config.RBAC_ENABLEDcls._fulfill_system_params_from_env(system_features)@@ -262,7 +267,7 @@ class FeatureService:system_features.webapp_auth.enabled = Truesystem_features.enable_change_email = Falsesystem_features.plugin_manager.enabled = True- cls._fulfill_params_from_enterprise(system_features, is_authenticated)+ cls._fulfill_params_from_enterprise(system_features)if dify_config.MARKETPLACE_ENABLED:system_features.enable_marketplace = True@@ -272,6 +277,17 @@ class FeatureService:return system_features+ @classmethod+ def get_license(cls) -> LicenseModel:+ """Return full license detail. Enterprise-only; requires an authenticated caller.++ Non-enterprise deployments have no license, so an unconstrained default+ (unlimited seats/workspaces) is returned.+ """+ if not dify_config.ENTERPRISE_ENABLED:+ return LicenseModel()+ return cls._build_license(EnterpriseService.get_info())+@classmethoddef get_app_dsl_version(cls) -> str:return CURRENT_APP_DSL_VERSION@@ -285,6 +301,7 @@ class FeatureService:system_features.is_allow_register = dify_config.ALLOW_REGISTERsystem_features.is_allow_create_workspace = dify_config.ALLOW_CREATE_WORKSPACEsystem_features.is_email_setup = dify_config.MAIL_TYPE is not None and dify_config.MAIL_TYPE != ""+ system_features.enable_change_email = dify_config.ENABLE_CHANGE_EMAILsystem_features.enable_trial_app = dify_config.ENABLE_TRIAL_APPsystem_features.enable_explore_banner = dify_config.ENABLE_EXPLORE_BANNERsystem_features.enable_learn_app = dify_config.ENABLE_LEARN_APP@@ -410,7 +427,27 @@ class FeatureService:vector_space.limit = billing_info["vector_space"]["limit"]@classmethod- def _fulfill_params_from_enterprise(cls, features: SystemFeatureModel, is_authenticated: bool = False):+ def _build_license(cls, enterprise_info: dict) -> LicenseModel:+ license_model = LicenseModel()+ if license_info := enterprise_info.get("License"):+ license_model.status = LicenseStatus(license_info.get("status", LicenseStatus.INACTIVE))+ license_model.expired_at = license_info.get("expiredAt", "")+ if workspaces_info := license_info.get("workspaces"):+ license_model.workspaces = LicenseLimitationModel(+ enabled=workspaces_info.get("enabled", False),+ limit=workspaces_info.get("limit", 0),+ size=workspaces_info.get("used", 0),+ )+ if seats_info := license_info.get("licensedSeats"):+ license_model.seats = LicenseLimitationModel(+ enabled=seats_info.get("enabled", False),+ limit=seats_info.get("limit", 0),+ size=seats_info.get("used", 0),+ )+ return license_model++ @classmethod+ def _fulfill_params_from_enterprise(cls, features: SystemFeatureModel):enterprise_info = EnterpriseService.get_info()if "SSOEnforcedForSignin" in enterprise_info:@@ -450,24 +487,14 @@ class FeatureService:)features.webapp_auth.sso_config.protocol = enterprise_info.get("SSOEnforcedForWebProtocol", "")- # SECURITY NOTE: Only license *status* is exposed to unauthenticated callers- # so the login page can detect an expired/inactive license after force-logout.- # All other license details (expiry date, workspace usage) remain auth-gated.- # This behavior reflects prior internal review of information-leakage risks.+ # SECURITY NOTE: system-features is unauthenticated, so it exposes only license+ # *status* — enough for the login page to detect an expired/inactive license after+ # force-logout. Full license detail (expiry, workspace/seat usage) is served+ # separately by get_license() behind an authenticated endpoint.if license_info := enterprise_info.get("License"):- features.license.status = LicenseStatus(license_info.get("status", LicenseStatus.INACTIVE))-- if is_authenticated:- features.license.expired_at = license_info.get("expiredAt", "")- if workspaces_info := license_info.get("workspaces"):- features.license.workspaces.enabled = workspaces_info.get("enabled", False)- features.license.workspaces.limit = workspaces_info.get("limit", 0)- features.license.workspaces.size = workspaces_info.get("used", 0)-- if seats_info := license_info.get("licensedSeats"):- features.license.seats.enabled = seats_info.get("enabled", False)- features.license.seats.limit = seats_info.get("limit", 0)- features.license.seats.size = seats_info.get("used", 0)+ features.license = LicenseStatusModel(+ status=LicenseStatus(license_info.get("status", LicenseStatus.INACTIVE))+ )if "PluginInstallationPermission" in enterprise_info:plugin_installation_info = enterprise_info["PluginInstallationPermission"]diff --git a/api/services/workspace_service.py b/api/services/workspace_service.pyindex 39938aad9d3..5f9003bb755 100644--- a/api/services/workspace_service.py+++ b/api/services/workspace_service.py@@ -4,6 +4,7 @@ from sqlalchemy.orm import Sessionfrom configs import dify_configfrom enums.cloud_plan import CloudPlan+from enums.deployment_edition import DeploymentEditionfrom models.account import Tenant, TenantAccountJoin, TenantAccountRolefrom services.account_service import TenantServicefrom services.feature_service import FeatureService@@ -60,7 +61,7 @@ class WorkspaceService:"remove_webapp_brand": remove_webapp_brand,"replace_webapp_logo": replace_webapp_logo,}- if dify_config.EDITION == "CLOUD":+ if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:tenant_info["next_credit_reset_date"] = feature.next_credit_reset_datefrom services.credit_pool_service import CreditPoolBalance, CreditPoolServicediff --git a/api/tasks/workflow_cfs_scheduler/entities.py b/api/tasks/workflow_cfs_scheduler/entities.pyindex 6990f6968a9..e95d606731c 100644--- a/api/tasks/workflow_cfs_scheduler/entities.py+++ b/api/tasks/workflow_cfs_scheduler/entities.py@@ -1,10 +1,11 @@from enum import StrEnumfrom configs import dify_config+from enums.deployment_edition import DeploymentEditionfrom services.workflow.entities import WorkflowScheduleCFSPlanEntity# Determine queue names based on edition-if dify_config.EDITION == "CLOUD":+if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:# Cloud edition: separate queues for different tiers_professional_queue = "workflow_professional"_team_queue = "workflow_team"diff --git a/api/tests/test_containers_integration_tests/services/test_account_service.py b/api/tests/test_containers_integration_tests/services/test_account_service.pyindex 24895e562e5..4579fbfbb40 100644--- a/api/tests/test_containers_integration_tests/services/test_account_service.py+++ b/api/tests/test_containers_integration_tests/services/test_account_service.py@@ -38,7 +38,8 @@ class TestAccountService:# Setup default mock returnsmock_feature_service.get_system_features.return_value.is_allow_register = Truemock_feature_service.get_system_features.return_value.is_allow_create_workspace = True- mock_feature_service.get_system_features.return_value.license.workspaces.is_available.return_value = True+ mock_feature_service.get_license.return_value.workspaces.is_available.return_value = True+ mock_feature_service.get_license.return_value.seats.is_available.return_value = Truemock_billing_service.is_email_in_freeze.return_value = Falsemock_passport_service.return_value.issue.return_value = "mock_jwt_token"@@ -405,7 +406,7 @@ class TestAccountService:].get_system_features.return_value.is_allow_create_workspace = Truemock_external_service_dependencies["feature_service"- ].get_system_features.return_value.license.workspaces.is_available.return_value = True+ ].get_license.return_value.workspaces.is_available.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = Falseaccount = AccountService.create_account_and_tenant(email=email,@@ -466,7 +467,7 @@ class TestAccountService:].get_system_features.return_value.is_allow_create_workspace = Truemock_external_service_dependencies["feature_service"- ].get_system_features.return_value.license.workspaces.is_available.return_value = False+ ].get_license.return_value.workspaces.is_available.return_value = Falsemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = Falsewith pytest.raises(WorkspacesLimitExceededError):@@ -492,7 +493,7 @@ class TestAccountService:mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = Truemock_external_service_dependencies["feature_service"- ].get_system_features.return_value.license.seats.is_available.return_value = False+ ].get_license.return_value.seats.is_available.return_value = Falsemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = Falsewith pytest.raises(SeatsLimitExceededError):@@ -1274,7 +1275,8 @@ class TestTenantService:):# Setup default mock returnsmock_feature_service.get_system_features.return_value.is_allow_create_workspace = True- mock_feature_service.get_system_features.return_value.license.workspaces.is_available.return_value = True+ mock_feature_service.get_license.return_value.workspaces.is_available.return_value = True+ mock_feature_service.get_license.return_value.seats.is_available.return_value = Truemock_billing_service.is_email_in_freeze.return_value = Falseyield {@@ -2244,7 +2246,7 @@ class TestTenantService:].get_system_features.return_value.is_allow_create_workspace = Truemock_external_service_dependencies["feature_service"- ].get_system_features.return_value.license.workspaces.is_available.return_value = True+ ].get_license.return_value.workspaces.is_available.return_value = True# Create accountaccount = AccountService.create_account(@@ -2285,7 +2287,7 @@ class TestTenantService:].get_system_features.return_value.is_allow_create_workspace = Truemock_external_service_dependencies["feature_service"- ].get_system_features.return_value.license.workspaces.is_available.return_value = True+ ].get_license.return_value.workspaces.is_available.return_value = True# Create account and existing tenantaccount = AccountService.create_account(@@ -2514,7 +2516,8 @@ class TestRegisterService:# Setup default mock returnsmock_feature_service.get_system_features.return_value.is_allow_register = Truemock_feature_service.get_system_features.return_value.is_allow_create_workspace = True- mock_feature_service.get_system_features.return_value.license.workspaces.is_available.return_value = True+ mock_feature_service.get_license.return_value.workspaces.is_available.return_value = True+ mock_feature_service.get_license.return_value.seats.is_available.return_value = Truemock_billing_service.is_email_in_freeze.return_value = Falsemock_passport_service.return_value.issue.return_value = "mock_jwt_token"@@ -2631,7 +2634,7 @@ class TestRegisterService:].get_system_features.return_value.is_allow_create_workspace = Truemock_external_service_dependencies["feature_service"- ].get_system_features.return_value.license.workspaces.is_available.return_value = True+ ].get_license.return_value.workspaces.is_available.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Execute registration@@ -2675,7 +2678,7 @@ class TestRegisterService:].get_system_features.return_value.is_allow_create_workspace = Truemock_external_service_dependencies["feature_service"- ].get_system_features.return_value.license.workspaces.is_available.return_value = True+ ].get_license.return_value.workspaces.is_available.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Execute registration with OAuth@@ -2724,7 +2727,7 @@ class TestRegisterService:].get_system_features.return_value.is_allow_create_workspace = Truemock_external_service_dependencies["feature_service"- ].get_system_features.return_value.license.workspaces.is_available.return_value = True+ ].get_license.return_value.workspaces.is_available.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Execute registration with pending status@@ -2809,7 +2812,7 @@ class TestRegisterService:].get_system_features.return_value.is_allow_create_workspace = Truemock_external_service_dependencies["feature_service"- ].get_system_features.return_value.license.workspaces.is_available.return_value = False+ ].get_license.return_value.workspaces.is_available.return_value = Falsemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# with pytest.raises(AccountRegisterError, match="Workspace is not allowed to create."):@@ -2888,7 +2891,7 @@ class TestRegisterService:].get_system_features.return_value.is_allow_create_workspace = Truemock_external_service_dependencies["feature_service"- ].get_system_features.return_value.license.workspaces.is_available.return_value = True+ ].get_license.return_value.workspaces.is_available.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Create tenant and inviter accountdiff --git a/api/tests/test_containers_integration_tests/services/test_feature_service.py b/api/tests/test_containers_integration_tests/services/test_feature_service.pyindex 4e5bfc6ac1d..a7e2584c14b 100644--- a/api/tests/test_containers_integration_tests/services/test_feature_service.py+++ b/api/tests/test_containers_integration_tests/services/test_feature_service.py@@ -5,10 +5,12 @@ from faker import Fakerfrom sqlalchemy.orm import Sessionfrom enums.cloud_plan import CloudPlan+from enums.deployment_edition import DeploymentEditionfrom services.feature_service import (FeatureModel,FeatureService,KnowledgeRateLimitModel,+ LicenseModel,LicenseStatus,SystemFeatureModel,)@@ -273,6 +275,7 @@ class TestFeatureService:tenant_id = self._create_test_tenant_id()with patch("services.feature_service.dify_config") as mock_config:+ mock_config.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISEmock_config.ENTERPRISE_ENABLED = Truemock_config.MARKETPLACE_ENABLED = Truemock_config.ENABLE_EMAIL_CODE_LOGIN = True@@ -285,7 +288,7 @@ class TestFeatureService:mock_config.PLUGIN_MAX_PACKAGE_SIZE = 100# Act: Execute the method under test- result = FeatureService.get_system_features(is_authenticated=True)+ result = FeatureService.get_system_features()# Assert: Verify the expected outcomesassert result is not None@@ -320,12 +323,9 @@ class TestFeatureService:assert result.webapp_auth.allow_email_password_login is Falseassert result.webapp_auth.sso_config.protocol == "oidc"- # Verify license configuration+ # Verify license status (public system-features exposes status only; detail lives on get_license)assert result.license.status.value == "active"- assert result.license.expired_at == "2025-12-31"- assert result.license.workspaces.enabled is True- assert result.license.workspaces.limit == 5- assert result.license.workspaces.size == 2+ assert not hasattr(result.license, "expired_at")# Verify plugin installation permissionassert result.plugin_installation_permission.plugin_installation_scope == "official_only"@@ -350,6 +350,7 @@ class TestFeatureService:"""# Arrange: Setup test data with exact same config as success testwith patch("services.feature_service.dify_config") as mock_config:+ mock_config.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISEmock_config.ENTERPRISE_ENABLED = Truemock_config.MARKETPLACE_ENABLED = Truemock_config.ENABLE_EMAIL_CODE_LOGIN = True@@ -360,20 +361,18 @@ class TestFeatureService:mock_config.MAIL_TYPE = "smtp"mock_config.PLUGIN_MAX_PACKAGE_SIZE = 100- # Act: Execute with is_authenticated=False- result = FeatureService.get_system_features(is_authenticated=False)+ # Act: Execute the public (unauthenticated) system-features call+ result = FeatureService.get_system_features()# Assert: Basic structureassert result is not Noneassert isinstance(result, SystemFeatureModel)# --- 1. Verify only license *status* is exposed to unauthenticated clients ---- # Detailed license info (expiry, workspaces) remains auth-gated.+ # Detailed license info (expiry, workspaces) is not part of the public model.assert result.license.status == LicenseStatus.ACTIVE- assert result.license.expired_at == ""- assert result.license.workspaces.enabled is False- assert result.license.workspaces.limit == 0- assert result.license.workspaces.size == 0+ assert not hasattr(result.license, "expired_at")+ assert not hasattr(result.license, "workspaces")# --- 2. Verify Public UI Configuration Availability ---# Ensure that data required for frontend rendering remains accessible.@@ -394,6 +393,47 @@ class TestFeatureService:# Marketplace should be visibleassert result.enable_marketplace is True+ def test_get_license_returns_full_detail(+ self, db_session_with_containers: Session, mock_external_service_dependencies+ ):+ """+ Test the authenticated license accessor.++ This test verifies that:+ - get_license() returns the full license payload (status, expiry, workspace usage).+ - Detail withheld from the public system-features model is present here.+ """+ # Arrange+ with patch("services.feature_service.dify_config") as mock_config:+ mock_config.ENTERPRISE_ENABLED = True++ # Act+ result = FeatureService.get_license()++ # Assert: full license detail is populated+ assert isinstance(result, LicenseModel)+ assert result.status == LicenseStatus.ACTIVE+ assert result.expired_at == "2025-12-31"+ assert result.workspaces.enabled is True+ assert result.workspaces.limit == 5+ assert result.workspaces.size == 2+ mock_external_service_dependencies["enterprise_service"].get_info.assert_called_once()++ def test_get_license_non_enterprise_is_unconstrained(+ self, db_session_with_containers: Session, mock_external_service_dependencies+ ):+ """Non-enterprise deployments have no license, so limits are unconstrained."""+ with patch("services.feature_service.dify_config") as mock_config:+ mock_config.ENTERPRISE_ENABLED = False++ result = FeatureService.get_license()++ assert isinstance(result, LicenseModel)+ assert result.status == LicenseStatus.NONE+ assert result.workspaces.is_available() is True+ assert result.seats.is_available() is True+ mock_external_service_dependencies["enterprise_service"].get_info.assert_not_called()+def test_get_system_features_basic_config(self, db_session_with_containers: Session, mock_external_service_dependencies):@@ -408,12 +448,14 @@ class TestFeatureService:"""# Arrange: Setup basic config mock (no enterprise)with patch("services.feature_service.dify_config") as mock_config:+ mock_config.DEPLOYMENT_EDITION = DeploymentEdition.COMMUNITYmock_config.ENTERPRISE_ENABLED = Falsemock_config.MARKETPLACE_ENABLED = Falsemock_config.ENABLE_EMAIL_CODE_LOGIN = Truemock_config.ENABLE_EMAIL_PASSWORD_LOGIN = Truemock_config.ENABLE_SOCIAL_OAUTH_LOGIN = Falsemock_config.ENABLE_COLLABORATION_MODE = False+ mock_config.ENABLE_CHANGE_EMAIL = Truemock_config.ALLOW_REGISTER = Truemock_config.ALLOW_CREATE_WORKSPACE = Truemock_config.MAIL_TYPE = "smtp"@@ -611,11 +653,13 @@ class TestFeatureService:"""# Arrange: Setup enterprise disabled mockwith patch("services.feature_service.dify_config") as mock_config:+ mock_config.DEPLOYMENT_EDITION = DeploymentEdition.COMMUNITYmock_config.ENTERPRISE_ENABLED = Falsemock_config.MARKETPLACE_ENABLED = Truemock_config.ENABLE_EMAIL_CODE_LOGIN = Falsemock_config.ENABLE_EMAIL_PASSWORD_LOGIN = Truemock_config.ENABLE_SOCIAL_OAUTH_LOGIN = True+ mock_config.ENABLE_CHANGE_EMAIL = Truemock_config.ALLOW_REGISTER = Falsemock_config.ALLOW_CREATE_WORKSPACE = Falsemock_config.MAIL_TYPE = None@@ -650,8 +694,8 @@ class TestFeatureService:# Verify default license statusassert result.license.status == "none"- assert result.license.expired_at == ""- assert result.license.workspaces.enabled is False+ assert not hasattr(result.license, "expired_at")+ assert not hasattr(result.license, "workspaces")# Verify no enterprise service callsmock_external_service_dependencies["enterprise_service"].get_info.assert_not_called()@@ -840,6 +884,7 @@ class TestFeatureService:"""# Arrange: Setup edge case webapp auth mock with proper configwith patch("services.feature_service.dify_config") as mock_config:+ mock_config.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISEmock_config.ENTERPRISE_ENABLED = Truemock_config.MARKETPLACE_ENABLED = Falsemock_config.ENABLE_EMAIL_CODE_LOGIN = False@@ -960,6 +1005,7 @@ class TestFeatureService:# Test case 1: Official only scopewith patch("services.feature_service.dify_config") as mock_config:+ mock_config.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISEmock_config.ENTERPRISE_ENABLED = Truemock_config.MARKETPLACE_ENABLED = Falsemock_config.ENABLE_EMAIL_CODE_LOGIN = False@@ -983,6 +1029,7 @@ class TestFeatureService:# Test case 2: All plugins scopewith patch("services.feature_service.dify_config") as mock_config:+ mock_config.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISEmock_config.ENTERPRISE_ENABLED = Truemock_config.MARKETPLACE_ENABLED = Falsemock_config.ENABLE_EMAIL_CODE_LOGIN = False@@ -1003,6 +1050,7 @@ class TestFeatureService:# Test case 3: Specific partners scopewith patch("services.feature_service.dify_config") as mock_config:+ mock_config.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISEmock_config.ENTERPRISE_ENABLED = Truemock_config.MARKETPLACE_ENABLED = Falsemock_config.ENABLE_EMAIL_CODE_LOGIN = False@@ -1026,6 +1074,7 @@ class TestFeatureService:# Test case 4: None scopewith patch("services.feature_service.dify_config") as mock_config:+ mock_config.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISEmock_config.ENTERPRISE_ENABLED = Truemock_config.MARKETPLACE_ENABLED = Falsemock_config.ENABLE_EMAIL_CODE_LOGIN = False@@ -1118,24 +1167,19 @@ class TestFeatureService:}}- # Act: Execute the method under test- result = FeatureService.get_system_features(is_authenticated=True)+ # Act: Execute the authenticated license accessor+ result = FeatureService.get_license()# Assert: Verify the expected outcomesassert result is not None- assert isinstance(result, SystemFeatureModel)+ assert isinstance(result, LicenseModel)- # Verify license status- assert result.license.status == "inactive"- assert result.license.expired_at == ""- assert result.license.workspaces.enabled is False- assert result.license.workspaces.size == 0- assert result.license.workspaces.limit == 0-- # Verify enterprise features- assert result.branding.enabled is True- assert result.webapp_auth.enabled is True- assert result.enable_change_email is False+ # Verify license status and detail+ assert result.status == "inactive"+ assert result.expired_at == ""+ assert result.workspaces.enabled is False+ assert result.workspaces.size == 0+ assert result.workspaces.limit == 0# Verify mock interactionsmock_external_service_dependencies["enterprise_service"].get_info.assert_called_once()@@ -1154,6 +1198,7 @@ class TestFeatureService:"""# Arrange: Setup partial enterprise info mock with proper configwith patch("services.feature_service.dify_config") as mock_config:+ mock_config.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISEmock_config.ENTERPRISE_ENABLED = Truemock_config.MARKETPLACE_ENABLED = Falsemock_config.ENABLE_EMAIL_CODE_LOGIN = False@@ -1200,8 +1245,8 @@ class TestFeatureService:# Verify default license statusassert result.license.status == "none"- assert result.license.expired_at == ""- assert result.license.workspaces.enabled is False+ assert not hasattr(result.license, "expired_at")+ assert not hasattr(result.license, "workspaces")# Verify default plugin installation permissionassert result.plugin_installation_permission.plugin_installation_scope == "all"@@ -1283,6 +1328,7 @@ class TestFeatureService:"""# Arrange: Setup edge case protocols mock with proper configwith patch("services.feature_service.dify_config") as mock_config:+ mock_config.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISEmock_config.ENTERPRISE_ENABLED = Truemock_config.MARKETPLACE_ENABLED = Falsemock_config.ENABLE_EMAIL_CODE_LOGIN = False@@ -1493,24 +1539,19 @@ class TestFeatureService:}}- # Act: Execute the method under test- result = FeatureService.get_system_features(is_authenticated=True)+ # Act: Execute the authenticated license accessor+ result = FeatureService.get_license()# Assert: Verify the expected outcomesassert result is not None- assert isinstance(result, SystemFeatureModel)-- # Verify license status- assert result.license.status == "expired"- assert result.license.expired_at == "2023-12-31"- assert result.license.workspaces.enabled is False- assert result.license.workspaces.size == 0- assert result.license.workspaces.limit == 0+ assert isinstance(result, LicenseModel)- # Verify enterprise features- assert result.branding.enabled is True- assert result.webapp_auth.enabled is True- assert result.enable_change_email is False+ # Verify license status and detail+ assert result.status == "expired"+ assert result.expired_at == "2023-12-31"+ assert result.workspaces.enabled is False+ assert result.workspaces.size == 0+ assert result.workspaces.limit == 0# Verify mock interactionsmock_external_service_dependencies["enterprise_service"].get_info.assert_called_once()@@ -1587,6 +1628,7 @@ class TestFeatureService:"""# Arrange: Setup edge case branding mock with proper configwith patch("services.feature_service.dify_config") as mock_config:+ mock_config.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISEmock_config.ENTERPRISE_ENABLED = Truemock_config.MARKETPLACE_ENABLED = Falsemock_config.ENABLE_EMAIL_CODE_LOGIN = False@@ -1776,6 +1818,7 @@ class TestFeatureService:"""# Arrange: Setup lost license mock with proper configwith patch("services.feature_service.dify_config") as mock_config:+ mock_config.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISEmock_config.ENTERPRISE_ENABLED = Truemock_config.MARKETPLACE_ENABLED = Falsemock_config.ENABLE_EMAIL_CODE_LOGIN = False@@ -1787,7 +1830,7 @@ class TestFeatureService:mock_config.PLUGIN_MAX_PACKAGE_SIZE = 100mock_external_service_dependencies["enterprise_service"].get_info.return_value = {- "license": {"status": "lost", "expired_at": None, "plan": None}+ "License": {"status": "lost"}}# Act: Execute the method under test@@ -1809,6 +1852,7 @@ class TestFeatureService:assert result.enable_email_password_login is Trueassert result.is_allow_register is Falseassert result.is_allow_create_workspace is False+ assert result.license.status == LicenseStatus.LOST# Verify mock interactionsmock_external_service_dependencies["enterprise_service"].get_info.assert_called_once()diff --git a/api/tests/test_containers_integration_tests/services/test_workspace_service.py b/api/tests/test_containers_integration_tests/services/test_workspace_service.pyindex bbbbd735e59..f22775a13eb 100644--- a/api/tests/test_containers_integration_tests/services/test_workspace_service.py+++ b/api/tests/test_containers_integration_tests/services/test_workspace_service.py@@ -6,6 +6,7 @@ import pytestfrom faker import Fakerfrom sqlalchemy.orm import Session+from enums.deployment_edition import DeploymentEditionfrom models import Account, Tenant, TenantAccountJoin, TenantAccountRolefrom services.credit_pool_service import CreditPoolBalancefrom services.workspace_service import WorkspaceService@@ -611,7 +612,7 @@ class TestWorkspaceService:db_session_with_containers, mock_external_service_dependencies)- mock_external_service_dependencies["dify_config"].EDITION = "SELF_HOSTED"+ mock_external_service_dependencies["dify_config"].DEPLOYMENT_EDITION = DeploymentEdition.COMMUNITYmock_external_service_dependencies["feature_service"].get_features.return_value.can_replace_logo = Falsemock_external_service_dependencies["tenant_service"].has_roles.return_value = False@@ -632,7 +633,7 @@ class TestWorkspaceService:db_session_with_containers, mock_external_service_dependencies)- mock_external_service_dependencies["dify_config"].EDITION = "CLOUD"+ mock_external_service_dependencies["dify_config"].DEPLOYMENT_EDITION = DeploymentEdition.CLOUDfeature = mock_external_service_dependencies["feature_service"].get_features.return_valuefeature.can_replace_logo = Falsefeature.next_credit_reset_date = "2025-02-01"@@ -657,7 +658,7 @@ class TestWorkspaceService:db_session_with_containers, mock_external_service_dependencies)- mock_external_service_dependencies["dify_config"].EDITION = "CLOUD"+ mock_external_service_dependencies["dify_config"].DEPLOYMENT_EDITION = DeploymentEdition.CLOUDfeature = mock_external_service_dependencies["feature_service"].get_features.return_valuefeature.can_replace_logo = Falsefeature.next_credit_reset_date = "2025-02-01"@@ -685,7 +686,7 @@ class TestWorkspaceService:db_session_with_containers, mock_external_service_dependencies)- mock_external_service_dependencies["dify_config"].EDITION = "CLOUD"+ mock_external_service_dependencies["dify_config"].DEPLOYMENT_EDITION = DeploymentEdition.CLOUDfeature = mock_external_service_dependencies["feature_service"].get_features.return_valuefeature.can_replace_logo = Falsefeature.next_credit_reset_date = "2025-02-01"@@ -713,7 +714,7 @@ class TestWorkspaceService:db_session_with_containers, mock_external_service_dependencies)- mock_external_service_dependencies["dify_config"].EDITION = "CLOUD"+ mock_external_service_dependencies["dify_config"].DEPLOYMENT_EDITION = DeploymentEdition.CLOUDfeature = mock_external_service_dependencies["feature_service"].get_features.return_valuefeature.can_replace_logo = Falsefeature.next_credit_reset_date = "2025-02-01"@@ -749,7 +750,7 @@ class TestWorkspaceService:db_session_with_containers, mock_external_service_dependencies)- mock_external_service_dependencies["dify_config"].EDITION = "CLOUD"+ mock_external_service_dependencies["dify_config"].DEPLOYMENT_EDITION = DeploymentEdition.CLOUDfeature = mock_external_service_dependencies["feature_service"].get_features.return_valuefeature.can_replace_logo = Falsefeature.next_credit_reset_date = "2025-02-01"@@ -779,7 +780,7 @@ class TestWorkspaceService:db_session_with_containers, mock_external_service_dependencies)- mock_external_service_dependencies["dify_config"].EDITION = "CLOUD"+ mock_external_service_dependencies["dify_config"].DEPLOYMENT_EDITION = DeploymentEdition.CLOUDfeature = mock_external_service_dependencies["feature_service"].get_features.return_valuefeature.can_replace_logo = Falsefeature.next_credit_reset_date = "2025-02-01"@@ -808,7 +809,7 @@ class TestWorkspaceService:db_session_with_containers, mock_external_service_dependencies)- mock_external_service_dependencies["dify_config"].EDITION = "CLOUD"+ mock_external_service_dependencies["dify_config"].DEPLOYMENT_EDITION = DeploymentEdition.CLOUDfeature = mock_external_service_dependencies["feature_service"].get_features.return_valuefeature.can_replace_logo = Falsefeature.next_credit_reset_date = "2025-02-01"diff --git a/api/tests/unit_tests/controllers/console/app/test_app_import_api.py b/api/tests/unit_tests/controllers/console/app/test_app_import_api.pyindex 3b675600539..e60656201ff 100644--- a/api/tests/unit_tests/controllers/console/app/test_app_import_api.py+++ b/api/tests/unit_tests/controllers/console/app/test_app_import_api.py@@ -13,6 +13,7 @@ from sqlalchemy import Engine, eventfrom sqlalchemy.orm import Sessionfrom controllers.console.app import app_import as app_import_module+from enums.deployment_edition import DeploymentEditionfrom models.account import Accountfrom models.base import TypeBasefrom models.engine import db@@ -47,7 +48,10 @@ class _Result:def _install_features(monkeypatch: pytest.MonkeyPatch, enabled: bool) -> None:- features = SystemFeatureModel(webapp_auth=WebAppAuthModel(enabled=enabled))+ features = SystemFeatureModel(+ deployment_edition=DeploymentEdition.COMMUNITY,+ webapp_auth=WebAppAuthModel(enabled=enabled),+ )monkeypatch.setattr(app_import_module.FeatureService, "get_system_features", lambda: features)diff --git a/api/tests/unit_tests/controllers/console/auth/test_email_register.py b/api/tests/unit_tests/controllers/console/auth/test_email_register.pyindex 468d98ab377..4c0b27d554f 100644--- a/api/tests/unit_tests/controllers/console/auth/test_email_register.py+++ b/api/tests/unit_tests/controllers/console/auth/test_email_register.py@@ -11,6 +11,7 @@ from controllers.console.auth.email_register import (EmailRegisterResetApi,EmailRegisterSendEmailApi,)+from enums.deployment_edition import DeploymentEditionfrom services.feature_service import SystemFeatureModel@@ -34,7 +35,11 @@ class TestEmailRegisterSendEmailApi:mock_account = MagicMock()mock_get_account.return_value = mock_account- feature_flags = SystemFeatureModel(enable_email_password_login=True, is_allow_register=True)+ feature_flags = SystemFeatureModel(+ deployment_edition=DeploymentEdition.COMMUNITY,+ enable_email_password_login=True,+ is_allow_register=True,+ )with (patch("controllers.console.auth.email_register.dify_config.BILLING_ENABLED", True),patch("controllers.console.wraps.dify_config.EDITION", "CLOUD"),@@ -75,7 +80,11 @@ class TestEmailRegisterCheckApi:mock_get_data.return_value = {"email": "[email protected]", "code": "4321"}mock_generate_token.return_value = (None, "new-token")- feature_flags = SystemFeatureModel(enable_email_password_login=True, is_allow_register=True)+ feature_flags = SystemFeatureModel(+ deployment_edition=DeploymentEdition.COMMUNITY,+ enable_email_password_login=True,+ is_allow_register=True,+ )with (patch("controllers.console.wraps.dify_config.EDITION", "CLOUD"),patch("controllers.console.wraps.FeatureService.get_system_features", return_value=feature_flags),@@ -123,7 +132,11 @@ class TestEmailRegisterResetApi:mock_login.return_value = token_pairmock_get_account.return_value = None- feature_flags = SystemFeatureModel(enable_email_password_login=True, is_allow_register=True)+ feature_flags = SystemFeatureModel(+ deployment_edition=DeploymentEdition.COMMUNITY,+ enable_email_password_login=True,+ is_allow_register=True,+ )with (patch("controllers.console.wraps.dify_config.EDITION", "CLOUD"),patch("controllers.console.wraps.FeatureService.get_system_features", return_value=feature_flags),@@ -171,7 +184,11 @@ class TestEmailRegisterResetApi:mock_login.return_value = token_pairmock_get_account.return_value = None- feature_flags = SystemFeatureModel(enable_email_password_login=True, is_allow_register=True)+ feature_flags = SystemFeatureModel(+ deployment_edition=DeploymentEdition.COMMUNITY,+ enable_email_password_login=True,+ is_allow_register=True,+ )with (patch("controllers.console.wraps.dify_config.EDITION", "CLOUD"),patch("controllers.console.wraps.FeatureService.get_system_features", return_value=feature_flags),@@ -224,7 +241,11 @@ class TestEmailRegisterResetApi:mock_login.return_value = token_pairmock_get_account.return_value = None- feature_flags = SystemFeatureModel(enable_email_password_login=True, is_allow_register=True)+ feature_flags = SystemFeatureModel(+ deployment_edition=DeploymentEdition.COMMUNITY,+ enable_email_password_login=True,+ is_allow_register=True,+ )with (patch("controllers.console.wraps.dify_config.EDITION", "CLOUD"),patch("controllers.console.wraps.FeatureService.get_system_features", return_value=feature_flags),diff --git a/api/tests/unit_tests/controllers/console/auth/test_email_verification.py b/api/tests/unit_tests/controllers/console/auth/test_email_verification.pyindex e56ed48bcfe..cb79ccc1835 100644--- a/api/tests/unit_tests/controllers/console/auth/test_email_verification.py+++ b/api/tests/unit_tests/controllers/console/auth/test_email_verification.py@@ -485,10 +485,12 @@ class TestEmailCodeLoginApi:@patch("controllers.console.auth.login.AccountService.revoke_email_code_login_token")@patch("controllers.console.auth.login.AccountService.get_user_through_email")@patch("controllers.console.auth.login.TenantService.get_join_tenants")+ @patch("controllers.console.auth.login.FeatureService.get_license")@patch("controllers.console.auth.login.FeatureService.get_system_features")def test_email_code_login_workspace_limit_exceeded(self,mock_get_features,+ mock_get_license,mock_get_tenants,mock_get_user,mock_revoke_token,@@ -507,9 +509,7 @@ class TestEmailCodeLoginApi:mock_get_data.return_value = {"email": "[email protected]", "code": "123456"}mock_get_user.return_value = mock_accountmock_get_tenants.return_value = []- mock_features = MagicMock()- mock_features.license.workspaces.is_available.return_value = False- mock_get_features.return_value = mock_features+ mock_get_license.return_value.workspaces.is_available.return_value = False# Act & Assertwith app.test_request_context(diff --git a/api/tests/unit_tests/controllers/console/auth/test_forgot_password.py b/api/tests/unit_tests/controllers/console/auth/test_forgot_password.pyindex 5253d0dfe06..48a6b98a1c3 100644--- a/api/tests/unit_tests/controllers/console/auth/test_forgot_password.py+++ b/api/tests/unit_tests/controllers/console/auth/test_forgot_password.py@@ -13,6 +13,7 @@ from controllers.console.auth.forgot_password import (ForgotPasswordResetApi,ForgotPasswordSendEmailApi,)+from enums.deployment_edition import DeploymentEditionfrom models.account import Accountfrom models.engine import dbfrom services.feature_service import SystemFeatureModel@@ -46,8 +47,15 @@ class TestForgotPasswordSendEmailApi:mock_get_account.return_value = mock_accountmock_send_email.return_value = "token-123"- wraps_features = SystemFeatureModel(enable_email_password_login=True, is_allow_register=True)- controller_features = SystemFeatureModel(is_allow_register=True)+ wraps_features = SystemFeatureModel(+ deployment_edition=DeploymentEdition.COMMUNITY,+ enable_email_password_login=True,+ is_allow_register=True,+ )+ controller_features = SystemFeatureModel(+ deployment_edition=DeploymentEdition.COMMUNITY,+ is_allow_register=True,+ )with (patch("controllers.console.auth.forgot_password.FeatureService.get_system_features",@@ -95,7 +103,10 @@ class TestForgotPasswordCheckApi:mock_get_data.return_value = {"email": "[email protected]", "code": "4321"}mock_generate_token.return_value = (None, "new-token")- wraps_features = SystemFeatureModel(enable_email_password_login=True)+ wraps_features = SystemFeatureModel(+ deployment_edition=DeploymentEdition.COMMUNITY,+ enable_email_password_login=True,+ )with (patch("controllers.console.wraps.dify_config.EDITION", "CLOUD"),patch("controllers.console.wraps.FeatureService.get_system_features", return_value=wraps_features),@@ -138,7 +149,10 @@ class TestForgotPasswordResetApi:db.session.commit()mock_get_account.return_value = account- wraps_features = SystemFeatureModel(enable_email_password_login=True)+ wraps_features = SystemFeatureModel(+ deployment_edition=DeploymentEdition.COMMUNITY,+ enable_email_password_login=True,+ )with (patch("controllers.console.wraps.dify_config.EDITION", "CLOUD"),patch("controllers.console.wraps.FeatureService.get_system_features", return_value=wraps_features),diff --git a/api/tests/unit_tests/controllers/console/auth/test_login_logout.py b/api/tests/unit_tests/controllers/console/auth/test_login_logout.pyindex ecb3e694cd3..cb0419c4acc 100644--- a/api/tests/unit_tests/controllers/console/auth/test_login_logout.py+++ b/api/tests/unit_tests/controllers/console/auth/test_login_logout.py@@ -343,10 +343,12 @@ class TestLoginApi:@patch("controllers.console.auth.login.RegisterService.get_invitation_with_case_fallback")@patch("controllers.console.auth.login.AccountService.authenticate")@patch("controllers.console.auth.login.TenantService.get_join_tenants")+ @patch("controllers.console.auth.login.FeatureService.get_license")@patch("controllers.console.auth.login.FeatureService.get_system_features")def test_login_fails_when_no_workspace_and_limit_exceeded(self,mock_get_features: MagicMock,+ mock_get_license: MagicMock,mock_get_tenants: MagicMock,mock_authenticate: MagicMock,mock_get_invitation: MagicMock,@@ -370,8 +372,8 @@ class TestLoginApi:mock_features = MagicMock()mock_features.is_allow_create_workspace = True- mock_features.license.workspaces.is_available.return_value = Falsemock_get_features.return_value = mock_features+ mock_get_license.return_value.workspaces.is_available.return_value = False# Act & Assertwith app.test_request_context(diff --git a/api/tests/unit_tests/controllers/console/auth/test_password_reset.py b/api/tests/unit_tests/controllers/console/auth/test_password_reset.pyindex 0ee9cf5248b..6da8cb5a51d 100644--- a/api/tests/unit_tests/controllers/console/auth/test_password_reset.py+++ b/api/tests/unit_tests/controllers/console/auth/test_password_reset.py@@ -23,6 +23,7 @@ from controllers.console.auth.forgot_password import (ForgotPasswordSendEmailApi,)from controllers.console.error import AccountNotFound, EmailSendIpLimitError+from enums.deployment_edition import DeploymentEditionfrom models.account import Account, Tenant, TenantAccountJoinfrom services.feature_service import SystemFeatureModel@@ -48,7 +49,10 @@ def enable_password_login_wrappers(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr("controllers.console.wraps.dify_config.EDITION", "CLOUD")monkeypatch.setattr("controllers.console.wraps.FeatureService.get_system_features",- lambda: SystemFeatureModel(enable_email_password_login=True),+ lambda: SystemFeatureModel(+ deployment_edition=DeploymentEdition.COMMUNITY,+ enable_email_password_login=True,+ ),)diff --git a/api/tests/unit_tests/controllers/console/test_feature.py b/api/tests/unit_tests/controllers/console/test_feature.pyindex 5b524cf9c64..66fb0b00f74 100644--- a/api/tests/unit_tests/controllers/console/test_feature.py+++ b/api/tests/unit_tests/controllers/console/test_feature.py@@ -2,14 +2,15 @@ from inspect import unwrapfrom pytest_mock import MockerFixture-from models import Account-from services.feature_service import FeatureModel, LimitationModel, SystemFeatureModel---def make_account() -> Account:- account = Account(name="Alice", email="[email protected]")- account.id = "account-1"- return account+from enums.deployment_edition import DeploymentEdition+from services.feature_service import (+ FeatureModel,+ LicenseLimitationModel,+ LicenseModel,+ LicenseStatus,+ LimitationModel,+ SystemFeatureModel,+)class TestFeatureApi:@@ -82,19 +83,16 @@ class TestAppDslVersionApi:class TestSystemFeatureApi:- def test_get_system_features_authenticated(self, mocker: MockerFixture):- """- current_user.is_authenticated == True- """+ def test_get_system_features_public(self, mocker: MockerFixture):+ """The public endpoint returns system features without any authentication input."""from controllers.console.feature import SystemFeatureApi- account = make_account()- current_account = mocker.patch(- "controllers.console.feature.current_account_with_tenant_optional",- return_value=(account, "tenant-123"),+ system_features = SystemFeatureModel(+ deployment_edition=DeploymentEdition.COMMUNITY,+ is_allow_register=True,+ enable_learn_app=True,)- system_features = SystemFeatureModel(is_allow_register=True, enable_learn_app=True)get_system_features = mocker.patch("controllers.console.feature.FeatureService.get_system_features",return_value=system_features,@@ -105,29 +103,28 @@ class TestSystemFeatureApi:assert result == system_features.model_dump()assert result["enable_learn_app"] is True- current_account.assert_called_once_with()- get_system_features.assert_called_once_with(is_authenticated=True)+ assert result["license"] == {"status": LicenseStatus.NONE}+ get_system_features.assert_called_once_with()- def test_get_system_features_unauthenticated(self, mocker: MockerFixture):- """- current_user.is_authenticated raises Unauthorized- """- from controllers.console.feature import SystemFeatureApi+class TestSystemFeatureLicenseApi:+ def test_get_license_success(self, mocker: MockerFixture):+ from controllers.console.feature import SystemFeatureLicenseApi- current_account = mocker.patch(- "controllers.console.feature.current_account_with_tenant_optional",- return_value=(None, None),+ license_model = LicenseModel(+ status=LicenseStatus.ACTIVE,+ expired_at="2025-12-31",+ seats=LicenseLimitationModel(enabled=True, limit=5, size=2),)- system_features = SystemFeatureModel(is_allow_register=False)- get_system_features = mocker.patch(- "controllers.console.feature.FeatureService.get_system_features",- return_value=system_features,+ get_license = mocker.patch(+ "controllers.console.feature.FeatureService.get_license",+ return_value=license_model,)- api = SystemFeatureApi()- result = api.get()+ api = SystemFeatureLicenseApi()+ raw_get = unwrap(SystemFeatureLicenseApi.get)+ result = raw_get(api)- assert result == system_features.model_dump()- current_account.assert_called_once_with()- get_system_features.assert_called_once_with(is_authenticated=False)+ assert result == license_model.model_dump()+ assert result["seats"] == {"enabled": True, "limit": 5, "size": 2}+ get_license.assert_called_once_with()diff --git a/api/tests/unit_tests/controllers/console/workspace/test_members.py b/api/tests/unit_tests/controllers/console/workspace/test_members.pyindex 652d1188ab4..58f8468429a 100644--- a/api/tests/unit_tests/controllers/console/workspace/test_members.py+++ b/api/tests/unit_tests/controllers/console/workspace/test_members.py@@ -323,8 +323,8 @@ class TestMemberInviteEmailApi:features = MagicMock()features.billing.enabled = Falsefeatures.workspace_members.enabled = False- system_features = MagicMock()- system_features.license.seats.is_available.return_value = False+ license_info = MagicMock()+ license_info.seats.is_available.return_value = Falsepayload = {"emails": ["[email protected]", "[email protected]"],@@ -336,9 +336,9 @@ class TestMemberInviteEmailApi:patch("controllers.console.workspace.members.FeatureService.get_features", return_value=features),patch("controllers.console.workspace.members._count_new_member_invites", return_value=(2, 2)),patch(- "controllers.console.workspace.members.FeatureService.get_system_features",- return_value=system_features,- ) as mock_get_system_features,+ "controllers.console.workspace.members.FeatureService.get_license",+ return_value=license_info,+ ) as mock_get_license,patch("controllers.console.workspace.members.RegisterService.invite_new_member") as mock_invite,patch("controllers.console.workspace.members.dify_config.ENTERPRISE_ENABLED", True),patch("controllers.console.workspace.members.dify_config.BILLING_ENABLED", False),@@ -346,8 +346,8 @@ class TestMemberInviteEmailApi:with pytest.raises(SeatsLimitExceeded):method(api, user)- mock_get_system_features.assert_called_once_with(is_authenticated=True)- system_features.license.seats.is_available.assert_called_once_with(2)+ mock_get_license.assert_called_once_with()+ license_info.seats.is_available.assert_called_once_with(2)mock_invite.assert_not_called()def test_invite_existing_accounts_do_not_consume_seats(self, app: Flask):@@ -359,8 +359,8 @@ class TestMemberInviteEmailApi:features = MagicMock()features.billing.enabled = Falsefeatures.workspace_members.enabled = False- system_features = MagicMock()- system_features.license.seats.is_available.return_value = False+ license_info = MagicMock()+ license_info.seats.is_available.return_value = Falsepayload = {"emails": ["[email protected]", "[email protected]"],@@ -372,9 +372,9 @@ class TestMemberInviteEmailApi:patch("controllers.console.workspace.members.FeatureService.get_features", return_value=features),patch("controllers.console.workspace.members._count_new_member_invites", return_value=(2, 0)),patch(- "controllers.console.workspace.members.FeatureService.get_system_features",- return_value=system_features,- ) as mock_get_system_features,+ "controllers.console.workspace.members.FeatureService.get_license",+ return_value=license_info,+ ) as mock_get_license,patch("controllers.console.workspace.members.RegisterService.invite_new_member", return_value="token") as mock_invite,@@ -386,8 +386,8 @@ class TestMemberInviteEmailApi:assert status == 201assert len(result["invitation_results"]) == 2- mock_get_system_features.assert_not_called()- system_features.license.seats.is_available.assert_not_called()+ mock_get_license.assert_not_called()+ license_info.seats.is_available.assert_not_called()assert mock_invite.call_count == 2def test_invite_mixed_accounts_with_available_seats(self, app: Flask):@@ -399,8 +399,8 @@ class TestMemberInviteEmailApi:features = MagicMock()features.billing.enabled = Falsefeatures.workspace_members.enabled = False- system_features = MagicMock()- system_features.license.seats.is_available.return_value = True+ license_info = MagicMock()+ license_info.seats.is_available.return_value = Truepayload = {"emails": ["[email protected]", "[email protected]"],@@ -412,9 +412,9 @@ class TestMemberInviteEmailApi:patch("controllers.console.workspace.members.FeatureService.get_features", return_value=features),patch("controllers.console.workspace.members._count_new_member_invites", return_value=(2, 1)),patch(- "controllers.console.workspace.members.FeatureService.get_system_features",- return_value=system_features,- ) as mock_get_system_features,+ "controllers.console.workspace.members.FeatureService.get_license",+ return_value=license_info,+ ) as mock_get_license,patch("controllers.console.workspace.members.RegisterService.invite_new_member", return_value="token") as mock_invite,@@ -426,8 +426,8 @@ class TestMemberInviteEmailApi:assert status == 201assert len(result["invitation_results"]) == 2- mock_get_system_features.assert_called_once_with(is_authenticated=True)- system_features.license.seats.is_available.assert_called_once_with(1)+ mock_get_license.assert_called_once_with()+ license_info.seats.is_available.assert_called_once_with(1)assert mock_invite.call_count == 2def test_invite_skips_seats_limit_when_enterprise_disabled(self, app: Flask):@@ -439,8 +439,8 @@ class TestMemberInviteEmailApi:features = MagicMock()features.billing.enabled = Falsefeatures.workspace_members.enabled = False- system_features = MagicMock()- system_features.license.seats.is_available.return_value = False+ license_info = MagicMock()+ license_info.seats.is_available.return_value = Falsepayload = {"emails": ["[email protected]"],@@ -452,9 +452,9 @@ class TestMemberInviteEmailApi:patch("controllers.console.workspace.members.FeatureService.get_features", return_value=features),patch("controllers.console.workspace.members._count_new_member_invites", return_value=(1, 1)),patch(- "controllers.console.workspace.members.FeatureService.get_system_features",- return_value=system_features,- ) as mock_get_system_features,+ "controllers.console.workspace.members.FeatureService.get_license",+ return_value=license_info,+ ) as mock_get_license,patch("controllers.console.workspace.members.RegisterService.invite_new_member", return_value="token"),patch("controllers.console.workspace.members.dify_config.CONSOLE_WEB_URL", "http://x"),patch("controllers.console.workspace.members.dify_config.ENTERPRISE_ENABLED", False),@@ -464,8 +464,8 @@ class TestMemberInviteEmailApi:assert status == 201assert result["invitation_results"][0]["status"] == "success"- mock_get_system_features.assert_not_called()- system_features.license.seats.is_available.assert_not_called()+ mock_get_license.assert_not_called()+ license_info.seats.is_available.assert_not_called()def test_invite_seats_error_is_reported_as_failed_result(self, app: Flask):api = MemberInviteEmailApi()@@ -476,8 +476,8 @@ class TestMemberInviteEmailApi:features = MagicMock()features.billing.enabled = Falsefeatures.workspace_members.enabled = False- system_features = MagicMock()- system_features.license.seats.is_available.return_value = True+ license_info = MagicMock()+ license_info.seats.is_available.return_value = Truepayload = {"emails": ["[email protected]"],@@ -489,8 +489,8 @@ class TestMemberInviteEmailApi:patch("controllers.console.workspace.members.FeatureService.get_features", return_value=features),patch("controllers.console.workspace.members._count_new_member_invites", return_value=(1, 1)),patch(- "controllers.console.workspace.members.FeatureService.get_system_features",- return_value=system_features,+ "controllers.console.workspace.members.FeatureService.get_license",+ return_value=license_info,),patch("controllers.console.workspace.members.RegisterService.invite_new_member",diff --git a/api/tests/unit_tests/controllers/openapi/auth/test_data.py b/api/tests/unit_tests/controllers/openapi/auth/test_data.pyindex 14167ec3ac7..7ee1a83ec00 100644--- a/api/tests/unit_tests/controllers/openapi/auth/test_data.py+++ b/api/tests/unit_tests/controllers/openapi/auth/test_data.py@@ -11,26 +11,27 @@ from controllers.openapi.auth.data import (RequestContext,current_edition,)+from enums.deployment_edition import DeploymentEditionfrom libs.oauth_bearer import Scope, TokenTypedef test_current_edition_saas():with patch("controllers.openapi.auth.data.dify_config") as cfg:- cfg.EDITION = "CLOUD"+ cfg.DEPLOYMENT_EDITION = DeploymentEdition.CLOUDcfg.ENTERPRISE_ENABLED = Trueassert current_edition() == Edition.SAASdef test_current_edition_ee():with patch("controllers.openapi.auth.data.dify_config") as cfg:- cfg.EDITION = "SELF_HOSTED"+ cfg.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISEcfg.ENTERPRISE_ENABLED = Trueassert current_edition() == Edition.EEdef test_current_edition_ce():with patch("controllers.openapi.auth.data.dify_config") as cfg:- cfg.EDITION = "SELF_HOSTED"+ cfg.DEPLOYMENT_EDITION = DeploymentEdition.COMMUNITYcfg.ENTERPRISE_ENABLED = Falseassert current_edition() == Edition.CEdiff --git a/api/tests/unit_tests/controllers/web/test_web_forgot_password.py b/api/tests/unit_tests/controllers/web/test_web_forgot_password.pyindex ffd51f81b0d..0d6fa621276 100644--- a/api/tests/unit_tests/controllers/web/test_web_forgot_password.py+++ b/api/tests/unit_tests/controllers/web/test_web_forgot_password.py@@ -14,6 +14,7 @@ from controllers.web.forgot_password import (ForgotPasswordResetApi,ForgotPasswordSendEmailApi,)+from enums.deployment_edition import DeploymentEditionfrom models.account import Accountfrom models.engine import dbfrom services.feature_service import SystemFeatureModel@@ -32,7 +33,10 @@ def database_app() -> Iterator[Flask]:@pytest.fixture(autouse=True)def _patch_wraps():- wraps_features = SystemFeatureModel(enable_email_password_login=True)+ wraps_features = SystemFeatureModel(+ deployment_edition=DeploymentEdition.COMMUNITY,+ enable_email_password_login=True,+ )with (patch("controllers.console.wraps.db") as mock_db,patch("controllers.console.wraps.dify_config.ENTERPRISE_ENABLED", True),diff --git a/api/tests/unit_tests/controllers/web/test_web_login.py b/api/tests/unit_tests/controllers/web/test_web_login.pyindex a91d4253aa8..2ccb6b832fc 100644--- a/api/tests/unit_tests/controllers/web/test_web_login.py+++ b/api/tests/unit_tests/controllers/web/test_web_login.py@@ -10,6 +10,7 @@ from werkzeug.exceptions import Unauthorizedimport services.errors.accountfrom controllers.web.login import EmailCodeLoginApi, EmailCodeLoginSendEmailApi, LoginApi, LoginStatusApi, LogoutApi+from enums.deployment_edition import DeploymentEditionfrom services.entities.auth_entities import LoginFailureReason@@ -34,7 +35,7 @@ def app():@pytest.fixture(autouse=True)def _patch_wraps():wraps_features = SimpleNamespace(enable_email_password_login=True)- console_dify = SimpleNamespace(ENTERPRISE_ENABLED=True, EDITION="CLOUD")+ console_dify = SimpleNamespace(ENTERPRISE_ENABLED=True, DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)web_dify = SimpleNamespace(ENTERPRISE_ENABLED=True)with (patch("controllers.console.wraps.db") as mock_db,diff --git a/api/tests/unit_tests/services/plugin/test_plugin_service_installation.py b/api/tests/unit_tests/services/plugin/test_plugin_service_installation.pyindex cd5927583ea..ca1a227b010 100644--- a/api/tests/unit_tests/services/plugin/test_plugin_service_installation.py+++ b/api/tests/unit_tests/services/plugin/test_plugin_service_installation.py@@ -19,6 +19,7 @@ from sqlalchemy.orm import Sessionfrom core.plugin.entities.plugin import PluginInstallationSourcefrom core.plugin.entities.plugin_daemon import PluginVerificationfrom core.plugin.plugin_service import PluginService+from enums.deployment_edition import DeploymentEditionfrom models import ProviderTypefrom models.engine import dbfrom models.provider import Provider, ProviderCredential, TenantPreferredModelProvider@@ -35,10 +36,11 @@ def _make_features(scope: PluginInstallationScope = PluginInstallationScope.ALL,) -> SystemFeatureModel:return SystemFeatureModel(+ deployment_edition=DeploymentEdition.COMMUNITY,plugin_installation_permission=PluginInstallationPermissionModel(restrict_to_marketplace_only=restrict_to_marketplace,plugin_installation_scope=scope,- )+ ),)diff --git a/api/tests/unit_tests/services/test_account_service.py b/api/tests/unit_tests/services/test_account_service.pyindex 13715f02820..bc8f4c763a7 100644--- a/api/tests/unit_tests/services/test_account_service.py+++ b/api/tests/unit_tests/services/test_account_service.py@@ -808,7 +808,7 @@ class TestTenantService:].get_system_features.return_value.is_allow_create_workspace = Truemock_external_service_dependencies["feature_service"- ].get_system_features.return_value.license.workspaces.is_available.return_value = True+ ].get_license.return_value.workspaces.is_available.return_value = Truemock_rsa_dependencies.return_value = "mock_public_key"with (@@ -1028,7 +1028,7 @@ class TestTenantService:].get_system_features.return_value.is_allow_create_workspace = Truemock_external_service_dependencies["feature_service"- ].get_system_features.return_value.license.workspaces.is_available.return_value = True+ ].get_license.return_value.workspaces.is_available.return_value = Truemock_tenant = MagicMock()mock_tenant.id = "tenant-rbac"@@ -1481,7 +1481,7 @@ class TestRegisterService:].get_system_features.return_value.is_allow_create_workspace = Truemock_external_service_dependencies["feature_service"- ].get_system_features.return_value.license.workspaces.is_available.return_value = True+ ].get_license.return_value.workspaces.is_available.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Mock AccountService.create_account@@ -1590,7 +1590,7 @@ class TestRegisterService:].get_system_features.return_value.is_allow_create_workspace = Truemock_external_service_dependencies["feature_service"- ].get_system_features.return_value.license.workspaces.is_available.return_value = True+ ].get_license.return_value.workspaces.is_available.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = Falsemock_account = TestAccountAssociatedDataFactory.create_account_mock(@@ -1629,7 +1629,7 @@ class TestRegisterService:].get_system_features.return_value.is_allow_create_workspace = Truemock_external_service_dependencies["feature_service"- ].get_system_features.return_value.license.workspaces.is_available.return_value = True+ ].get_license.return_value.workspaces.is_available.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = Falsemock_account = TestAccountAssociatedDataFactory.create_account_mock(@@ -1664,7 +1664,7 @@ class TestRegisterService:].get_system_features.return_value.is_allow_create_workspace = Truemock_external_service_dependencies["feature_service"- ].get_system_features.return_value.license.workspaces.is_available.return_value = True+ ].get_license.return_value.workspaces.is_available.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Mock AccountService.create_account and link_account_integrate@@ -1708,7 +1708,7 @@ class TestRegisterService:].get_system_features.return_value.is_allow_create_workspace = Truemock_external_service_dependencies["feature_service"- ].get_system_features.return_value.license.workspaces.is_available.return_value = True+ ].get_license.return_value.workspaces.is_available.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Mock AccountService.create_account@@ -1750,7 +1750,7 @@ class TestRegisterService:].get_system_features.return_value.is_allow_create_workspace = Truemock_external_service_dependencies["feature_service"- ].get_system_features.return_value.license.workspaces.is_available.return_value = True+ ].get_license.return_value.workspaces.is_available.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Mock AccountService.create_accountdiff --git a/api/tests/unit_tests/services/test_feature_service_change_email.py b/api/tests/unit_tests/services/test_feature_service_change_email.pynew file mode 100644index 00000000000..b6b6059cd57--- /dev/null+++ b/api/tests/unit_tests/services/test_feature_service_change_email.py@@ -0,0 +1,15 @@+import pytest++from services.feature_service import FeatureService++[email protected]("enabled", [False, True])+def test_get_system_features_reads_enable_change_email(+ monkeypatch: pytest.MonkeyPatch,+ enabled: bool,+) -> None:+ monkeypatch.setattr("services.feature_service.dify_config.ENABLE_CHANGE_EMAIL", enabled)++ result = FeatureService.get_system_features()++ assert result.enable_change_email is enableddiff --git a/api/tests/unit_tests/services/test_feature_service_deployment_edition.py b/api/tests/unit_tests/services/test_feature_service_deployment_edition.pynew file mode 100644index 00000000000..966247c610c--- /dev/null+++ b/api/tests/unit_tests/services/test_feature_service_deployment_edition.py@@ -0,0 +1,35 @@+import pytest+from pydantic import ValidationError++from enums.deployment_edition import DeploymentEdition+from services.feature_service import FeatureService, SystemFeatureModel+++def test_system_feature_model_requires_deployment_edition() -> None:+ with pytest.raises(ValidationError):+ SystemFeatureModel.model_validate({})+++ ("edition", "enterprise_enabled", "expected"),+ [+ ("SELF_HOSTED", False, DeploymentEdition.COMMUNITY),+ ("SELF_HOSTED", True, DeploymentEdition.ENTERPRISE),+ ("CLOUD", False, DeploymentEdition.CLOUD),+ ("CLOUD", True, DeploymentEdition.CLOUD),+ ],+)+def test_get_system_features_resolves_deployment_edition(+ monkeypatch: pytest.MonkeyPatch,+ edition: str,+ enterprise_enabled: bool,+ expected: DeploymentEdition,+) -> None:+ monkeypatch.setattr("services.feature_service.dify_config.EDITION", edition)+ monkeypatch.setattr("services.feature_service.dify_config.ENTERPRISE_ENABLED", enterprise_enabled)+ monkeypatch.setattr("services.feature_service.FeatureService._fulfill_params_from_enterprise", lambda *_: None)++ result = FeatureService.get_system_features()++ assert result.deployment_edition is expected+ assert result.model_dump(mode="json")["deployment_edition"] == expected.valuediff --git a/api/tests/unit_tests/services/test_feature_service_enable_app_deploy.py b/api/tests/unit_tests/services/test_feature_service_enable_app_deploy.pyindex 1c3b4fdbc1f..0f0fa1e1dba 100644--- a/api/tests/unit_tests/services/test_feature_service_enable_app_deploy.py+++ b/api/tests/unit_tests/services/test_feature_service_enable_app_deploy.py@@ -1,5 +1,6 @@import pytest+from enums.deployment_edition import DeploymentEditionfrom services import feature_service as feature_service_modulefrom services.feature_service import FeatureService, SystemFeatureModel@@ -29,7 +30,7 @@ def test_fulfill_params_from_enterprise_enable_app_deploy(staticmethod(lambda: enterprise_info),)- features = SystemFeatureModel()+ features = SystemFeatureModel(deployment_edition=DeploymentEdition.COMMUNITY)features.enable_app_deploy = initialFeatureService._fulfill_params_from_enterprise(features)diff --git a/api/tests/unit_tests/services/test_feature_service_knowledge_fs.py b/api/tests/unit_tests/services/test_feature_service_knowledge_fs.pyindex 63bfc739659..c151edf5406 100644--- a/api/tests/unit_tests/services/test_feature_service_knowledge_fs.py+++ b/api/tests/unit_tests/services/test_feature_service_knowledge_fs.py@@ -1,10 +1,11 @@import pytest+from enums.deployment_edition import DeploymentEditionfrom services.feature_service import FeatureService, SystemFeatureModeldef test_system_feature_model_disables_knowledge_fs_by_default() -> None:- assert SystemFeatureModel().knowledge_fs_enabled is False+ assert SystemFeatureModel(deployment_edition=DeploymentEdition.COMMUNITY).knowledge_fs_enabled is False@pytest.mark.parametrize("enabled", [False, True])diff --git a/api/tests/unit_tests/services/test_feature_service_learn_app.py b/api/tests/unit_tests/services/test_feature_service_learn_app.pyindex 61616b84356..bc33bfabbc1 100644--- a/api/tests/unit_tests/services/test_feature_service_learn_app.py+++ b/api/tests/unit_tests/services/test_feature_service_learn_app.py@@ -1,12 +1,15 @@import pytest+from enums.deployment_edition import DeploymentEditionfrom services import feature_service as feature_service_modulefrom services.feature_service import FeatureService, SystemFeatureModeldef test_system_feature_model_defaults_enable_learn_app():- assert SystemFeatureModel().enable_learn_app is True- assert SystemFeatureModel().enable_step_by_step_tour is False+ system_features = SystemFeatureModel(deployment_edition=DeploymentEdition.COMMUNITY)++ assert system_features.enable_learn_app is True+ assert system_features.enable_step_by_step_tour is False@pytest.mark.parametrize("enabled", [True, False])diff --git a/api/tests/unit_tests/services/test_feature_service_licensed_seats.py b/api/tests/unit_tests/services/test_feature_service_licensed_seats.pyindex aa593f6279d..fb1a5139118 100644--- a/api/tests/unit_tests/services/test_feature_service_licensed_seats.py+++ b/api/tests/unit_tests/services/test_feature_service_licensed_seats.py@@ -1,38 +1,34 @@import pytestfrom services import feature_service as feature_service_module-from services.feature_service import FeatureService, SystemFeatureModel+from services.feature_service import FeatureService, LicenseModel, LicenseStatus_ENTERPRISE_INFO = {"License": {"licensedSeats": {"enabled": True, "limit": 3, "used": 1}}}-def test_fulfill_params_from_enterprise_parses_licensed_seats(monkeypatch: pytest.MonkeyPatch):- """Authenticated fill copies the licensed-seat quota out of the enterprise payload."""+def test_get_license_parses_licensed_seats(monkeypatch: pytest.MonkeyPatch):+ """The authenticated license accessor copies the licensed-seat quota out of the enterprise payload."""+ monkeypatch.setattr("services.feature_service.dify_config.ENTERPRISE_ENABLED", True)monkeypatch.setattr(feature_service_module.EnterpriseService,"get_info",staticmethod(lambda: _ENTERPRISE_INFO),)- features = SystemFeatureModel()- FeatureService._fulfill_params_from_enterprise(features, is_authenticated=True)+ license_model = FeatureService.get_license()- assert features.license.seats.enabled is True- assert features.license.seats.limit == 3- assert features.license.seats.size == 1+ assert isinstance(license_model, LicenseModel)+ assert license_model.seats.enabled is True+ assert license_model.seats.limit == 3+ assert license_model.seats.size == 1-def test_fulfill_params_from_enterprise_withholds_seats_when_unauthenticated(monkeypatch: pytest.MonkeyPatch):- """Seat counts are auth-gated: unauthenticated callers keep the zeroed default."""- monkeypatch.setattr(- feature_service_module.EnterpriseService,- "get_info",- staticmethod(lambda: _ENTERPRISE_INFO),- )+def test_get_license_non_enterprise_is_unconstrained(monkeypatch: pytest.MonkeyPatch):+ """Non-enterprise deployments have no license; seat allocation is unconstrained."""+ monkeypatch.setattr("services.feature_service.dify_config.ENTERPRISE_ENABLED", False)- features = SystemFeatureModel()- FeatureService._fulfill_params_from_enterprise(features, is_authenticated=False)+ license_model = FeatureService.get_license()- assert features.license.seats.enabled is False- assert features.license.seats.limit == 0- assert features.license.seats.size == 0+ assert license_model.status == LicenseStatus.NONE+ assert license_model.seats.enabled is False+ assert license_model.seats.is_available() is Truediff --git a/api/tests/unit_tests/services/test_feature_service_webapp_public_access.py b/api/tests/unit_tests/services/test_feature_service_webapp_public_access.pyindex a58aa44d323..510acd67332 100644--- a/api/tests/unit_tests/services/test_feature_service_webapp_public_access.py+++ b/api/tests/unit_tests/services/test_feature_service_webapp_public_access.py@@ -1,5 +1,6 @@import pytest+from enums.deployment_edition import DeploymentEditionfrom services.feature_service import FeatureService, SystemFeatureModel@@ -18,7 +19,7 @@ def test_fulfill_system_params_from_env_sets_allow_public_access():monkeypatch.setattr("services.feature_service.dify_config.WEBAPP_PUBLIC_ACCESS_ENABLED", env_value)- system_features = SystemFeatureModel()+ system_features = SystemFeatureModel(deployment_edition=DeploymentEdition.COMMUNITY)FeatureService._fulfill_system_params_from_env(system_features)assert system_features.webapp_auth.allow_public_access is expecteddiff --git a/api/tests/unit_tests/services/test_recommended_app_service.py b/api/tests/unit_tests/services/test_recommended_app_service.pyindex 5f08160f67f..827ded2d61a 100644--- a/api/tests/unit_tests/services/test_recommended_app_service.py+++ b/api/tests/unit_tests/services/test_recommended_app_service.py@@ -10,6 +10,7 @@ import pytestfrom sqlalchemy import selectfrom sqlalchemy.orm import Session+from enums.deployment_edition import DeploymentEditionfrom models.model import AccountTrialAppRecord, App, AppMode, TrialAppfrom services import recommended_app_service as service_modulefrom services.feature_service import SystemFeatureModel@@ -298,7 +299,10 @@ class TestRecommendedAppServiceGetDetail:sqlite_session: Session,) -> None:mock_config.HOSTED_FETCH_APP_TEMPLATES_MODE = "remote"- mock_feature_service.get_system_features.return_value = SystemFeatureModel(enable_trial_app=False)+ mock_feature_service.get_system_features.return_value = SystemFeatureModel(+ deployment_edition=DeploymentEdition.COMMUNITY,+ enable_trial_app=False,+ )cases: list[tuple[str, RecommendedAppPayload]] = [("complex-app",@@ -337,7 +341,10 @@ class TestRecommendedAppServiceGetDetail:mock_feature_service: MagicMock,sqlite_session: Session,) -> None:- mock_feature_service.get_system_features.return_value = SystemFeatureModel(enable_trial_app=False)+ mock_feature_service.get_system_features.return_value = SystemFeatureModel(+ deployment_edition=DeploymentEdition.COMMUNITY,+ enable_trial_app=False,+ )for mode in ["remote", "builtin", "db"]:mock_config.HOSTED_FETCH_APP_TEMPLATES_MODE = modedetail = _app_detail(app_id="test-app", name=f"App from {mode}")@@ -367,7 +374,10 @@ class TestRecommendedAppServiceGetLearnDifyApps:sqlite_session: Session,) -> None:mock_config.HOSTED_FETCH_APP_TEMPLATES_MODE = "remote"- mock_feature_service.get_system_features.return_value = SystemFeatureModel(enable_trial_app=False)+ mock_feature_service.get_system_features.return_value = SystemFeatureModel(+ deployment_edition=DeploymentEdition.COMMUNITY,+ enable_trial_app=False,+ )expected_app = RecommendedAppPayload(app_id="app-1", category="Workflow")mock_instance = MagicMock()mock_instance.get_learn_dify_apps.return_value = {@@ -402,7 +412,12 @@ class TestRecommendedAppServiceGetLearnDifyApps:monkeypatch.setattr(service_module.FeatureService,"get_system_features",- MagicMock(return_value=SystemFeatureModel(enable_trial_app=True)),+ MagicMock(+ return_value=SystemFeatureModel(+ deployment_edition=DeploymentEdition.COMMUNITY,+ enable_trial_app=True,+ )+ ),)can_trial_mock = MagicMock(return_value=True)monkeypatch.setattr(RecommendedAppService, "_can_trial_app", can_trial_mock)@@ -425,7 +440,12 @@ class TestRecommendedAppServiceTrialFeatures:monkeypatch.setattr(service_module.FeatureService,"get_system_features",- MagicMock(return_value=SystemFeatureModel(enable_trial_app=False)),+ MagicMock(+ return_value=SystemFeatureModel(+ deployment_edition=DeploymentEdition.COMMUNITY,+ enable_trial_app=False,+ )+ ),)result = RecommendedAppService.get_recommended_apps_and_categories("en-US", session=sqlite_session)@@ -456,7 +476,12 @@ class TestRecommendedAppServiceTrialFeatures:monkeypatch.setattr(service_module.FeatureService,"get_system_features",- MagicMock(return_value=SystemFeatureModel(enable_trial_app=True)),+ MagicMock(+ return_value=SystemFeatureModel(+ deployment_edition=DeploymentEdition.COMMUNITY,+ enable_trial_app=True,+ )+ ),)result = RecommendedAppService.get_recommended_apps_and_categories("ja-JP", session=sqlite_session)@@ -492,7 +517,12 @@ class TestRecommendedAppServiceTrialFeatures:monkeypatch.setattr(service_module.FeatureService,"get_system_features",- MagicMock(return_value=SystemFeatureModel(enable_trial_app=True)),+ MagicMock(+ return_value=SystemFeatureModel(+ deployment_edition=DeploymentEdition.COMMUNITY,+ enable_trial_app=True,+ )+ ),)result = RecommendedAppService.get_recommend_app_detail(app_id, session=sqlite_session)diff --git a/docker/envs/core-services/shared.env.example b/docker/envs/core-services/shared.env.exampleindex bf2c32d5b1d..5fe6ab974e1 100644--- a/docker/envs/core-services/shared.env.example+++ b/docker/envs/core-services/shared.env.example@@ -16,11 +16,21 @@ CHECK_UPDATE_URL=https://updates.dify.aiOPENAI_API_BASE=https://api.openai.com/v1MIGRATION_ENABLED=trueFILES_ACCESS_TIMEOUT=300+# System Features+MARKETPLACE_ENABLED=true+ENABLE_EMAIL_CODE_LOGIN=false+ENABLE_EMAIL_PASSWORD_LOGIN=true+ENABLE_SOCIAL_OAUTH_LOGIN=false# Remove `collaboration` from COMPOSE_PROFILES to stop the dedicated websocket service.ENABLE_COLLABORATION_MODE=true--# Learn app feature toggle+ALLOW_REGISTER=false+ALLOW_CREATE_WORKSPACE=false+ENABLE_CHANGE_EMAIL=true+ENABLE_TRIAL_APP=false+ENABLE_EXPLORE_BANNER=falseENABLE_LEARN_APP=true+ENABLE_STEP_BY_STEP_TOUR=false+RBAC_ENABLED=falseCELERY_BROKER_URL=redis://:difyai123456@redis:6379/1CELERY_TASK_ANNOTATIONS=nullAZURE_BLOB_ACCOUNT_URL=https://<your_account_name>.blob.core.windows.net@@ -90,6 +100,8 @@ WORKFLOW_LOG_CLEANUP_SPECIFIC_WORKFLOW_IDS=EXPOSE_PLUGIN_DEBUGGING_HOST=localhostEXPOSE_PLUGIN_DEBUGGING_PORT=5003DEPLOY_ENV=PRODUCTION+EDITION=SELF_HOSTED+ENTERPRISE_ENABLED=falseACCESS_TOKEN_EXPIRE_MINUTES=60REFRESH_TOKEN_EXPIRE_DAYS=30APP_DEFAULT_ACTIVE_REQUESTS=0diff --git a/docker/envs/core-services/web.env.example b/docker/envs/core-services/web.env.exampleindex 576e1673bc9..5c952f4af4c 100644--- a/docker/envs/core-services/web.env.example+++ b/docker/envs/core-services/web.env.example@@ -15,7 +15,6 @@ TEXT_GENERATION_TIMEOUT_MS=60000ALLOW_INLINE_STYLES=falseALLOW_UNSAFE_DATA_SCHEME=falseMAX_TREE_DEPTH=50-MARKETPLACE_ENABLED=trueMARKETPLACE_API_URL=https://marketplace.dify.aiINDEXING_MAX_SEGMENTATION_TOKENS_LENGTH=4000ALLOW_EMBED=falsediff --git a/lint.config.ts b/lint.config.tsindex 34c6182d80e..6ee726761a9 100644--- a/lint.config.ts+++ b/lint.config.ts@@ -660,7 +660,7 @@ export const lintConfig = {'error',{allowConstantExport: true,- allowExportNames: [],+ allowExportNames: ['viewport'],},],},diff --git a/oxlint-suppressions.json b/oxlint-suppressions.jsonindex fb2c46efaf5..0569de71067 100644--- a/oxlint-suppressions.json+++ b/oxlint-suppressions.json@@ -5951,11 +5951,6 @@"count": 1}},- "web/app/layout.tsx": {- "react/only-export-components": {- "count": 1- }- },"web/app/reset-password/check-code/page.tsx": {"jsx_a11y/click-events-have-key-events": {"count": 1diff --git a/packages/contracts/generated/api/console/system-features/orpc.gen.ts b/packages/contracts/generated/api/console/system-features/orpc.gen.tsindex aa1e3a88948..d9ebc5df2b4 100644--- a/packages/contracts/generated/api/console/system-features/orpc.gen.ts+++ b/packages/contracts/generated/api/console/system-features/orpc.gen.ts@@ -1,7 +1,31 @@// This file is auto-generated by @hey-api/openapi-tsimport { oc } from '@orpc/contract'-import { zGetSystemFeaturesResponse } from './zod.gen'+import { zGetSystemFeaturesLicenseResponse, zGetSystemFeaturesResponse } from './zod.gen'++/**+ * Get full license detail (status, expiry, workspace/seat usage)+ *+ * Get license status and usage detail+ * Authenticated counterpart to the license *status* exposed on the public+ * system-features endpoint.+ */+export const get = oc+ .route({+ description:+ 'Get license status and usage detail\nAuthenticated counterpart to the license *status* exposed on the public\nsystem-features endpoint.',+ inputStructure: 'detailed',+ method: 'GET',+ operationId: 'getSystemFeaturesLicense',+ path: '/system-features/license',+ summary: 'Get full license detail (status, expiry, workspace/seat usage)',+ tags: ['console'],+ })+ .output(zGetSystemFeaturesLicenseResponse)++export const license = {+ get,+}/*** Get system-wide feature configuration@@ -12,12 +36,13 @@ import { zGetSystemFeaturesResponse } from './zod.gen'** Authentication would create circular dependency (can't login without dashboard loading).*- * Only non-sensitive configuration data should be returned by this endpoint.+ * Only non-sensitive configuration data should be returned by this endpoint. Authenticated+ * license detail is served separately by SystemFeatureLicenseApi.*/-export const get = oc+export const get2 = oc.route({description:- "Get system-wide feature configuration\nNOTE: This endpoint is unauthenticated by design, as it provides system features\ndata required for dashboard initialization.\n\nAuthentication would create circular dependency (can't login without dashboard loading).\n\nOnly non-sensitive configuration data should be returned by this endpoint.",+ "Get system-wide feature configuration\nNOTE: This endpoint is unauthenticated by design, as it provides system features\ndata required for dashboard initialization.\n\nAuthentication would create circular dependency (can't login without dashboard loading).\n\nOnly non-sensitive configuration data should be returned by this endpoint. Authenticated\nlicense detail is served separately by SystemFeatureLicenseApi.",inputStructure: 'detailed',method: 'GET',operationId: 'getSystemFeatures',@@ -28,7 +53,8 @@ export const get = oc.output(zGetSystemFeaturesResponse)export const systemFeatures = {- get,+ get: get2,+ license,}export const contract = {diff --git a/packages/contracts/generated/api/console/system-features/types.gen.ts b/packages/contracts/generated/api/console/system-features/types.gen.tsindex 65652a60498..2f865c06736 100644--- a/packages/contracts/generated/api/console/system-features/types.gen.ts+++ b/packages/contracts/generated/api/console/system-features/types.gen.ts@@ -6,6 +6,7 @@ export type ClientOptions = {export type SystemFeatureModel = {branding: BrandingModel+ deployment_edition: DeploymentEditionenable_app_deploy: booleanenable_change_email: booleanenable_collaboration_mode: boolean@@ -22,7 +23,7 @@ export type SystemFeatureModel = {is_allow_register: booleanis_email_setup: booleanknowledge_fs_enabled: boolean- license: LicenseModel+ license: LicenseStatusModelmax_plugin_package_size: numberplugin_installation_permission: PluginInstallationPermissionModelplugin_manager: PluginManagerModel@@ -32,6 +33,13 @@ export type SystemFeatureModel = {webapp_auth: WebAppAuthModel}+export type LicenseModel = {+ expired_at: string+ seats: LicenseLimitationModel+ status: LicenseStatus+ workspaces: LicenseLimitationModel+}+export type BrandingModel = {application_title: stringenabled: boolean@@ -40,11 +48,10 @@ export type BrandingModel = {workspace_logo: string}-export type LicenseModel = {- expired_at: string- seats: LicenseLimitationModel+export type DeploymentEdition = 'CLOUD' | 'COMMUNITY' | 'ENTERPRISE'++export type LicenseStatusModel = {status: LicenseStatus- workspaces: LicenseLimitationModel}export type PluginInstallationPermissionModel = {@@ -95,3 +102,17 @@ export type GetSystemFeaturesResponses = {}export type GetSystemFeaturesResponse = GetSystemFeaturesResponses[keyof GetSystemFeaturesResponses]++export type GetSystemFeaturesLicenseData = {+ body?: never+ path?: never+ query?: never+ url: '/system-features/license'+}++export type GetSystemFeaturesLicenseResponses = {+ 200: LicenseModel+}++export type GetSystemFeaturesLicenseResponse =+ GetSystemFeaturesLicenseResponses[keyof GetSystemFeaturesLicenseResponses]diff --git a/packages/contracts/generated/api/console/system-features/zod.gen.ts b/packages/contracts/generated/api/console/system-features/zod.gen.tsindex 8d2aa34ee22..1ef07bee0bd 100644--- a/packages/contracts/generated/api/console/system-features/zod.gen.ts+++ b/packages/contracts/generated/api/console/system-features/zod.gen.ts@@ -13,6 +13,13 @@ export const zBrandingModel = z.object({workspace_logo: z.string().default(''),})+/**+ * DeploymentEdition+ *+ * Enum representing the deployment edition of the platform.+ */+export const zDeploymentEdition = z.enum(['CLOUD', 'COMMUNITY', 'ENTERPRISE'])+/*** PluginManagerModel*/@@ -56,6 +63,13 @@ export const zLicenseModel = z.object({}),})+/**+ * LicenseStatusModel+ */+export const zLicenseStatusModel = z.object({+ status: zLicenseStatus.default('none'),+})+/*** PluginInstallationScope*/@@ -104,6 +118,7 @@ export const zSystemFeatureModel = z.object({login_page_logo: '',workspace_logo: '',}),+ deployment_edition: zDeploymentEdition,enable_app_deploy: z.boolean().default(false),enable_change_email: z.boolean().default(true),enable_collaboration_mode: z.boolean().default(true),@@ -120,20 +135,7 @@ export const zSystemFeatureModel = z.object({is_allow_register: z.boolean().default(false),is_email_setup: z.boolean().default(false),knowledge_fs_enabled: z.boolean().default(false),- license: zLicenseModel.default({- expired_at: '',- seats: {- enabled: false,- limit: 0,- size: 0,- },- status: 'none',- workspaces: {- enabled: false,- limit: 0,- size: 0,- },- }),+ license: zLicenseStatusModel.default({ status: 'none' }),max_plugin_package_size: z.int().default(15728640),plugin_installation_permission: zPluginInstallationPermissionModel.default({plugin_installation_scope: 'all',@@ -157,3 +159,8 @@ export const zSystemFeatureModel = z.object({* Success*/export const zGetSystemFeaturesResponse = zSystemFeatureModel++/**+ * Success+ */+export const zGetSystemFeaturesLicenseResponse = zLicenseModeldiff --git a/packages/contracts/generated/api/web/types.gen.ts b/packages/contracts/generated/api/web/types.gen.tsindex a593faced5c..3425dc64e5d 100644--- a/packages/contracts/generated/api/web/types.gen.ts+++ b/packages/contracts/generated/api/web/types.gen.ts@@ -118,6 +118,8 @@ export type ConversationRenamePayload = (name?: string | null}+export type DeploymentEdition = 'CLOUD' | 'COMMUNITY' | 'ENTERPRISE'+export type EmailCodeLoginSendPayload = {email: stringlanguage?: string | null@@ -300,21 +302,12 @@ export type JsonValueType = unknownexport type JsonValue2 = unknown-export type LicenseLimitationModel = {- enabled: boolean- limit: number- size: number-}+export type LicenseStatus = 'active' | 'expired' | 'expiring' | 'inactive' | 'lost' | 'none'-export type LicenseModel = {- expired_at: string- seats: LicenseLimitationModel+export type LicenseStatusModel = {status: LicenseStatus- workspaces: LicenseLimitationModel}-export type LicenseStatus = 'active' | 'expired' | 'expiring' | 'inactive' | 'lost' | 'none'-export type LoginPayload = {email: stringpassword: string@@ -510,6 +503,7 @@ export type SuggestedQuestionsResponse = {export type SystemFeatureModel = {branding: BrandingModel+ deployment_edition: DeploymentEditionenable_app_deploy: booleanenable_change_email: booleanenable_collaboration_mode: boolean@@ -526,7 +520,7 @@ export type SystemFeatureModel = {is_allow_register: booleanis_email_setup: booleanknowledge_fs_enabled: boolean- license: LicenseModel+ license: LicenseStatusModelmax_plugin_package_size: numberplugin_installation_permission: PluginInstallationPermissionModelplugin_manager: PluginManagerModeldiff --git a/packages/contracts/generated/api/web/zod.gen.ts b/packages/contracts/generated/api/web/zod.gen.tsindex b1504220f27..515245a69e3 100644--- a/packages/contracts/generated/api/web/zod.gen.ts+++ b/packages/contracts/generated/api/web/zod.gen.ts@@ -132,6 +132,13 @@ export const zConversationRenamePayload = z.intersection(}),)+/**+ * DeploymentEdition+ *+ * Enum representing the deployment edition of the platform.+ */+export const zDeploymentEdition = z.enum(['CLOUD', 'COMMUNITY', 'ENTERPRISE'])+/*** EmailCodeLoginSendPayload*/@@ -340,40 +347,16 @@ export const zHumanInputFormSubmitPayload = z.object({inputs: z.record(z.string(), zJsonValue2),})-/**- * LicenseLimitationModel- *- * - enabled: whether this limit is enforced- * - size: current usage count- * - limit: maximum allowed count; 0 means unlimited- */-export const zLicenseLimitationModel = z.object({- enabled: z.boolean().default(false),- limit: z.int().default(0),- size: z.int().default(0),-})-/*** LicenseStatus*/export const zLicenseStatus = z.enum(['active', 'expired', 'expiring', 'inactive', 'lost', 'none'])/**- * LicenseModel+ * LicenseStatusModel*/-export const zLicenseModel = z.object({- expired_at: z.string().default(''),- seats: zLicenseLimitationModel.default({- enabled: false,- limit: 0,- size: 0,- }),+export const zLicenseStatusModel = z.object({status: zLicenseStatus.default('none'),- workspaces: zLicenseLimitationModel.default({- enabled: false,- limit: 0,- size: 0,- }),})/**@@ -782,6 +765,7 @@ export const zSystemFeatureModel = z.object({login_page_logo: '',workspace_logo: '',}),+ deployment_edition: zDeploymentEdition,enable_app_deploy: z.boolean().default(false),enable_change_email: z.boolean().default(true),enable_collaboration_mode: z.boolean().default(true),@@ -798,20 +782,7 @@ export const zSystemFeatureModel = z.object({is_allow_register: z.boolean().default(false),is_email_setup: z.boolean().default(false),knowledge_fs_enabled: z.boolean().default(false),- license: zLicenseModel.default({- expired_at: '',- seats: {- enabled: false,- limit: 0,- size: 0,- },- status: 'none',- workspaces: {- enabled: false,- limit: 0,- size: 0,- },- }),+ license: zLicenseStatusModel.default({ status: 'none' }),max_plugin_package_size: z.int().default(15728640),plugin_installation_permission: zPluginInstallationPermissionModel.default({plugin_installation_scope: 'all',diff --git a/web/.env.example b/web/.env.exampleindex 64b8082bbfd..1c8ed103949 100644--- a/web/.env.example+++ b/web/.env.example@@ -1,9 +1,5 @@# For production release, change this to PRODUCTIONNEXT_PUBLIC_DEPLOY_ENV=DEVELOPMENT-# The deployment edition, SELF_HOSTED-NEXT_PUBLIC_EDITION=SELF_HOSTED-# Whether a self-hosted deployment runs Enterprise Edition-NEXT_PUBLIC_ENTERPRISE_ENABLED=false# The base path for the applicationNEXT_PUBLIC_BASE_PATH=# Server-only console API origin for server-side requests.@@ -114,20 +110,3 @@ NEXT_PUBLIC_WEB_PREFIX=# number of concurrencyNEXT_PUBLIC_BATCH_CONCURRENCY=5--# Cloud system-features frontend defaults.-# These values are only used when NEXT_PUBLIC_EDITION=CLOUD (IS_CLOUD_EDITION).-NEXT_PUBLIC_ENABLE_MARKETPLACE=true-NEXT_PUBLIC_ENABLE_EMAIL_CODE_LOGIN=true-NEXT_PUBLIC_ENABLE_EMAIL_PASSWORD_LOGIN=false-NEXT_PUBLIC_ENABLE_SOCIAL_OAUTH_LOGIN=true-NEXT_PUBLIC_ENABLE_COLLABORATION_MODE=false-NEXT_PUBLIC_ALLOW_REGISTER=true-NEXT_PUBLIC_ALLOW_CREATE_WORKSPACE=true-NEXT_PUBLIC_IS_EMAIL_SETUP=true-NEXT_PUBLIC_ENABLE_CHANGE_EMAIL=true-NEXT_PUBLIC_CREATORS_PLATFORM_FEATURES_ENABLED=true-NEXT_PUBLIC_ENABLE_TRIAL_APP=true-NEXT_PUBLIC_ENABLE_EXPLORE_BANNER=true-NEXT_PUBLIC_RBAC_ENABLED=false-NEXT_PUBLIC_KNOWLEDGE_FS_ENABLED=falsediff --git a/web/Dockerfile b/web/Dockerfileindex 72b2a50536b..d9e01580401 100644--- a/web/Dockerfile+++ b/web/Dockerfile@@ -49,7 +49,6 @@ RUN pnpm build && pnpm build:vinextFROM base AS productionENV NODE_ENV=production-ENV EDITION=SELF_HOSTEDENV DEPLOY_ENV=PRODUCTIONENV CONSOLE_API_URL=http://127.0.0.1:5001ENV APP_API_URL=http://127.0.0.1:5001diff --git a/web/__tests__/billing/billing-integration.test.tsx b/web/__tests__/billing/billing-integration.test.tsxindex d43b873a62a..8f3e21209fc 100644--- a/web/__tests__/billing/billing-integration.test.tsx+++ b/web/__tests__/billing/billing-integration.test.tsx@@ -1,3 +1,5 @@+import type { RenderOptions } from '@testing-library/react'+import type { ReactElement } from 'react'import type { UsagePlanInfo, UsageResetInfo } from '@/app/components/billing/type'import { screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'@@ -14,21 +16,21 @@ import TriggerEventsLimitModal from '@/app/components/billing/trigger-events-limimport { Plan } from '@/app/components/billing/type'import UpgradeBtn from '@/app/components/billing/upgrade-btn'import VectorSpaceFull from '@/app/components/billing/vector-space-full'-import { render } from '@/test/console/render'+import { createConsoleQueryWrapper } from '@/test/console/query-data'+import { render as renderWithConsoleState } from '@/test/console/render'++const render = (ui: ReactElement, options: RenderOptions = {}) => {+ const { wrapper } = createConsoleQueryWrapper({+ systemFeatures: { deployment_edition: 'CLOUD' },+ })+ return renderWithConsoleState(ui, { ...options, wrapper })+}let mockProviderCtx: Record<string, unknown> = {}let mockConsoleState: Record<string, unknown> = {}const mockSetShowPricingModal = vi.fn()const mockSetShowAccountSettingModal = vi.fn()-vi.mock('@/config', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/config')>()- return {- ...actual,- IS_CLOUD_EDITION: true,- }-})-vi.mock('@/context/provider-context', () => ({useProviderContext: () => mockProviderCtx,}))diff --git a/web/__tests__/billing/education-verification-flow.test.tsx b/web/__tests__/billing/education-verification-flow.test.tsxindex 1203cc106ae..6cbea5318fc 100644--- a/web/__tests__/billing/education-verification-flow.test.tsx+++ b/web/__tests__/billing/education-verification-flow.test.tsx@@ -1,3 +1,5 @@+import type { RenderOptions } from '@testing-library/react'+import type { ReactElement } from 'react'/*** Integration test: Education Verification Flow*@@ -14,7 +16,15 @@ import * as React from 'react'import { defaultPlan } from '@/app/components/billing/config'import PlanComp from '@/app/components/billing/plan'import { Plan } from '@/app/components/billing/type'-import { render } from '@/test/console/render'+import { createConsoleQueryWrapper } from '@/test/console/query-data'+import { render as renderWithConsoleState } from '@/test/console/render'++const render = (ui: ReactElement, options: RenderOptions = {}) => {+ const { wrapper } = createConsoleQueryWrapper({+ systemFeatures: { deployment_edition: 'CLOUD' },+ })+ return renderWithConsoleState(ui, { ...options, wrapper })+}// ─── Mock state ──────────────────────────────────────────────────────────────let mockProviderCtx: Record<string, unknown> = {}@@ -25,14 +35,6 @@ const mockRouterPush = vi.fn()const mockMutateAsync = vi.fn()const mockSetEducationVerifying = vi.hoisted(() => vi.fn())-vi.mock('@/config', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/config')>()- return {- ...actual,- IS_CLOUD_EDITION: true,- }-})-// ─── Context mocks ───────────────────────────────────────────────────────────vi.mock('@/context/provider-context', () => ({useProviderContext: () => mockProviderCtx,diff --git a/web/__tests__/billing/partner-stack-flow.test.tsx b/web/__tests__/billing/partner-stack-flow.test.tsxindex 95e2a5748a2..d5f89ee6859 100644--- a/web/__tests__/billing/partner-stack-flow.test.tsx+++ b/web/__tests__/billing/partner-stack-flow.test.tsx@@ -7,11 +7,15 @@* Covers URL param reading, cookie persistence, API bind on mount,* cookie cleanup after successful bind, and error handling for 400 status.*/-import { act, cleanup, render, renderHook, waitFor } from '@testing-library/react'+import { act, cleanup, renderHook, waitFor } from '@testing-library/react'import Cookies from 'js-cookie'import * as React from 'react'import usePSInfo from '@/app/components/billing/partner-stack/use-ps-info'import { PARTNER_STACK_CONFIG } from '@/config'+import { renderWithConsoleQuery } from '@/test/console/query-data'++const render = (ui: React.ReactElement) =>+ renderWithConsoleQuery(ui, { systemFeatures: { deployment_edition: 'CLOUD' } })// ─── Mock state ──────────────────────────────────────────────────────────────let mockSearchParams = new URLSearchParams()@@ -39,7 +43,6 @@ vi.mock('@/config', async (importOriginal) => {const actual = await importOriginal<Record<string, unknown>>()return {...actual,- IS_CLOUD_EDITION: true,PARTNER_STACK_CONFIG: {cookieName: 'partner_stack_info',saveCookieDays: 90,@@ -288,7 +291,7 @@ describe('Partner Stack Flow', () => {// ─── 4. PartnerStack Component Mount ────────────────────────────────────describe('PartnerStack component mount behavior', () => {- it('should call saveOrUpdate and bind on mount when IS_CLOUD_EDITION is true', async () => {+ it('should call saveOrUpdate and bind on mount', async () => {mockSearchParams = new URLSearchParams({ps_partner_key: 'mount-partner',ps_xid: 'mount-click',@@ -299,18 +302,13 @@ describe('Partner Stack Flow', () => {render(<PartnerStack />)- // The component calls saveOrUpdate and bind in useEffectawait waitFor(() => {- // Bind should have been calledexpect(mockMutateAsync).toHaveBeenCalledWith({partnerKey: 'mount-partner',clickId: 'mount-click',})+ expect(Cookies.get(PARTNER_STACK_CONFIG.cookieName)).toBeUndefined()})-- // Cookie should have been saved (saveOrUpdate was called before bind)- // After bind succeeds, cookie is removed- expect(Cookies.get(PARTNER_STACK_CONFIG.cookieName)).toBeUndefined()})it('should render nothing (return null)', async () => {diff --git a/web/__tests__/env.spec.ts b/web/__tests__/env.spec.tsindex 3a9f258a123..e2dcc0c2943 100644--- a/web/__tests__/env.spec.ts+++ b/web/__tests__/env.spec.ts@@ -1,6 +1,5 @@describe('env runtime transport', () => {const originalAgentV2Env = process.env.NEXT_PUBLIC_ENABLE_AGENT_V2- const originalRbacEnv = process.env.NEXT_PUBLIC_RBAC_ENABLEDbeforeEach(() => {vi.clearAllMocks()@@ -8,17 +7,12 @@ describe('env runtime transport', () => {vi.doUnmock('../utils/client')document.body.removeAttribute('data-enable-agent-v2')document.body.removeAttribute('data-enable-agent-v-2')- document.body.removeAttribute('data-rbac-enabled')delete process.env.NEXT_PUBLIC_ENABLE_AGENT_V2- delete process.env.NEXT_PUBLIC_RBAC_ENABLED})afterAll(() => {if (originalAgentV2Env === undefined) delete process.env.NEXT_PUBLIC_ENABLE_AGENT_V2else process.env.NEXT_PUBLIC_ENABLE_AGENT_V2 = originalAgentV2Env-- if (originalRbacEnv === undefined) delete process.env.NEXT_PUBLIC_RBAC_ENABLED- else process.env.NEXT_PUBLIC_RBAC_ENABLED = originalRbacEnv})it('should read NEXT_PUBLIC_ENABLE_AGENT_V2 from the browser runtime dataset key', async () => {@@ -29,14 +23,6 @@ describe('env runtime transport', () => {expect(env.NEXT_PUBLIC_ENABLE_AGENT_V2).toBe(true)})- it('should read NEXT_PUBLIC_RBAC_ENABLED from the browser runtime dataset key', async () => {- document.body.setAttribute('data-rbac-enabled', 'true')-- const { env } = await import('../env')-- expect(env.NEXT_PUBLIC_RBAC_ENABLED).toBe(true)- })-it('should emit the Agent v2 runtime dataset attribute from getDatasetMap on the server', async () => {process.env.NEXT_PUBLIC_ENABLE_AGENT_V2 = 'true'@@ -51,18 +37,4 @@ describe('env runtime transport', () => {expect(datasetMap['data-enable-agent-v2']).toBe(true)expect(datasetMap['data-enable-agent-v-2']).toBeUndefined()})-- it('should emit the RBAC runtime dataset attribute from getDatasetMap on the server', async () => {- process.env.NEXT_PUBLIC_RBAC_ENABLED = 'true'-- vi.doMock('../utils/client', () => ({- isClient: false,- isServer: true,- }))-- const { getDatasetMap } = await import('../env')- const datasetMap = getDatasetMap()-- expect(datasetMap['data-rbac-enabled']).toBe(true)- })})diff --git a/web/app/(commonLayout)/__tests__/hydration-boundary.spec.tsx b/web/app/(commonLayout)/__tests__/hydration-boundary.spec.tsxindex b34faae8248..13471dd863b 100644--- a/web/app/(commonLayout)/__tests__/hydration-boundary.spec.tsx+++ b/web/app/(commonLayout)/__tests__/hydration-boundary.spec.tsx@@ -1,12 +1,12 @@+import type { DehydratedState } from '@tanstack/react-query'import type { ReactElement } from 'react'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { render, screen } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'const mocks = vi.hoisted(() => ({- queryClient: undefined as QueryClient | undefined,+ rootQueryClient: undefined as QueryClient | undefined,profileQueryFn: vi.fn(),- systemFeaturesQueryFn: vi.fn(),workspaceQueryFn: vi.fn(),workspaceQueryOptions: vi.fn(),getServerConsoleClientContext: vi.fn(),@@ -18,9 +18,14 @@ const mocks = vi.hoisted(() => ({basePath: '',}))-vi.mock('@/context/query-client-server', () => ({- getQueryClientServer: () => mocks.queryClient,-}))+vi.mock('@/context/query-client-server', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/context/query-client-server')>()++ return {+ ...actual,+ getQueryClientServer: () => mocks.rootQueryClient,+ }+})vi.mock('@/next/headers', () => ({headers: () => mocks.headers(),@@ -58,19 +63,11 @@ vi.mock('@/service/server', () => ({},}))-vi.mock('@/features/system-features/server', () => ({- serverSystemFeaturesQueryOptions: () => ({- queryKey: ['console', 'system-features'],- queryFn: mocks.systemFeaturesQueryFn,- retry: false,- }),-}))-describe('CommonLayoutHydrationBoundary', () => {beforeEach(() => {vi.clearAllMocks()mocks.basePath = ''- mocks.queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ mocks.rootQueryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })mocks.headers.mockResolvedValue(new Headers({'x-dify-pathname': '/apps',@@ -94,7 +91,6 @@ describe('CommonLayoutHydrationBoundary', () => {currentEnv: 'DEVELOPMENT',},})- mocks.systemFeaturesQueryFn.mockResolvedValue({ branding: { enabled: false } })mocks.workspaceQueryFn.mockResolvedValue({ id: 'workspace-id', name: 'Workspace' })mocks.getServerConsoleClientContext.mockResolvedValue({cookie: 'session=abc',@@ -107,7 +103,7 @@ describe('CommonLayoutHydrationBoundary', () => {})})- it('should prefetch common layout queries and render children', async () => {+ it('should prefetch common layout queries', async () => {const { CommonLayoutHydrationBoundary } = await import('../hydration-boundary')const element = await CommonLayoutHydrationBoundary({@@ -121,7 +117,6 @@ describe('CommonLayoutHydrationBoundary', () => {)expect(screen.getByText('Common shell')).toBeInTheDocument()expect(mocks.profileQueryFn).toHaveBeenCalledTimes(1)- expect(mocks.systemFeaturesQueryFn).toHaveBeenCalledTimes(1)expect(mocks.getServerConsoleClientContext).toHaveBeenCalledTimes(1)expect(mocks.workspaceQueryOptions).toHaveBeenCalledWith({context: {@@ -133,6 +128,25 @@ describe('CommonLayoutHydrationBoundary', () => {expect(mocks.workspaceQueryFn).toHaveBeenCalledTimes(1)})+ it('should dehydrate only Common-owned queries', async () => {+ mocks.rootQueryClient?.setQueryData(['console', 'system-features'], {+ deployment_edition: 'CLOUD',+ })+ const { CommonLayoutHydrationBoundary } = await import('../hydration-boundary')++ const element = await CommonLayoutHydrationBoundary({ children: null })+ const state = (element as ReactElement<{ state: DehydratedState }>).props.state+ const queryKeys = state.queries.map((query) => query.queryKey)++ expect(queryKeys).toHaveLength(2)+ expect(queryKeys).toEqual(+ expect.arrayContaining([+ ['common', 'user-profile'],+ ['console', 'workspaces', 'current', 'post'],+ ]),+ )+ })+it('should redirect unauthorized users to the refresh route with the current path', async () => {mocks.basePath = '/workflow'mocks.profileQueryFn.mockRejectedValue(@@ -188,7 +202,6 @@ describe('CommonLayoutHydrationBoundary', () => {)expect(screen.getByText('Common shell')).toBeInTheDocument()expect(mocks.profileQueryFn).not.toHaveBeenCalled()- expect(mocks.systemFeaturesQueryFn).not.toHaveBeenCalled()expect(mocks.workspaceQueryFn).not.toHaveBeenCalled()})})diff --git a/web/app/(commonLayout)/__tests__/console-bootstrap-gate.spec.tsx b/web/app/(commonLayout)/__tests__/profile-bootstrap-gate.spec.tsxsimilarity index 68%rename from web/app/(commonLayout)/__tests__/console-bootstrap-gate.spec.tsxrename to web/app/(commonLayout)/__tests__/profile-bootstrap-gate.spec.tsxindex 7656aac6d18..ca33736de85 100644--- a/web/app/(commonLayout)/__tests__/console-bootstrap-gate.spec.tsx+++ b/web/app/(commonLayout)/__tests__/profile-bootstrap-gate.spec.tsx@@ -2,10 +2,9 @@ import type { ReactNode } from 'react'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { act, render, screen, waitFor } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'-import { ConsoleBootstrapGate } from '../console-bootstrap-gate'+import { ProfileBootstrapGate } from '../profile-bootstrap-gate'const profileQueryKey = ['console', 'account', 'profile', 'get']-const systemFeaturesQueryKey = ['console', 'system-features', 'get']type Deferred<T> = {promise: Promise<T>@@ -13,7 +12,7 @@ type Deferred<T> = {reject: (reason?: unknown) => void}-const createDeferred = <T,>(): Deferred<T> => {+function createDeferred<T>(): Deferred<T> {let resolve!: (value: T) => voidlet reject!: (reason?: unknown) => voidconst promise = new Promise<T>((nextResolve, nextReject) => {@@ -26,7 +25,6 @@ const createDeferred = <T,>(): Deferred<T> => {const mocks = vi.hoisted(() => ({profileQuery: undefined as Deferred<{ id: string }> | undefined,- systemFeaturesQuery: undefined as Deferred<{ branding: { enabled: boolean } }> | undefined,}))vi.mock('@/features/account-profile/client', () => ({@@ -36,13 +34,6 @@ vi.mock('@/features/account-profile/client', () => ({}),}))-vi.mock('@/features/system-features/client', () => ({- systemFeaturesQueryOptions: () => ({- queryKey: systemFeaturesQueryKey,- queryFn: () => mocks.systemFeaturesQuery!.promise,- }),-}))-function createQueryClient() {return new QueryClient({defaultOptions: {@@ -54,20 +45,19 @@ function createQueryClient() {function renderGate(children: ReactNode, queryClient = createQueryClient()) {render(<QueryClientProvider client={queryClient}>- <ConsoleBootstrapGate>{children}</ConsoleBootstrapGate>+ <ProfileBootstrapGate>{children}</ProfileBootstrapGate></QueryClientProvider>,)return queryClient}-describe('ConsoleBootstrapGate', () => {+describe('ProfileBootstrapGate', () => {beforeEach(() => {mocks.profileQuery = createDeferred()- mocks.systemFeaturesQuery = createDeferred()})- it('waits for profile and system features before mounting atom consumers', async () => {+ it('waits for the profile before mounting atom consumers', async () => {renderGate(<div>Console shell</div>)expect(screen.queryByText('Console shell')).not.toBeInTheDocument()@@ -75,11 +65,6 @@ describe('ConsoleBootstrapGate', () => {await act(async () => {mocks.profileQuery!.resolve({ id: 'user-1' })})- expect(screen.queryByText('Console shell')).not.toBeInTheDocument()-- await act(async () => {- mocks.systemFeaturesQuery!.resolve({ branding: { enabled: false } })- })expect(await screen.findByText('Console shell')).toBeInTheDocument()})@@ -87,11 +72,6 @@ describe('ConsoleBootstrapGate', () => {it('keeps atom consumers mounted when a cached profile background refetch fails', async () => {const queryClient = createQueryClient()queryClient.setQueryData(profileQueryKey, { id: 'user-1' }, { updatedAt: 1 })- queryClient.setQueryData(- systemFeaturesQueryKey,- { branding: { enabled: false } },- { updatedAt: 1 },- )renderGate(<div>Console shell</div>, queryClient)@@ -102,7 +82,6 @@ describe('ConsoleBootstrapGate', () => {await act(async () => {mocks.profileQuery!.reject(new Error('profile refetch failed'))- mocks.systemFeaturesQuery!.resolve({ branding: { enabled: false } })})await waitFor(() => {diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/__tests__/chart-view.spec.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/__tests__/chart-view.spec.tsxindex 89102a1386a..3b82a635dd3 100644--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/__tests__/chart-view.spec.tsx+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/__tests__/chart-view.spec.tsx@@ -1,5 +1,6 @@+import type { PeriodParams } from '@/app/components/app/overview/app-chart'import { screen } from '@testing-library/react'-import { renderWithAccountProfile as render } from '@/test/console/account-profile'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { AppACLPermission } from '@/utils/permission'import ChartView from '../chart-view'@@ -13,6 +14,7 @@ const testState = vi.hoisted(() => ({currentUserId: 'user-1',workspacePermissionKeys: [] as string[],chartRenderSpy: vi.fn(),+ conversationPeriodSpy: vi.fn(),}))vi.mock('@/context/workspace-state', async () => {@@ -46,8 +48,9 @@ vi.mock('@/app/components/app/overview/app-chart', () => ({testState.chartRenderSpy('avg-user-interactions')return <div>avg user interactions chart</div>},- ConversationsChart: () => {+ ConversationsChart: ({ period }: { period: PeriodParams }) => {testState.chartRenderSpy('conversations')+ testState.conversationPeriodSpy(period)return <div>conversations chart</div>},CostChart: () => {diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/chart-view.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/chart-view.tsxindex e55345a8287..243a2a931ec 100644--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/chart-view.tsx+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/chart-view.tsx@@ -1,6 +1,8 @@'use client'+import type { DeploymentEdition } from '@dify/contracts/api/console/system-features/types.gen'import type { PeriodParams } from '@/app/components/app/overview/app-chart'import type { I18nKeysByPrefix } from '@/types/i18n'+import { useSuspenseQuery } from '@tanstack/react-query'import dayjs from 'dayjs'import quarterOfYear from 'dayjs/plugin/quarterOfYear'import { useAtomValue } from 'jotai'@@ -23,10 +25,10 @@ import {WorkflowMessagesChart,} from '@/app/components/app/overview/app-chart'import { useStore as useAppStore } from '@/app/components/app/store'-import { IS_CLOUD_EDITION } from '@/config'import { userProfileIdAtom } from '@/context/account-state'import { useDocLink } from '@/context/i18n'import { workspacePermissionKeysAtom } from '@/context/permission-state'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { getAppACLCapabilities } from '@/utils/permission'import LongTimeRangePicker from './long-time-range-picker'import TimeRangePicker from './time-range-picker'@@ -51,7 +53,28 @@ type IChartViewProps = {}export default function ChartView({ appId, headerRight }: IChartViewProps) {+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })++ return (+ <ChartViewContent+ appId={appId}+ headerRight={headerRight}+ deploymentEdition={deploymentEdition}+ />+ )+}++function ChartViewContent({+ appId,+ headerRight,+ deploymentEdition,+}: IChartViewProps & { deploymentEdition: DeploymentEdition }) {const { t } = useTranslation()+ const isCloudEdition = deploymentEdition === 'CLOUD'+ const isNonCloudEdition = deploymentEdition === 'COMMUNITY' || deploymentEdition === 'ENTERPRISE'const docLink = useDocLink()const appDetail = useAppStore((state) => state.appDetail)const currentUserId = useAtomValue(userProfileIdAtom)@@ -67,8 +90,8 @@ export default function ChartView({ appId, headerRight }: IChartViewProps) {)const isChatApp = appDetail?.mode !== 'completion' && appDetail?.mode !== 'workflow'const isWorkflow = appDetail?.mode === 'workflow'- const [period, setPeriod] = useState<PeriodParams>(- IS_CLOUD_EDITION+ const [period, setPeriod] = useState<PeriodParams>(() =>+ isCloudEdition? {name: t(($) => $['filter.period.today'], { ns: 'appLog' }),query: {@@ -112,13 +135,14 @@ export default function ChartView({ appId, headerRight }: IChartViewProps) {</div></div><div className="mt-1 flex h-10 items-center justify-between pr-10 pl-6">- {IS_CLOUD_EDITION ? (+ {isCloudEdition && (<TimeRangePickerranges={TIME_PERIOD_MAPPING}onSelect={setPeriod}queryDateFormat={queryDateFormat}/>- ) : (+ )}+ {isNonCloudEdition && (<LongTimeRangePickerperiodMapping={LONG_TIME_PERIOD_MAPPING}onSelect={setPeriod}diff --git a/web/app/(commonLayout)/console-bootstrap-gate.tsx b/web/app/(commonLayout)/console-bootstrap-gate.tsxdeleted file mode 100644index d507eee82d2..00000000000--- a/web/app/(commonLayout)/console-bootstrap-gate.tsx+++ /dev/null@@ -1,14 +0,0 @@-'use client'--import type { ReactNode } from 'react'-import { useSuspenseQueries } from '@tanstack/react-query'-import { userProfileQueryOptions } from '@/features/account-profile/client'-import { systemFeaturesQueryOptions } from '@/features/system-features/client'--export function ConsoleBootstrapGate({ children }: { children: ReactNode }) {- useSuspenseQueries({- queries: [userProfileQueryOptions(), systemFeaturesQueryOptions()],- })-- return children-}diff --git a/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/__tests__/layout-main.spec.tsx b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/__tests__/layout-main.spec.tsxindex f0c494ec286..0c7e4a461e4 100644--- a/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/__tests__/layout-main.spec.tsx+++ b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/__tests__/layout-main.spec.tsx@@ -43,14 +43,6 @@ vi.mock('@/context/permission-state', async () => {workspacePermissionKeys: [],}))})-vi.mock('@/context/system-features-state', async () => {- const { createSystemFeaturesStateModuleMock } = await import('@/test/console/state-fixture')-- return createSystemFeaturesStateModuleMock(() => ({- datasetRbacEnabled: mockIsRbacEnabled,- }))-})-vi.mock('@/context/event-emitter', () => ({useEventEmitterContextContext: () => ({eventEmitter: undefined,diff --git a/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/layout-main.tsx b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/layout-main.tsxindex 86e90b3aa68..bffbf673d54 100644--- a/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/layout-main.tsx+++ b/web/app/(commonLayout)/datasets/(datasetDetailLayout)/[datasetId]/layout-main.tsx@@ -2,6 +2,7 @@import type { FC } from 'react'import type { DataSet } from '@/models/datasets'import { cn } from '@langgenius/dify-ui/cn'+import { useSuspenseQuery } from '@tanstack/react-query'import { useAtomValue } from 'jotai'import * as React from 'react'import { useEffect } from 'react'@@ -13,8 +14,8 @@ import {workspacePermissionKeysAtom,workspacePermissionKeysLoadingAtom,} from '@/context/permission-state'-import { datasetRbacEnabledAtom } from '@/context/system-features-state'import { currentWorkspaceLoadingAtom } from '@/context/workspace-state'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import useDocumentTitle from '@/hooks/use-document-title'import { usePathname, useRouter } from '@/next/navigation'import { useDatasetDetail } from '@/service/knowledge/use-dataset'@@ -60,7 +61,10 @@ const DatasetDetailLayout: FC<IAppDetailLayoutProps> = (props) => {const pathname = usePathname()const isLoadingCurrentWorkspace = useAtomValue(currentWorkspaceLoadingAtom)const isLoadingWorkspacePermissionKeys = useAtomValue(workspacePermissionKeysLoadingAtom)- const isRbacEnabled = useAtomValue(datasetRbacEnabledAtom)+ const { data: isRbacEnabled } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ rbac_enabled }) => rbac_enabled,+ })const currentUserId = useAtomValue(userProfileIdAtom)const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)diff --git a/web/app/(commonLayout)/datasets/new/[knowledgeSpaceId]/layout.tsx b/web/app/(commonLayout)/datasets/new/[knowledgeSpaceId]/layout.tsxindex 2d2499e4783..aefbec8e6ce 100644--- a/web/app/(commonLayout)/datasets/new/[knowledgeSpaceId]/layout.tsx+++ b/web/app/(commonLayout)/datasets/new/[knowledgeSpaceId]/layout.tsx@@ -1,4 +1,3 @@-import { KnowledgeRouteGuard } from '@/features/new-rag/knowledge-route-guard'import { KnowledgeSpaceShell } from '@/features/new-rag/knowledge-space-shell'export default async function Layout({@@ -10,9 +9,5 @@ export default async function Layout({}) {const { knowledgeSpaceId } = await params- return (- <KnowledgeRouteGuard>- <KnowledgeSpaceShell knowledgeSpaceId={knowledgeSpaceId}>{children}</KnowledgeSpaceShell>- </KnowledgeRouteGuard>- )+ return <KnowledgeSpaceShell knowledgeSpaceId={knowledgeSpaceId}>{children}</KnowledgeSpaceShell>}diff --git a/web/app/(commonLayout)/datasets/new/__tests__/layout.spec.tsx b/web/app/(commonLayout)/datasets/new/__tests__/layout.spec.tsxnew file mode 100644index 00000000000..256cd2a1c7b--- /dev/null+++ b/web/app/(commonLayout)/datasets/new/__tests__/layout.spec.tsx@@ -0,0 +1,71 @@+import type { ReactElement, ReactNode } from 'react'+import { render, screen } from '@testing-library/react'++const mocks = vi.hoisted(() => ({+ ensureQueryData: vi.fn(),+ redirect: vi.fn((_href: string) => {+ throw new Error('NEXT_REDIRECT')+ }),+ systemFeaturesQueryOptions: { queryKey: ['console', 'system-features'] },+}))++vi.mock('@/context/query-client-server', () => ({+ getQueryClientServer: () => ({+ ensureQueryData: mocks.ensureQueryData,+ }),+}))++vi.mock('@/service/server', () => ({+ serverConsoleQuery: {+ systemFeatures: {+ get: {+ queryOptions: () => mocks.systemFeaturesQueryOptions,+ },+ },+ },+}))++vi.mock('@/next/navigation', () => ({+ redirect: (href: string) => mocks.redirect(href),+}))++async function renderLayout(children: ReactNode) {+ const { default: Layout } = await import('../layout')+ const element = await Layout({ children })+ render(element as ReactElement)+}++describe('NewKnowledgeLayout', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mocks.ensureQueryData.mockResolvedValue({ knowledge_fs_enabled: true })+ })++ it('renders new knowledge routes when KnowledgeFS is enabled', async () => {+ await renderLayout(<div>New knowledge content</div>)++ expect(mocks.ensureQueryData).toHaveBeenCalledWith(mocks.systemFeaturesQueryOptions)+ expect(screen.getByText('New knowledge content')).toBeInTheDocument()+ expect(mocks.redirect).not.toHaveBeenCalled()+ })++ it('redirects to datasets when KnowledgeFS is disabled', async () => {+ mocks.ensureQueryData.mockResolvedValue({ knowledge_fs_enabled: false })+ const { default: Layout } = await import('../layout')++ await expect(Layout({ children: <div>New knowledge content</div> })).rejects.toThrow(+ 'NEXT_REDIRECT',+ )++ expect(mocks.redirect).toHaveBeenCalledWith('/datasets')+ })++ it('preserves System Features failures', async () => {+ const error = new Error('System Features unavailable')+ mocks.ensureQueryData.mockRejectedValue(error)+ const { default: Layout } = await import('../layout')++ await expect(Layout({ children: <div>New knowledge content</div> })).rejects.toBe(error)+ expect(mocks.redirect).not.toHaveBeenCalled()+ })+})diff --git a/web/app/(commonLayout)/datasets/new/create/page.tsx b/web/app/(commonLayout)/datasets/new/create/page.tsxindex 200effeb522..9daec78165d 100644--- a/web/app/(commonLayout)/datasets/new/create/page.tsx+++ b/web/app/(commonLayout)/datasets/new/create/page.tsx@@ -1,10 +1,5 @@import { CreateKnowledgePage } from '@/features/new-rag/create-knowledge-page'-import { KnowledgeRouteGuard } from '@/features/new-rag/knowledge-route-guard'export default function Page() {- return (- <KnowledgeRouteGuard>- <CreateKnowledgePage />- </KnowledgeRouteGuard>- )+ return <CreateKnowledgePage />}diff --git a/web/app/(commonLayout)/datasets/new/layout.tsx b/web/app/(commonLayout)/datasets/new/layout.tsxnew file mode 100644index 00000000000..9df5dcadd6c--- /dev/null+++ b/web/app/(commonLayout)/datasets/new/layout.tsx@@ -0,0 +1,14 @@+import type { ReactNode } from 'react'+import { getQueryClientServer } from '@/context/query-client-server'+import { redirect } from '@/next/navigation'+import { serverConsoleQuery } from '@/service/server'++export default async function Layout({ children }: { children: ReactNode }) {+ const systemFeatures = await getQueryClientServer().ensureQueryData(+ serverConsoleQuery.systemFeatures.get.queryOptions(),+ )++ if (!systemFeatures.knowledge_fs_enabled) redirect('/datasets')++ return children+}diff --git a/web/app/(commonLayout)/deployments/__tests__/layout.spec.tsx b/web/app/(commonLayout)/deployments/__tests__/layout.spec.tsxindex fbf32ce0f98..d609f167574 100644--- a/web/app/(commonLayout)/deployments/__tests__/layout.spec.tsx+++ b/web/app/(commonLayout)/deployments/__tests__/layout.spec.tsx@@ -15,8 +15,14 @@ vi.mock('@/context/query-client-server', () => ({}),}))-vi.mock('@/features/system-features/server', () => ({- serverSystemFeaturesQueryOptions: () => mocks.systemFeaturesQueryOptions,+vi.mock('@/service/server', () => ({+ serverConsoleQuery: {+ systemFeatures: {+ get: {+ queryOptions: () => mocks.systemFeaturesQueryOptions,+ },+ },+ },}))vi.mock('@/features/deployments/deploy-drawer', () => ({diff --git a/web/app/(commonLayout)/deployments/layout.tsx b/web/app/(commonLayout)/deployments/layout.tsxindex c9b2c5fedf0..e5f8a29756e 100644--- a/web/app/(commonLayout)/deployments/layout.tsx+++ b/web/app/(commonLayout)/deployments/layout.tsx@@ -1,12 +1,12 @@import type { ReactNode } from 'react'import { getQueryClientServer } from '@/context/query-client-server'import { DeployDrawer } from '@/features/deployments/deploy-drawer'-import { serverSystemFeaturesQueryOptions } from '@/features/system-features/server'import { notFound } from '@/next/navigation'+import { serverConsoleQuery } from '@/service/server'export default async function DeploymentsLayout({ children }: { children: ReactNode }) {const systemFeatures = await getQueryClientServer().ensureQueryData(- serverSystemFeaturesQueryOptions(),+ serverConsoleQuery.systemFeatures.get.queryOptions(),)if (!systemFeatures.enable_app_deploy) notFound()diff --git a/web/app/(commonLayout)/error.tsx b/web/app/(commonLayout)/error.tsxindex c396b6968eb..26400fc1fb9 100644--- a/web/app/(commonLayout)/error.tsx+++ b/web/app/(commonLayout)/error.tsx@@ -1,6 +1,7 @@'use client'import { Button } from '@langgenius/dify-ui/button'+import { useQueryErrorResetBoundary } from '@tanstack/react-query'import { useTranslation } from 'react-i18next'import { FullScreenLoading } from '@/app/components/full-screen-loading'import { isLegacyBase401 } from '@/features/account-profile/client'@@ -12,6 +13,7 @@ type Props = Readonly<{export default function CommonLayoutError({ error, unstable_retry }: Props) {const { t } = useTranslation('common')+ const { reset } = useQueryErrorResetBoundary()console.error(error)@@ -26,7 +28,14 @@ export default function CommonLayoutError({ error, unstable_retry }: Props) {<div className="system-sm-regular text-text-tertiary">{t(($) => $['errorBoundary.message'])}</div>- <Button size="small" variant="secondary" onClick={() => unstable_retry()}>+ <Button+ size="small"+ variant="secondary"+ onClick={() => {+ reset()+ unstable_retry()+ }}+ >{t(($) => $['errorBoundary.tryAgain'])}</Button></div>diff --git a/web/app/(commonLayout)/hydration-boundary.tsx b/web/app/(commonLayout)/hydration-boundary.tsxindex dda23f3e43f..6207780f9fb 100644--- a/web/app/(commonLayout)/hydration-boundary.tsx+++ b/web/app/(commonLayout)/hydration-boundary.tsx@@ -1,8 +1,7 @@import type { ReactNode } from 'react'import { dehydrate, HydrationBoundary } from '@tanstack/react-query'-import { getQueryClientServer } from '@/context/query-client-server'+import { makeQueryClient } from '@/context/query-client-server'import { serverUserProfileQueryOptions } from '@/features/account-profile/server'-import { serverSystemFeaturesQueryOptions } from '@/features/system-features/server'import { headers } from '@/next/headers'import { redirect } from '@/next/navigation'import {@@ -56,7 +55,7 @@ const handleProfileError = async (error: unknown) => {}export async function CommonLayoutHydrationBoundary({ children }: { children: ReactNode }) {- const queryClient = getQueryClientServer()+ const queryClient = makeQueryClient()const accountProfileUrl = resolveServerConsoleApiUrl(ACCOUNT_PROFILE_PATH)if (accountProfileUrl) {@@ -65,7 +64,6 @@ export async function CommonLayoutHydrationBoundary({ children }: { children: Reawait Promise.all([queryClient.fetchQuery(serverUserProfileQueryOptions()),- queryClient.prefetchQuery(serverSystemFeaturesQueryOptions()),queryClient.prefetchQuery(serverConsoleQuery.workspaces.current.post.queryOptions({context,diff --git a/web/app/(commonLayout)/profile-bootstrap-gate.tsx b/web/app/(commonLayout)/profile-bootstrap-gate.tsxnew file mode 100644index 00000000000..35471dc635a--- /dev/null+++ b/web/app/(commonLayout)/profile-bootstrap-gate.tsx@@ -0,0 +1,11 @@+'use client'++import type { ReactNode } from 'react'+import { useSuspenseQuery } from '@tanstack/react-query'+import { userProfileQueryOptions } from '@/features/account-profile/client'++export function ProfileBootstrapGate({ children }: { children: ReactNode }) {+ useSuspenseQuery(userProfileQueryOptions())++ return children+}diff --git a/web/app/(commonLayout)/providers.tsx b/web/app/(commonLayout)/providers.tsxindex abd8b5a7d4f..28cd8ab94f5 100644--- a/web/app/(commonLayout)/providers.tsx+++ b/web/app/(commonLayout)/providers.tsx@@ -4,9 +4,9 @@ import { OAuthRegistrationAnalytics } from '@/app/components/oauth-registration-import { EventEmitterContextProvider } from '@/context/event-emitter-provider'import { ModalContextProvider } from '@/context/modal-context-provider'import { ProviderContextProvider } from '@/context/provider-context-provider'-import { ConsoleBootstrapGate } from './console-bootstrap-gate'import { ExternalServiceSync } from './external-service-sync'import { CommonLayoutHydrationBoundary } from './hydration-boundary'+import { ProfileBootstrapGate } from './profile-bootstrap-gate'export async function ConsoleRuntimeProviders({ children }: { children: ReactNode }) {return (@@ -14,10 +14,10 @@ export async function ConsoleRuntimeProviders({ children }: { children: ReactNod<OAuthRegistrationAnalytics /><EducationVerifyActionRecorder /><CommonLayoutHydrationBoundary>- <ConsoleBootstrapGate>+ <ProfileBootstrapGate><ExternalServiceSync />{children}- </ConsoleBootstrapGate>+ </ProfileBootstrapGate></CommonLayoutHydrationBoundary></>)diff --git a/web/app/(shareLayout)/webapp-signin/normalForm.tsx b/web/app/(shareLayout)/webapp-signin/normalForm.tsxindex 7def2fc6823..b1f3b35abe1 100644--- a/web/app/(shareLayout)/webapp-signin/normalForm.tsx+++ b/web/app/(shareLayout)/webapp-signin/normalForm.tsx@@ -6,7 +6,6 @@ import * as React from 'react'import { useCallback, useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'import Loading from '@/app/components/base/loading'-import { IS_CE_EDITION } from '@/config'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { LicenseStatus } from '@/features/system-features/constants'import Link from '@/next/link'@@ -19,6 +18,9 @@ const NormalForm = () => {const [isLoading, setIsLoading] = useState(true)const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())+ const isNonCloudEdition =+ systemFeatures.deployment_edition === 'COMMUNITY' ||+ systemFeatures.deployment_edition === 'ENTERPRISE'const [authType, updateAuthType] = useState<'code' | 'password'>('password')const [showORLine, setShowORLine] = useState(false)const [allMethodsAreDisabled, setAllMethodsAreDisabled] = useState(false)@@ -236,7 +238,7 @@ const NormalForm = () => {{t(($) => $.pp, { ns: 'login' })}</Link></div>- {IS_CE_EDITION && (+ {isNonCloudEdition && (<div className="w-hull mt-2 block system-xs-regular text-text-tertiary">{t(($) => $.goToInit, { ns: 'login' })} diff --git a/web/app/__tests__/error.spec.tsx b/web/app/__tests__/error.spec.tsxnew file mode 100644index 00000000000..02f70aba22a--- /dev/null+++ b/web/app/__tests__/error.spec.tsx@@ -0,0 +1,39 @@+import { QueryErrorResetBoundary } from '@tanstack/react-query'+import { render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { afterEach, describe, expect, it, vi } from 'vitest'+import CommonLayoutError from '@/app/(commonLayout)/error'+import AppError from '@/app/error'++describe('route error recovery', () => {+ afterEach(() => {+ vi.restoreAllMocks()+ })++ it.each([+ {+ name: 'root error',+ renderError: (retry: () => void) => <AppError error={new Error('failed')} reset={retry} />,+ },+ {+ name: 'common layout error',+ renderError: (retry: () => void) => (+ <CommonLayoutError error={new Error('failed')} unstable_retry={retry} />+ ),+ },+ ])('resets failed queries before retrying the $name', async ({ renderError }) => {+ const user = userEvent.setup()+ const retry = vi.fn()+ vi.spyOn(console, 'error').mockImplementation(() => {})++ render(+ <QueryErrorResetBoundary>+ {({ isReset }) => renderError(() => retry(isReset()))}+ </QueryErrorResetBoundary>,+ )++ await user.click(screen.getByRole('button', { name: 'common.errorBoundary.tryAgain' }))++ expect(retry).toHaveBeenCalledWith(true)+ })+})diff --git a/web/app/__tests__/layout.spec.tsx b/web/app/__tests__/layout.spec.tsxnew file mode 100644index 00000000000..bfddd400f02--- /dev/null+++ b/web/app/__tests__/layout.spec.tsx@@ -0,0 +1,71 @@+import { QueryClient } from '@tanstack/react-query'++let queryClient: QueryClient++const mocks = vi.hoisted(() => ({+ getSystemFeatures: vi.fn(),+ requestHeaders: new Headers(),+}))++vi.mock('@/context/query-client-server', () => ({+ getQueryClientServer: () => queryClient,+}))++vi.mock('@/env', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/env')>()++ return {+ ...actual,+ getDatasetMap: () => ({}),+ }+})++vi.mock('@/service/server', () => ({+ serverConsoleQuery: {+ systemFeatures: {+ get: {+ queryOptions: () => ({+ queryKey: ['console', 'system-features'],+ queryFn: mocks.getSystemFeatures,+ retry: false,+ }),+ },+ },+ },+}))++vi.mock('@/i18n-config/server', () => ({+ getLocaleOnServer: async () => 'en-US',+}))++vi.mock('@/next/headers', () => ({+ headers: async () => mocks.requestHeaders,+}))++describe('Root layout System Features bootstrap', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ })++ it('caches the resolved System Features for dehydration', async () => {+ mocks.getSystemFeatures.mockResolvedValue({ deployment_edition: 'CLOUD' })+ const { default: RootLayout } = await import('../layout')++ await expect(RootLayout({ children: <div>App</div> })).resolves.toBeDefined()++ expect(mocks.getSystemFeatures).toHaveBeenCalledTimes(1)+ expect(queryClient.getQueryData(['console', 'system-features'])).toEqual({+ deployment_edition: 'CLOUD',+ })+ })++ it('renders the client recovery path when the server prefetch fails', async () => {+ mocks.getSystemFeatures.mockRejectedValue(new Error('system features unavailable'))+ const { default: RootLayout } = await import('../layout')++ await expect(RootLayout({ children: <div>App</div> })).resolves.toBeDefined()++ expect(queryClient.getQueryData(['console', 'system-features'])).toBeUndefined()+ })+})diff --git a/web/app/account/(commonLayout)/account-page/index.tsx b/web/app/account/(commonLayout)/account-page/index.tsxindex 5415c56e5b7..219bdc47c03 100644--- a/web/app/account/(commonLayout)/account-page/index.tsx+++ b/web/app/account/(commonLayout)/account-page/index.tsx@@ -12,7 +12,7 @@ import AppIcon from '@/app/components/base/app-icon'import Input from '@/app/components/base/input'import PremiumBadge from '@/app/components/base/premium-badge'import Collapse from '@/app/components/header/account-setting/collapse'-import { IS_CE_EDITION, validPassword } from '@/config'+import { validPassword } from '@/config'import { useProviderContext } from '@/context/provider-context'import { userProfileQueryOptions } from '@/features/account-profile/client'import { systemFeaturesQueryOptions } from '@/features/system-features/client'@@ -243,7 +243,7 @@ export default function AccountPage() {wrapperClassName="mt-2"/>)}- {!IS_CE_EDITION && (+ {systemFeatures.deployment_edition === 'CLOUD' && (<ButtonclassName="mt-2 text-components-button-destructive-secondary-text"onClick={() => setShowDeleteAccountModal(true)}diff --git a/web/app/auth/refresh/__tests__/route.spec.ts b/web/app/auth/refresh/__tests__/route.spec.tsindex ce205e7bb0e..c7142936b51 100644--- a/web/app/auth/refresh/__tests__/route.spec.ts+++ b/web/app/auth/refresh/__tests__/route.spec.ts@@ -4,16 +4,12 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'const mocks = vi.hoisted(() => ({basePath: '',- isCloudEdition: false,}))vi.mock('@/config', () => ({API_PREFIX: 'http://localhost:5001/console/api',CSRF_COOKIE_NAME: () => 'csrf_token',CSRF_HEADER_NAME: 'X-CSRF-Token',- get IS_CLOUD_EDITION() {- return mocks.isCloudEdition- },}))vi.mock('server-only', () => ({}))@@ -52,7 +48,6 @@ describe('auth refresh route', () => {vi.resetModules()vi.unstubAllGlobals()mocks.basePath = ''- mocks.isCloudEdition = false})it('should refresh cookies and redirect back to the requested path', async () => {@@ -244,8 +239,7 @@ describe('auth refresh route', () => {expect(response.headers.get('location')).toBe('/signin?redirect_url=%2F')})- it('should keep a Cloud staging fallback on the current deployment after refresh', async () => {- mocks.isCloudEdition = true+ it('should keep a staging fallback on the current deployment after refresh', async () => {vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(null, { status: 200 })))const { GET } = await import('../route')@@ -260,8 +254,7 @@ describe('auth refresh route', () => {expect(response.headers.get('location')).toBe('/')})- it('should carry the current Cloud deployment fallback through signin when refresh fails', async () => {- mocks.isCloudEdition = true+ it('should carry the current deployment fallback through signin when refresh fails', async () => {vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(null, { status: 401 })))const { GET } = await import('../route')@@ -277,7 +270,6 @@ describe('auth refresh route', () => {})it('should use the current deployment home when a trusted target loops back to auth refresh', async () => {- mocks.isCloudEdition = truevi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(null, { status: 200 })))const { GET } = await import('../route')diff --git a/web/app/components/__tests__/external-attribution-recorder.spec.tsx b/web/app/components/__tests__/external-attribution-recorder.spec.tsxindex 2b4cb3ad6c6..b035f70d91e 100644--- a/web/app/components/__tests__/external-attribution-recorder.spec.tsx+++ b/web/app/components/__tests__/external-attribution-recorder.spec.tsx@@ -6,17 +6,10 @@ import { setAnalyticsConsent } from '@/app/components/base/analytics-consent/conimport { useSearchParams } from '@/next/navigation'import ExternalAttributionRecorder from '../external-attribution-recorder'-const mockConfig = vi.hoisted(() => ({ IS_CLOUD_EDITION: true }))const { mockRememberCreateAppExternalAttribution } = vi.hoisted(() => ({mockRememberCreateAppExternalAttribution: vi.fn(),}))-vi.mock('@/config', () => ({- get IS_CLOUD_EDITION() {- return mockConfig.IS_CLOUD_EDITION- },-}))-vi.mock('@/next/navigation', () => ({useSearchParams: vi.fn(),}))@@ -43,7 +36,6 @@ describe('ExternalAttributionRecorder', () => {beforeEach(() => {vi.clearAllMocks()Cookies.remove('utm_info')- mockConfig.IS_CLOUD_EDITION = truesetAnalyticsConsent('granted')setSearchParams()})@@ -150,14 +142,4 @@ describe('ExternalAttributionRecorder', () => {})expect(mockRememberCreateAppExternalAttribution).toHaveBeenCalledTimes(1)})-- it('is a no-op outside the cloud edition', () => {- mockConfig.IS_CLOUD_EDITION = false- setSearchParams('utm_source=dify_blog&slug=get-started-with-dify')-- render(<ExternalAttributionRecorder />)-- expect(getUtmInfoCookie()).toBeNull()- expect(mockRememberCreateAppExternalAttribution).not.toHaveBeenCalled()- })})diff --git a/web/app/components/app/app-access-control/__tests__/index.spec.tsx b/web/app/components/app/app-access-control/__tests__/index.spec.tsxindex e83d8730fd2..30bb3d2e75a 100644--- a/web/app/components/app/app-access-control/__tests__/index.spec.tsx+++ b/web/app/components/app/app-access-control/__tests__/index.spec.tsx@@ -35,7 +35,15 @@ vi.mock('@/service/access-control', () => ({vi.mock('@/service/client', () => ({consoleQuery: {- systemFeatures: { get: { queryKey: () => ['system-features'] } },+ systemFeatures: {+ get: {+ queryKey: () => ['system-features'],+ queryOptions: (options: Record<string, unknown> = {}) => ({+ queryKey: ['system-features'],+ ...options,+ }),+ },+ },enterprise: {webAppAuth: {updateWebAppWhitelistSubjects: {diff --git a/web/app/components/app/app-publisher/__tests__/sections.spec.tsx b/web/app/components/app/app-publisher/__tests__/sections.spec.tsxindex d14cb9fa8b2..2c66a5c9cd9 100644--- a/web/app/components/app/app-publisher/__tests__/sections.spec.tsx+++ b/web/app/components/app/app-publisher/__tests__/sections.spec.tsx@@ -1,7 +1,8 @@/* oxlint-disable typescript/no-explicit-any */import type { ReactNode } from 'react'-import { fireEvent, render, screen } from '@testing-library/react'+import { fireEvent, screen } from '@testing-library/react'import { AccessMode } from '@/models/access-control'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { AppModeEnum } from '@/types/app'import {AccessModeDisplay,diff --git a/web/app/components/app/configuration/config-var/__tests__/index.spec.tsx b/web/app/components/app/configuration/config-var/__tests__/index.spec.tsxindex 140792112b5..2eeeabcdae2 100644--- a/web/app/components/app/configuration/config-var/__tests__/index.spec.tsx+++ b/web/app/components/app/configuration/config-var/__tests__/index.spec.tsx@@ -3,10 +3,11 @@ import type { IConfigVarProps } from '../index'import type { ExternalDataTool } from '@/models/common'import type { PromptVariable } from '@/models/debug'import { toast } from '@langgenius/dify-ui/toast'-import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'+import { act, fireEvent, screen, waitFor, within } from '@testing-library/react'import * as React from 'react'import { vi } from 'vitest'import DebugConfigurationContext from '@/context/debug-configuration'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { AppModeEnum } from '@/types/app'import ConfigVar, { ADD_EXTERNAL_DATA_TOOL } from '../index'diff --git a/web/app/components/app/configuration/config-var/config-modal/__tests__/index.spec.tsx b/web/app/components/app/configuration/config-var/config-modal/__tests__/index.spec.tsxindex dfc652b42a9..0b8f715192f 100644--- a/web/app/components/app/configuration/config-var/config-modal/__tests__/index.spec.tsx+++ b/web/app/components/app/configuration/config-var/config-modal/__tests__/index.spec.tsx@@ -1,10 +1,11 @@import type { InputVar } from '@/app/components/workflow/types'import type { App, AppSSO } from '@/types/app'import { toast } from '@langgenius/dify-ui/toast'-import { fireEvent, render, screen } from '@testing-library/react'+import { fireEvent, screen } from '@testing-library/react'import * as React from 'react'import { useStore } from '@/app/components/app/store'import { InputVarType } from '@/app/components/workflow/types'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { AppModeEnum } from '@/types/app'import ConfigModal from '../index'diff --git a/web/app/components/app/configuration/dataset-config/settings-modal/__tests__/index.spec.tsx b/web/app/components/app/configuration/dataset-config/settings-modal/__tests__/index.spec.tsxindex 8d67aaf85f0..cf29f617e13 100644--- a/web/app/components/app/configuration/dataset-config/settings-modal/__tests__/index.spec.tsx+++ b/web/app/components/app/configuration/dataset-config/settings-modal/__tests__/index.spec.tsx@@ -8,7 +8,6 @@ import { IndexingType } from '@/app/components/datasets/create/step-two'import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'import { systemFeaturesQueryOptions } from '@/features/system-features/client'-import { defaultSystemFeatures } from '@/features/system-features/config'import {ChunkingMode,DatasetPermission,@@ -18,6 +17,7 @@ import {import { updateDatasetSetting } from '@/service/datasets'import { useMembers } from '@/service/use-common'import { renderWithConsoleQuery as render } from '@/test/console/query-data'+import { createSystemFeaturesFixture } from '@/test/console/system-features'import { RETRIEVE_METHOD } from '@/types/app'import { DatasetACLPermission } from '@/utils/permission'import SettingsModal from '../index'@@ -210,7 +210,7 @@ const renderWithProviders = (dataset: DataSet) => {const queryClient = new QueryClient({defaultOptions: { queries: { retry: false } },})- queryClient.setQueryData(systemFeaturesQueryOptions().queryKey, defaultSystemFeatures)+ queryClient.setQueryData(systemFeaturesQueryOptions().queryKey, createSystemFeaturesFixture())return render(<QueryClientProvider client={queryClient}>diff --git a/web/app/components/app/create-app-dialog/app-card/__tests__/index.spec.tsx b/web/app/components/app/create-app-dialog/app-card/__tests__/index.spec.tsxindex 365292547a4..628a10ff3eb 100644--- a/web/app/components/app/create-app-dialog/app-card/__tests__/index.spec.tsx+++ b/web/app/components/app/create-app-dialog/app-card/__tests__/index.spec.tsx@@ -1,22 +1,18 @@+import type { ReactElement } from 'react'import type { App } from '@/models/explore'import type { AppIconType } from '@/types/app'import { screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { trackEvent } from '@/app/components/base/amplitude'import AppListContext from '@/context/app-list-context'-import { renderWithConsoleQuery as render } from '@/test/console/query-data'+import { renderWithConsoleQuery } from '@/test/console/query-data'import { AppModeEnum } from '@/types/app'import AppCard from '../index'vi.mock('@/app/components/base/amplitude', () => ({ trackEvent: vi.fn() }))-const mockConfig = vi.hoisted(() => ({ isCloudEdition: true }))-vi.mock('@/config', async (importOriginal) => ({- ...(await importOriginal<typeof import('@/config')>()),- get IS_CLOUD_EDITION() {- return mockConfig.isCloudEdition- },-}))+const render = (ui: ReactElement) =>+ renderWithConsoleQuery(ui, { systemFeatures: { deployment_edition: 'CLOUD' } })const app: App = {can_trial: true,@@ -47,7 +43,6 @@ const app: App = {describe('AppCard', () => {beforeEach(() => {- mockConfig.isCloudEdition = truevi.clearAllMocks()})diff --git a/web/app/components/app/create-app-dialog/app-card/index.tsx b/web/app/components/app/create-app-dialog/app-card/index.tsxindex dd3fbd25f6e..8c8e24fcb04 100644--- a/web/app/components/app/create-app-dialog/app-card/index.tsx+++ b/web/app/components/app/create-app-dialog/app-card/index.tsx@@ -4,13 +4,14 @@ import { PlusIcon } from '@heroicons/react/20/solid'import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'import { RiInformation2Line } from '@remixicon/react'+import { useSuspenseQuery } from '@tanstack/react-query'import { useCallback } from 'react'import { useTranslation } from 'react-i18next'import { useContextSelector } from 'use-context-selector'import { trackEvent } from '@/app/components/base/amplitude'import AppIcon from '@/app/components/base/app-icon'-import { IS_CLOUD_EDITION } from '@/config'import AppListContext from '@/context/app-list-context'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { AppTypeIcon, AppTypeLabel } from '../../type-selector'type AppCardProps = {@@ -21,8 +22,12 @@ type AppCardProps = {const AppCard = ({ app, canCreate, onCreate }: AppCardProps) => {const { t } = useTranslation()+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })const { app: appBasicInfo } = app- const canViewApp = IS_CLOUD_EDITION+ const canViewApp = deploymentEdition === 'CLOUD'const setShowTryAppPanel = useContextSelector(AppListContext, (ctx) => ctx.setShowTryAppPanel)const handleShowTryAppPanel = useCallback(() => {trackEvent('preview_template', {diff --git a/web/app/components/app/in-site-message/__tests__/notification.spec.tsx b/web/app/components/app/in-site-message/__tests__/notification.spec.tsxindex 0f69679a704..31dcc680c79 100644--- a/web/app/components/app/in-site-message/__tests__/notification.spec.tsx+++ b/web/app/components/app/in-site-message/__tests__/notification.spec.tsx@@ -3,27 +3,26 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { fireEvent, render, screen, waitFor } from '@testing-library/react'import InSiteMessageNotification from '../notification'-const { mockConfig, mockNotification, mockNotificationDismiss } = vi.hoisted(() => ({- mockConfig: {- isCloudEdition: true,+const { mockEdition, mockNotification, mockNotificationDismiss } = vi.hoisted(() => ({+ mockEdition: {+ value: 'CLOUD' as 'COMMUNITY' | 'ENTERPRISE' | 'CLOUD' | null,},mockNotification: vi.fn(),mockNotificationDismiss: vi.fn(),}))-vi.mock(import('@/config'), async (importOriginal) => {- const actual = await importOriginal()-- return {- ...actual,- get IS_CLOUD_EDITION() {- return mockConfig.isCloudEdition- },- }-})-vi.mock('@/service/client', () => ({consoleQuery: {+ systemFeatures: {+ get: {+ queryKey: () => ['console', 'systemFeatures', 'get'],+ queryOptions: (options?: Record<string, unknown>) => ({+ queryKey: ['console', 'systemFeatures', 'get'],+ queryFn: () => new Promise(() => {}),+ ...options,+ }),+ },+ },notification: {get: {queryOptions: (options?: Record<string, unknown>) => ({@@ -56,6 +55,9 @@ const createWrapper = () => {},},})+ queryClient.setQueryData(['console', 'systemFeatures', 'get'], {+ deployment_edition: mockEdition.value,+ })const Wrapper = ({ children }: { children: ReactNode }) => (<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>@@ -67,7 +69,7 @@ const createWrapper = () => {describe('InSiteMessageNotification', () => {beforeEach(() => {vi.clearAllMocks()- mockConfig.isCloudEdition = true+ mockEdition.value = 'CLOUD'vi.stubGlobal('open', vi.fn())})@@ -78,7 +80,7 @@ describe('InSiteMessageNotification', () => {// Validate query gating and empty state rendering.describe('Rendering', () => {it('should render null and skip query when not cloud edition', async () => {- mockConfig.isCloudEdition = false+ mockEdition.value = 'COMMUNITY'const Wrapper = createWrapper()const { container } = render(<InSiteMessageNotification />, { wrapper: Wrapper })diff --git a/web/app/components/app/in-site-message/notification.tsx b/web/app/components/app/in-site-message/notification.tsxindex c39a701c9a7..9b9c5f7dfee 100644--- a/web/app/components/app/in-site-message/notification.tsx+++ b/web/app/components/app/in-site-message/notification.tsx@@ -1,9 +1,9 @@'use client'import type { InSiteMessageActionItem } from './index'-import { useMutation, useQuery } from '@tanstack/react-query'+import { useMutation, useQuery, useSuspenseQuery } from '@tanstack/react-query'import { useTranslation } from 'react-i18next'-import { IS_CLOUD_EDITION } from '@/config'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { consoleQuery } from '@/service/client'import InSiteMessage from './index'@@ -56,20 +56,25 @@ function parseNotificationBody(body: string): NotificationBodyPayload | null {function InSiteMessageNotification() {const { t } = useTranslation()+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })+ const isCloudEdition = deploymentEdition === 'CLOUD'const dismissNotificationMutation = useMutation(consoleQuery.notification.dismiss.post.mutationOptions(),)const { data } = useQuery(consoleQuery.notification.get.queryOptions({- enabled: IS_CLOUD_EDITION,+ enabled: isCloudEdition,}),)const notification = data?.notifications?.[0]const parsedBody = notification ? parseNotificationBody(notification.body) : null- if (!IS_CLOUD_EDITION || !notification || !notification.notification_id) return null+ if (!isCloudEdition || !notification || !notification.notification_id) return nullconst notificationId = notification.notification_idconst fallbackActions: InSiteMessageActionItem[] = [diff --git a/web/app/components/app/log/__tests__/archived-logs-notice.spec.tsx b/web/app/components/app/log/__tests__/archived-logs-notice.spec.tsxindex 1c23d5ab6c0..e255b3b0954 100644--- a/web/app/components/app/log/__tests__/archived-logs-notice.spec.tsx+++ b/web/app/components/app/log/__tests__/archived-logs-notice.spec.tsx@@ -5,17 +5,10 @@ import { Plan } from '@/app/components/billing/type'import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'import { useModalContextSelector } from '@/context/modal-context'import { useProviderContext } from '@/context/provider-context'+import { createConsoleQueryWrapper } from '@/test/console/query-data'import { render } from '@/test/console/render'import { ArchivedLogsNotice } from '../archived-logs-notice'-vi.mock('@/config', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/config')>()- return {- ...actual,- IS_CLOUD_EDITION: true,- }-})-vi.mock('@/context/workspace-state', async () => {const { createWorkspaceStateModuleMock } = await import('@/test/console/state-fixture')@@ -57,6 +50,12 @@ function mockProviderPlan(planType: Plan) {describe('ArchivedLogsNotice', () => {const setShowAccountSettingModal = vi.fn()+ const renderNotice = () => {+ const { wrapper } = createConsoleQueryWrapper({+ systemFeatures: { deployment_edition: 'CLOUD' },+ })+ return render(<ArchivedLogsNotice />, { wrapper })+ }beforeEach(() => {vi.clearAllMocks()@@ -69,7 +68,7 @@ describe('ArchivedLogsNotice', () => {})it('should show notice for paid workspace managers', () => {- render(<ArchivedLogsNotice />)+ renderNotice()expect(screen.getByText('appLog.archives.notice.description')).toBeInTheDocument()fireEvent.click(screen.getByRole('button', { name: 'appLog.archives.notice.action' }))@@ -81,7 +80,7 @@ describe('ArchivedLogsNotice', () => {it('should not show notice for sandbox workspaces', () => {mockProviderPlan(Plan.sandbox)- render(<ArchivedLogsNotice />)+ renderNotice()expect(screen.queryByText('appLog.archives.notice.description')).not.toBeInTheDocument()})diff --git a/web/app/components/app/log/archived-logs-notice.tsx b/web/app/components/app/log/archived-logs-notice.tsxindex f5e75d37a6e..fb372854397 100644--- a/web/app/components/app/log/archived-logs-notice.tsx+++ b/web/app/components/app/log/archived-logs-notice.tsx@@ -1,16 +1,21 @@'use client'+import { useSuspenseQuery } from '@tanstack/react-query'import { useAtomValue } from 'jotai'import { useTranslation } from 'react-i18next'import { Plan } from '@/app/components/billing/type'import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'-import { IS_CLOUD_EDITION } from '@/config'import { useModalContextSelector } from '@/context/modal-context'import { useProviderContext } from '@/context/provider-context'import { isCurrentWorkspaceManagerAtom } from '@/context/workspace-state'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'export function ArchivedLogsNotice() {const { t } = useTranslation()+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })const isCurrentWorkspaceManager = useAtomValue(isCurrentWorkspaceManagerAtom)const { enableBilling, plan } = useProviderContext()const setShowAccountSettingModal = useModalContextSelector(@@ -18,7 +23,7 @@ export function ArchivedLogsNotice() {)if (- !IS_CLOUD_EDITION ||+ deploymentEdition !== 'CLOUD' ||!isCurrentWorkspaceManager ||!enableBilling ||plan.type === Plan.sandboxdiff --git a/web/app/components/app/overview/__tests__/app-card-utils.spec.ts b/web/app/components/app/overview/__tests__/app-card-utils.spec.tsindex 27913f680a2..115a4f971b6 100644--- a/web/app/components/app/overview/__tests__/app-card-utils.spec.ts+++ b/web/app/components/app/overview/__tests__/app-card-utils.spec.ts@@ -313,6 +313,7 @@ describe('app-card-utils', () => {expect(snippet).toContain('name: "Alice"')expect(snippet).toContain('count: "5"')expect(snippet).toContain('background-color: #FF0000')+ expect(snippet).toContain(`baseUrl: 'https://example.com${basePath}'`)})it('should generate an embedded script snippet with empty inputs comment', () => {diff --git a/web/app/components/app/overview/apikey-info-panel/__tests__/cloud.spec.tsx b/web/app/components/app/overview/apikey-info-panel/__tests__/cloud.spec.tsxindex 825b8e883be..81ed2b9f286 100644--- a/web/app/components/app/overview/apikey-info-panel/__tests__/cloud.spec.tsx+++ b/web/app/components/app/overview/apikey-info-panel/__tests__/cloud.spec.tsx@@ -5,10 +5,9 @@ import {interactions,mockUseModalContext,scenarios,+ setDeploymentEdition,} from './test-utils'-vi.mock('@/config', () => ({ IS_CE_EDITION: false }))-afterEach(cleanup)describe('APIKeyInfoPanel - Cloud Edition', () => {@@ -16,6 +15,7 @@ describe('APIKeyInfoPanel - Cloud Edition', () => {beforeEach(() => {clearAllMocks()+ setDeploymentEdition('CLOUD')mockUseModalContext.mockReturnValue({...defaultModalContext,setShowAccountSettingModal,diff --git a/web/app/components/app/overview/apikey-info-panel/__tests__/index.spec.tsx b/web/app/components/app/overview/apikey-info-panel/__tests__/index.spec.tsxindex d942cdad66c..3ae1a19f0ab 100644--- a/web/app/components/app/overview/apikey-info-panel/__tests__/index.spec.tsx+++ b/web/app/components/app/overview/apikey-info-panel/__tests__/index.spec.tsx@@ -5,11 +5,10 @@ import {interactions,mockUseModalContext,scenarios,+ setDeploymentEdition,textKeys,} from './test-utils'-vi.mock('@/config', () => ({ IS_CE_EDITION: true }))-afterEach(cleanup)describe('APIKeyInfoPanel - Community Edition', () => {@@ -17,6 +16,7 @@ describe('APIKeyInfoPanel - Community Edition', () => {beforeEach(() => {clearAllMocks()+ setDeploymentEdition('COMMUNITY')mockUseModalContext.mockReturnValue({...defaultModalContext,setShowAccountSettingModal,diff --git a/web/app/components/app/overview/apikey-info-panel/__tests__/test-utils.tsx b/web/app/components/app/overview/apikey-info-panel/__tests__/test-utils.tsxindex 71728e989d7..2864d2fc0fb 100644--- a/web/app/components/app/overview/apikey-info-panel/__tests__/test-utils.tsx+++ b/web/app/components/app/overview/apikey-info-panel/__tests__/test-utils.tsx@@ -1,7 +1,8 @@+import type { DeploymentEdition } from '@dify/contracts/api/console/system-features/types.gen'import type { RenderOptions } from '@testing-library/react'import type { Mock, MockedFunction } from 'vitest'import type { ModalContextState } from '@/context/modal-context'-import { fireEvent, render, screen } from '@testing-library/react'+import { fireEvent, screen } from '@testing-library/react'import { noop } from 'es-toolkit/function'import { defaultPlan } from '@/app/components/billing/config'import {@@ -9,6 +10,7 @@ import {useModalContextSelector as actualUseModalContextSelector,} from '@/context/modal-context'import { useProviderContext as actualUseProviderContext } from '@/context/provider-context'+import { renderWithConsoleQuery } from '@/test/console/query-data'import APIKeyInfoPanel from '../index'const { mockRouterPush } = vi.hoisted(() => ({@@ -102,6 +104,7 @@ type APIKeyInfoPanelRenderOptions = {} & Omit<RenderOptions, 'wrapper'>const mainButtonName = /appOverview\.apiKeyInfo\.setAPIBtn/+let deploymentEdition: DeploymentEdition = 'COMMUNITY'// Setup function to configure mocksfunction setupMocks(overrides: MockOverrides = {}) {@@ -129,7 +132,10 @@ function renderAPIKeyInfoPanel(options: APIKeyInfoPanelRenderOptions = {}) {setupMocks(mockOverrides)- return render(<APIKeyInfoPanel />, renderOptions)+ return renderWithConsoleQuery(<APIKeyInfoPanel />, {+ ...renderOptions,+ systemFeatures: { deployment_edition: deploymentEdition },+ })}// Helper functions for common test scenarios@@ -200,5 +206,9 @@ export function clearAllMocks() {vi.clearAllMocks()}+export function setDeploymentEdition(value: DeploymentEdition) {+ deploymentEdition = value+}+// Export mock functions for external accessexport { defaultModalContext, mockUseModalContext }diff --git a/web/app/components/app/overview/apikey-info-panel/index.tsx b/web/app/components/app/overview/apikey-info-panel/index.tsxindex f8186e26504..59b5e3a39b8 100644--- a/web/app/components/app/overview/apikey-info-panel/index.tsx+++ b/web/app/components/app/overview/apikey-info-panel/index.tsx@@ -3,17 +3,22 @@ import type { FC } from 'react'import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'import { RiCloseLine } from '@remixicon/react'+import { useSuspenseQuery } from '@tanstack/react-query'import * as React from 'react'import { useState } from 'react'import { useTranslation } from 'react-i18next'import { LinkExternal02 } from '@/app/components/base/icons/src/vender/line/general'import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'import { useIntegrationsSetting } from '@/app/components/header/account-setting/use-integrations-setting'-import { IS_CE_EDITION } from '@/config'import { useProviderContext } from '@/context/provider-context'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'const APIKeyInfoPanel: FC = () => {- const isCloud = !IS_CE_EDITION+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })+ const isCloud = deploymentEdition === 'CLOUD'const { isAPIKeySet } = useProviderContext()const openIntegrationsSetting = useIntegrationsSetting()diff --git a/web/app/components/app/overview/app-card-utils.ts b/web/app/components/app/overview/app-card-utils.tsindex fd8603d5bbb..6d08b49da80 100644--- a/web/app/components/app/overview/app-card-utils.ts+++ b/web/app/components/app/overview/app-card-utils.ts@@ -2,7 +2,6 @@ import type { InputVar } from '@/app/components/workflow/types'import type { AppDetailResponse } from '@/models/app'import type { AppSSO } from '@/types/app'import { BlockEnum, InputVarType } from '@/app/components/workflow/types'-import { IS_CE_EDITION } from '@/config'import { AccessMode } from '@/models/access-control'import { AppModeEnum } from '@/types/app'import { basePath } from '@/utils/var'@@ -177,20 +176,16 @@ export const getEmbeddedScriptSnippet = ({primaryColor: stringisTestEnv?: booleaninputValues: Record<string, WorkflowLaunchInputValue>-}) =>- `<script>+}) => {+ return `<script>window.difyChatbotConfig = {token: '${token}'${isTestEnv? `,isDev: true`: ''- }${- IS_CE_EDITION- ? `,- baseUrl: '${url}${basePath}'`- : ''- }${+ },+ baseUrl: '${url}${basePath}'${webAppRoute !== 'chatbot'? `,routeSegment: '${webAppRoute}'`@@ -221,6 +216,7 @@ export const getEmbeddedScriptSnippet = ({height: 40rem !important;}</style>`+}export const getChromePluginContent = (iframeUrl: string) => `ChatBot URL: ${iframeUrl}`diff --git a/web/app/components/apps/__tests__/list.spec.tsx b/web/app/components/apps/__tests__/list.spec.tsxindex c614bff67ee..c55bb20d5a2 100644--- a/web/app/components/apps/__tests__/list.spec.tsx+++ b/web/app/components/apps/__tests__/list.spec.tsx@@ -105,6 +105,10 @@ vi.mock('@/service/client', () => ({systemFeatures: {get: {queryKey: () => ['console', 'systemFeatures', 'get'],+ queryOptions: (options: Record<string, unknown> = {}) => ({+ queryKey: ['console', 'systemFeatures', 'get'],+ ...options,+ }),},},},diff --git a/web/app/components/base/amplitude/__tests__/AmplitudeProvider.spec.tsx b/web/app/components/base/amplitude/__tests__/AmplitudeProvider.spec.tsxindex c546c86d60c..67a2cdaa6db 100644--- a/web/app/components/base/amplitude/__tests__/AmplitudeProvider.spec.tsx+++ b/web/app/components/base/amplitude/__tests__/AmplitudeProvider.spec.tsx@@ -5,7 +5,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'const mockConfig = vi.hoisted(() => ({AMPLITUDE_API_KEY: 'test-api-key',- IS_CLOUD_EDITION: true,}))const mockConsent = vi.hoisted(() => ({value: 'granted' as 'unknown' | 'denied' | 'granted',@@ -17,12 +16,6 @@ vi.mock('@/config', () => ({get AMPLITUDE_API_KEY() {return mockConfig.AMPLITUDE_API_KEY},- get IS_CLOUD_EDITION() {- return mockConfig.IS_CLOUD_EDITION- },- get isAmplitudeEnabled() {- return mockConfig.IS_CLOUD_EDITION && !!mockConfig.AMPLITUDE_API_KEY- },}))vi.mock('@amplitude/analytics-browser', () => ({@@ -44,7 +37,6 @@ describe('AmplitudeProvider', () => {vi.resetModules()vi.clearAllMocks()mockConfig.AMPLITUDE_API_KEY = 'test-api-key'- mockConfig.IS_CLOUD_EDITION = truemockConsent.value = 'granted';({ AmplitudeProvider } = await import('../AmplitudeProvider'))})diff --git a/web/app/components/base/amplitude/__tests__/init.spec.ts b/web/app/components/base/amplitude/__tests__/init.spec.tsindex cea92087653..4912cadb1ad 100644--- a/web/app/components/base/amplitude/__tests__/init.spec.ts+++ b/web/app/components/base/amplitude/__tests__/init.spec.ts@@ -4,7 +4,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'const mockConfig = vi.hoisted(() => ({AMPLITUDE_API_KEY: 'test-api-key',- IS_CLOUD_EDITION: true,}))let ensureAmplitudeInitialized: typeof import('../init').ensureAmplitudeInitialized@@ -13,12 +12,6 @@ vi.mock('@/config', () => ({get AMPLITUDE_API_KEY() {return mockConfig.AMPLITUDE_API_KEY},- get IS_CLOUD_EDITION() {- return mockConfig.IS_CLOUD_EDITION- },- get isAmplitudeEnabled() {- return mockConfig.IS_CLOUD_EDITION && !!mockConfig.AMPLITUDE_API_KEY- },}))vi.mock('@amplitude/analytics-browser', () => ({@@ -36,7 +29,6 @@ describe('amplitude init helper', () => {vi.resetModules()vi.clearAllMocks()mockConfig.AMPLITUDE_API_KEY = 'test-api-key'- mockConfig.IS_CLOUD_EDITION = true;({ ensureAmplitudeInitialized } = await import('../init'))})diff --git a/web/app/components/base/amplitude/__tests__/utils.spec.ts b/web/app/components/base/amplitude/__tests__/utils.spec.tsindex 25fe773eb05..aa030937e2a 100644--- a/web/app/components/base/amplitude/__tests__/utils.spec.ts+++ b/web/app/components/base/amplitude/__tests__/utils.spec.ts@@ -2,7 +2,6 @@ import { flushEvents, resetUser, setUserId, setUserProperties, trackEvent } fromconst mockState = vi.hoisted(() => ({consent: 'granted' as 'unknown' | 'denied' | 'granted',- enabled: true,initialized: true,}))@@ -24,12 +23,6 @@ const MockIdentify = vi.hoisted(},)-vi.mock('@/config', () => ({- get isAmplitudeEnabled() {- return mockState.enabled- },-}))-vi.mock('@/app/components/base/analytics-consent/consent-store', () => ({getAnalyticsConsent: () => mockState.consent,}))@@ -51,12 +44,11 @@ describe('amplitude utils', () => {beforeEach(() => {vi.clearAllMocks()mockState.consent = 'granted'- mockState.enabled = truemockState.initialized = true})describe('trackEvent', () => {- it('should call amplitude.track and return its result when amplitude is enabled', () => {+ it('should call amplitude.track and return its result when the consented SDK is initialized', () => {const trackResult = { promise: Promise.resolve({}) }mockTrack.mockReturnValue(trackResult)@@ -67,8 +59,8 @@ describe('amplitude utils', () => {expect(result).toBe(trackResult)})- it('should not call amplitude.track when amplitude is disabled', () => {- mockState.enabled = false+ it('should not call amplitude.track before the SDK initializes', () => {+ mockState.initialized = falsetrackEvent('dataset_created', { source: 'wizard' })@@ -93,7 +85,7 @@ describe('amplitude utils', () => {})describe('flushEvents', () => {- it('should call amplitude.flush and return its result when amplitude is enabled', () => {+ it('should call amplitude.flush and return its result when the consented SDK is initialized', () => {const flushResult = { promise: Promise.resolve() }mockFlush.mockReturnValue(flushResult)@@ -103,8 +95,8 @@ describe('amplitude utils', () => {expect(result).toBe(flushResult)})- it('should not call amplitude.flush when amplitude is disabled', () => {- mockState.enabled = false+ it('should not call amplitude.flush before the SDK initializes', () => {+ mockState.initialized = falseflushEvents()@@ -121,15 +113,15 @@ describe('amplitude utils', () => {})describe('setUserId', () => {- it('should call amplitude.setUserId when amplitude is enabled', () => {+ it('should call amplitude.setUserId when the consented SDK is initialized', () => {setUserId('user-123')expect(mockSetUserId).toHaveBeenCalledTimes(1)expect(mockSetUserId).toHaveBeenCalledWith('user-123')})- it('should not call amplitude.setUserId when amplitude is disabled', () => {- mockState.enabled = false+ it('should not call amplitude.setUserId before the SDK initializes', () => {+ mockState.initialized = falsesetUserId('user-123')@@ -146,7 +138,7 @@ describe('amplitude utils', () => {})describe('setUserProperties', () => {- it('should build identify event and call amplitude.identify when amplitude is enabled', () => {+ it('should build an identify event when the consented SDK is initialized', () => {const properties = {role: 'owner',seats: 3,@@ -165,8 +157,8 @@ describe('amplitude utils', () => {])})- it('should not call amplitude.identify when amplitude is disabled', () => {- mockState.enabled = false+ it('should not call amplitude.identify before the SDK initializes', () => {+ mockState.initialized = falsesetUserProperties({ role: 'owner' })@@ -183,14 +175,14 @@ describe('amplitude utils', () => {})describe('resetUser', () => {- it('should call amplitude.reset when amplitude is enabled', () => {+ it('should call amplitude.reset when the consented SDK is initialized', () => {resetUser()expect(mockReset).toHaveBeenCalledTimes(1)})- it('should not call amplitude.reset when amplitude is disabled', () => {- mockState.enabled = false+ it('should not call amplitude.reset before the SDK initializes', () => {+ mockState.initialized = falseresetUser()diff --git a/web/app/components/base/amplitude/init.ts b/web/app/components/base/amplitude/init.tsindex d3b09648a92..351c1b1d039 100644--- a/web/app/components/base/amplitude/init.ts+++ b/web/app/components/base/amplitude/init.ts@@ -1,6 +1,6 @@import * as amplitude from '@amplitude/analytics-browser'import { sessionReplayPlugin } from '@amplitude/plugin-session-replay-browser'-import { AMPLITUDE_API_KEY, isAmplitudeEnabled } from '@/config'+import { AMPLITUDE_API_KEY } from '@/config'export type AmplitudeInitializationOptions = {sessionReplaySampleRate?: number@@ -61,7 +61,7 @@ const createPageNameEnrichmentPlugin = (): amplitude.Types.EnrichmentPlugin => {export const ensureAmplitudeInitialized = ({sessionReplaySampleRate = 0.5,}: AmplitudeInitializationOptions = {}) => {- if (!isAmplitudeEnabled || isAmplitudeInitialized) return+ if (!AMPLITUDE_API_KEY || isAmplitudeInitialized) returnisAmplitudeInitialized = true@@ -90,6 +90,6 @@ export const ensureAmplitudeInitialized = ({}export const setAmplitudeOptOut = (optOut: boolean) => {- if (!isAmplitudeEnabled || !isAmplitudeInitialized) return+ if (!AMPLITUDE_API_KEY || !isAmplitudeInitialized) returnamplitude.setOptOut(optOut)}diff --git a/web/app/components/base/amplitude/utils.ts b/web/app/components/base/amplitude/utils.tsindex d1aa0aef54e..58354463fc1 100644--- a/web/app/components/base/amplitude/utils.ts+++ b/web/app/components/base/amplitude/utils.ts@@ -1,10 +1,8 @@import * as amplitude from '@amplitude/analytics-browser'import { getAnalyticsConsent } from '@/app/components/base/analytics-consent/consent-store'-import { isAmplitudeEnabled } from '@/config'import { getIsAmplitudeInitialized } from './init'-const canUseAmplitude = () =>- isAmplitudeEnabled && getAnalyticsConsent() === 'granted' && getIsAmplitudeInitialized()+const canUseAmplitude = () => getAnalyticsConsent() === 'granted' && getIsAmplitudeInitialized()/*** Track custom eventdiff --git a/web/app/components/base/analytics-consent/README.md b/web/app/components/base/analytics-consent/README.mdindex 71b799c3c08..9dcb8562fae 100644--- a/web/app/components/base/analytics-consent/README.md+++ b/web/app/components/base/analytics-consent/README.md@@ -6,12 +6,15 @@ Owns CookieYes consent state and the Dify Cloud analytics boundary.- `consent-store`- `cookieyes-consent-bridge`-- `cloud-analytics-boundary`+- `cloud-analytics`- `cloud-analytics-runtime`-- `cloud-analytics-state`- `request-boundary`## External Modules- `app/components/base/amplitude`- `app/components/base/ga`+- `app/components/external-attribution-recorder`+- `config`+- `context/query-client-server`+- `features/system-features`diff --git a/web/app/components/base/analytics-consent/__tests__/cloud-analytics-runtime.spec.tsx b/web/app/components/base/analytics-consent/__tests__/cloud-analytics-runtime.spec.tsxindex 9abb21634a8..81503ff9798 100644--- a/web/app/components/base/analytics-consent/__tests__/cloud-analytics-runtime.spec.tsx+++ b/web/app/components/base/analytics-consent/__tests__/cloud-analytics-runtime.spec.tsx@@ -17,6 +17,10 @@ vi.mock('@/app/components/base/amplitude', () => ({),}))+vi.mock('@/app/components/external-attribution-recorder', () => ({+ default: () => <span data-testid="external-attribution-recorder" />,+}))+describe('CloudAnalyticsRuntime', () => {beforeEach(() => {mockState.pathname = '/signin'@@ -26,6 +30,7 @@ describe('CloudAnalyticsRuntime', () => {const { rerender } = render(<CloudAnalyticsRuntime />)expect(screen.getByTestId('cookieyes-consent-bridge')).toBeInTheDocument()+ expect(screen.getByTestId('external-attribution-recorder')).toBeInTheDocument()expect(screen.getByTestId('amplitude-provider')).toHaveAttribute('data-active', 'true')mockState.pathname = '/integrations'diff --git a/web/app/components/base/analytics-consent/__tests__/cloud-analytics-boundary.spec.tsx b/web/app/components/base/analytics-consent/__tests__/cloud-analytics.spec.tsxsimilarity index 52%rename from web/app/components/base/analytics-consent/__tests__/cloud-analytics-boundary.spec.tsxrename to web/app/components/base/analytics-consent/__tests__/cloud-analytics.spec.tsxindex f6f7444b4fc..ca421514126 100644--- a/web/app/components/base/analytics-consent/__tests__/cloud-analytics-boundary.spec.tsx+++ b/web/app/components/base/analytics-consent/__tests__/cloud-analytics.spec.tsx@@ -1,30 +1,49 @@import type { ReactNode } from 'react'+import { QueryClient } from '@tanstack/react-query'import { render } from '@testing-library/react'+let queryClient: QueryClient+type ConfigState = {cookieYesSiteKey: string- isCloudEdition: booleanisProd: booleanwebPrefix: string | undefined}-const { configState, mockHeadersGet } = vi.hoisted(() => ({- configState: {- cookieYesSiteKey: 'site-key',- isCloudEdition: true,- isProd: true,- webPrefix: 'https://cloud.dify.ai',- } as ConfigState,- mockHeadersGet: vi.fn(),+const { configState, getSystemFeatures, mockHeadersGet, systemFeaturesQueryKey } = vi.hoisted(+ () => ({+ configState: {+ cookieYesSiteKey: 'site-key',+ isProd: true,+ webPrefix: 'https://cloud.dify.ai',+ } as ConfigState,+ getSystemFeatures: vi.fn(),+ mockHeadersGet: vi.fn(),+ systemFeaturesQueryKey: ['console', 'system-features'] as const,+ }),+)++vi.mock('@/context/query-client-server', () => ({+ getQueryClientServer: () => queryClient,+}))++vi.mock('@/service/server', () => ({+ serverConsoleQuery: {+ systemFeatures: {+ get: {+ queryOptions: () => ({+ queryFn: getSystemFeatures,+ queryKey: systemFeaturesQueryKey,+ }),+ },+ },+ },}))vi.mock('@/config', () => ({get COOKIEYES_SITE_KEY() {return configState.cookieYesSiteKey},- get IS_CLOUD_EDITION() {- return configState.isCloudEdition- },get IS_PROD() {return configState.isProd},@@ -57,24 +76,28 @@ vi.mock('@/next/script', () => ({),}))-async function renderBoundary() {- const [{ CloudAnalyticsBoundary }, { getCloudAnalyticsBoundaryState }] = await Promise.all([- import('../cloud-analytics-boundary'),- import('../cloud-analytics-state'),- ])- const state = getCloudAnalyticsBoundaryState({ get: mockHeadersGet })- const view = render(<CloudAnalyticsBoundary {...state} />)- return { ...view, state }+vi.mock('@/next/headers', () => ({+ headers: async () => ({ get: mockHeadersGet }),+}))++vi.mock('../cloud-analytics-runtime', () => ({+ CloudAnalyticsRuntime: () => <span data-testid="cloud-analytics-runtime" />,+}))++async function renderCloudAnalytics() {+ const { CloudAnalytics } = await import('../cloud-analytics')+ return render(await CloudAnalytics())}-describe('CloudAnalyticsBoundary', () => {+describe('CloudAnalytics', () => {beforeEach(() => {vi.clearAllMocks()vi.resetModules()configState.cookieYesSiteKey = 'site-key'- configState.isCloudEdition = trueconfigState.isProd = trueconfigState.webPrefix = 'https://cloud.dify.ai'+ queryClient = new QueryClient()+ queryClient.setQueryData(systemFeaturesQueryKey, { deployment_edition: 'CLOUD' })mockHeadersGet.mockImplementation((name: string) => {const values: Record<string, string> = {host: 'cloud.dify.ai',@@ -85,14 +108,13 @@ describe('CloudAnalyticsBoundary', () => {})})- it('renders a directly detectable CookieYes script in the head sequence', async () => {- const { container, state } = await renderBoundary()+ it('renders analytics scripts before interaction and mounts the runtime', async () => {+ const { container, getByTestId } = await renderCloudAnalytics()const scripts = Array.from(container.querySelectorAll('script'))const scriptIds = scripts.map((script) => script.getAttribute('id') || script.getAttribute('data-id'),)- expect(state.enabled).toBe(true)expect(scriptIds).toEqual(['google-consent-defaults','cookieyes',@@ -112,6 +134,7 @@ describe('CloudAnalyticsBoundary', () => {)expect(cookieYesScript).toHaveAttribute('data-strategy', 'beforeInteractive')expect(cookieYesScript).toHaveAttribute('data-nonce', 'test-nonce')+ expect(getByTestId('cloud-analytics-runtime')).toBeInTheDocument()})it('does not render on a published-app path', async () => {@@ -123,10 +146,10 @@ describe('CloudAnalyticsBoundary', () => {return values[name] ?? null})- const { container, state } = await renderBoundary()+ const { container, queryByTestId } = await renderCloudAnalytics()- expect(state.enabled).toBe(false)expect(container.querySelector('script')).toBeNull()+ expect(queryByTestId('cloud-analytics-runtime')).toBeNull()})it('does not render on a different host', async () => {@@ -138,9 +161,30 @@ describe('CloudAnalyticsBoundary', () => {return values[name] ?? null})- const { container, state } = await renderBoundary()+ const { container, queryByTestId } = await renderCloudAnalytics()++ expect(container.querySelector('script')).toBeNull()+ expect(queryByTestId('cloud-analytics-runtime')).toBeNull()+ })++ it.each(['COMMUNITY', 'ENTERPRISE'] as const)(+ 'disables analytics when deployment edition is %s',+ async (deploymentEdition) => {+ queryClient.setQueryData(systemFeaturesQueryKey, { deployment_edition: deploymentEdition })+ const { container, queryByTestId } = await renderCloudAnalytics()++ expect(container.querySelector('script')).toBeNull()+ expect(queryByTestId('cloud-analytics-runtime')).toBeNull()+ },+ )++ it('does not render when System Features are unavailable', async () => {+ queryClient.removeQueries({ queryKey: systemFeaturesQueryKey })++ const { container, queryByTestId } = await renderCloudAnalytics()- expect(state.enabled).toBe(false)expect(container.querySelector('script')).toBeNull()+ expect(queryByTestId('cloud-analytics-runtime')).toBeNull()+ expect(getSystemFeatures).not.toHaveBeenCalled()})})diff --git a/web/app/components/base/analytics-consent/__tests__/request-boundary.spec.ts b/web/app/components/base/analytics-consent/__tests__/request-boundary.spec.tsindex 4538037ce44..35d3f40a8f2 100644--- a/web/app/components/base/analytics-consent/__tests__/request-boundary.spec.ts+++ b/web/app/components/base/analytics-consent/__tests__/request-boundary.spec.ts@@ -2,12 +2,12 @@ import { isCloudAnalyticsPath, isCloudAnalyticsRequest } from '../request-boundaconst baseRequest = {cookieYesSiteKey: 'site-key',- isCloudEdition: true,+ deploymentEdition: 'CLOUD',isProd: true,pathname: '/signin',requestHost: 'cloud.dify.ai',webPrefix: 'https://cloud.dify.ai',-}+} as constdescribe('cloud analytics request boundary', () => {it('enables first-party Cloud authentication and console routes', () => {@@ -35,7 +35,7 @@ describe('cloud analytics request boundary', () => {it.each([{ cookieYesSiteKey: '', reason: 'missing CookieYes configuration' },- { isCloudEdition: false, reason: 'self-hosted edition' },+ { deploymentEdition: 'COMMUNITY' as const, reason: 'non-Cloud edition' },{ isProd: false, reason: 'non-production environment' },{ requestHost: 'udify.app', reason: 'published app host' },{ requestHost: 'customer.example.com', reason: 'custom host' },diff --git a/web/app/components/base/analytics-consent/cloud-analytics-boundary.tsx b/web/app/components/base/analytics-consent/cloud-analytics-boundary.tsxdeleted file mode 100644index a2e31fb4a38..00000000000--- a/web/app/components/base/analytics-consent/cloud-analytics-boundary.tsx+++ /dev/null@@ -1,27 +0,0 @@-import type { CloudAnalyticsBoundaryState } from './cloud-analytics-state'-import Script from '@/next/script'-import { GoogleAnalyticsTagScripts, GoogleConsentDefaults } from '../ga'--export function CloudAnalyticsBoundary({- cookieYesSiteKey,- enabled,- nonce,-}: CloudAnalyticsBoundaryState) {- if (!enabled) return null-- const cookieYesScriptSrc = `https://cdn-cookieyes.com/client_data/${cookieYesSiteKey}/script.js`-- return (- <>- <GoogleConsentDefaults nonce={nonce} />- <Script- id="cookieyes"- strategy="beforeInteractive"- type="text/javascript"- src={cookieYesScriptSrc}- nonce={nonce}- />- <GoogleAnalyticsTagScripts nonce={nonce} />- </>- )-}diff --git a/web/app/components/base/analytics-consent/cloud-analytics-runtime.tsx b/web/app/components/base/analytics-consent/cloud-analytics-runtime.tsxindex 24fb16fc38e..b4825643d76 100644--- a/web/app/components/base/analytics-consent/cloud-analytics-runtime.tsx+++ b/web/app/components/base/analytics-consent/cloud-analytics-runtime.tsx@@ -1,6 +1,7 @@'use client'import AmplitudeProvider from '@/app/components/base/amplitude'+import ExternalAttributionRecorder from '@/app/components/external-attribution-recorder'import { usePathname } from '@/next/navigation'import { CookieYesConsentBridge } from './cookieyes-consent-bridge'import { isCloudAnalyticsPath } from './request-boundary'@@ -12,6 +13,7 @@ export function CloudAnalyticsRuntime() {<><CookieYesConsentBridge /><AmplitudeProvider active={isCloudAnalyticsPath(pathname)} />+ <ExternalAttributionRecorder /></>)}diff --git a/web/app/components/base/analytics-consent/cloud-analytics-state.ts b/web/app/components/base/analytics-consent/cloud-analytics-state.tsdeleted file mode 100644index 8f3d1420437..00000000000--- a/web/app/components/base/analytics-consent/cloud-analytics-state.ts+++ /dev/null@@ -1,35 +0,0 @@-import { COOKIEYES_SITE_KEY, IS_CLOUD_EDITION, IS_PROD, WEB_PREFIX } from '@/config'-import { isCloudAnalyticsRequest } from './request-boundary'--const CURRENT_PATHNAME_HEADER = 'x-dify-pathname'--type RequestHeaders = {- get: (name: string) => string | null-}--export type CloudAnalyticsBoundaryState = {- cookieYesSiteKey: string- enabled: boolean- nonce?: string-}--export function getCloudAnalyticsBoundaryState(- requestHeaders: RequestHeaders,-): CloudAnalyticsBoundaryState {- const pathname = requestHeaders.get(CURRENT_PATHNAME_HEADER) || '/'- const requestHost = requestHeaders.get('x-forwarded-host') || requestHeaders.get('host')- const enabled = isCloudAnalyticsRequest({- cookieYesSiteKey: COOKIEYES_SITE_KEY,- isCloudEdition: IS_CLOUD_EDITION,- isProd: IS_PROD,- pathname,- requestHost,- webPrefix: WEB_PREFIX,- })-- return {- cookieYesSiteKey: COOKIEYES_SITE_KEY,- enabled,- nonce: requestHeaders.get('x-nonce') ?? undefined,- }-}diff --git a/web/app/components/base/analytics-consent/cloud-analytics.tsx b/web/app/components/base/analytics-consent/cloud-analytics.tsxnew file mode 100644index 00000000000..f6e9f0e26c1--- /dev/null+++ b/web/app/components/base/analytics-consent/cloud-analytics.tsx@@ -0,0 +1,50 @@+import { COOKIEYES_SITE_KEY, IS_PROD, WEB_PREFIX } from '@/config'+import { getQueryClientServer } from '@/context/query-client-server'+import { headers } from '@/next/headers'+import Script from '@/next/script'+import { serverConsoleQuery } from '@/service/server'+import { GoogleAnalyticsTagScripts, GoogleConsentDefaults } from '../ga'+import { CloudAnalyticsRuntime } from './cloud-analytics-runtime'+import { isCloudAnalyticsRequest } from './request-boundary'++const CURRENT_PATHNAME_HEADER = 'x-dify-pathname'++export async function CloudAnalytics() {+ const queryClient = getQueryClientServer()+ const systemFeaturesQuery = serverConsoleQuery.systemFeatures.get.queryOptions()+ const systemFeatures = queryClient.getQueryData(systemFeaturesQuery.queryKey)++ if (!systemFeatures) return null++ const requestHeaders = await headers()+ const pathname = requestHeaders.get(CURRENT_PATHNAME_HEADER) || '/'+ const requestHost = requestHeaders.get('x-forwarded-host') || requestHeaders.get('host')+ const enabled = isCloudAnalyticsRequest({+ cookieYesSiteKey: COOKIEYES_SITE_KEY,+ deploymentEdition: systemFeatures.deployment_edition,+ isProd: IS_PROD,+ pathname,+ requestHost,+ webPrefix: WEB_PREFIX,+ })++ if (!enabled) return null++ const nonce = requestHeaders.get('x-nonce') ?? undefined+ const cookieYesScriptSrc = `https://cdn-cookieyes.com/client_data/${COOKIEYES_SITE_KEY}/script.js`++ return (+ <>+ <GoogleConsentDefaults nonce={nonce} />+ <Script+ id="cookieyes"+ strategy="beforeInteractive"+ type="text/javascript"+ src={cookieYesScriptSrc}+ nonce={nonce}+ />+ <GoogleAnalyticsTagScripts nonce={nonce} />+ <CloudAnalyticsRuntime />+ </>+ )+}diff --git a/web/app/components/base/analytics-consent/request-boundary.ts b/web/app/components/base/analytics-consent/request-boundary.tsindex 34662428bbb..6f6d1e770d0 100644--- a/web/app/components/base/analytics-consent/request-boundary.ts+++ b/web/app/components/base/analytics-consent/request-boundary.ts@@ -1,3 +1,5 @@+import type { DeploymentEdition } from '@dify/contracts/api/console/system-features/types.gen'+const EXCLUDED_ANALYTICS_PATH_SEGMENTS = ['/agent','/chat',@@ -10,7 +12,7 @@ const EXCLUDED_ANALYTICS_PATH_SEGMENTS = [type CloudAnalyticsRequest = {cookieYesSiteKey: string | undefined- isCloudEdition: boolean+ deploymentEdition: DeploymentEditionisProd: booleanpathname: stringrequestHost: string | null@@ -25,13 +27,19 @@ export function isCloudAnalyticsPath(pathname: string) {export function isCloudAnalyticsRequest({cookieYesSiteKey,- isCloudEdition,+ deploymentEdition,isProd,pathname,requestHost,webPrefix,}: CloudAnalyticsRequest) {- if (!isCloudEdition || !isProd || !cookieYesSiteKey?.trim() || !requestHost || !webPrefix)+ if (+ deploymentEdition !== 'CLOUD' ||+ !isProd ||+ !cookieYesSiteKey?.trim() ||+ !requestHost ||+ !webPrefix+ )return falseif (!isCloudAnalyticsPath(pathname)) return falsediff --git a/web/app/components/base/features/new-feature-panel/moderation/__tests__/moderation-setting-modal.spec.tsx b/web/app/components/base/features/new-feature-panel/moderation/__tests__/moderation-setting-modal.spec.tsxindex ea5da9db857..41b27a3af37 100644--- a/web/app/components/base/features/new-feature-panel/moderation/__tests__/moderation-setting-modal.spec.tsx+++ b/web/app/components/base/features/new-feature-panel/moderation/__tests__/moderation-setting-modal.spec.tsx@@ -1,7 +1,8 @@import type { ModerationConfig } from '@/models/debug'-import { act, fireEvent, render, screen } from '@testing-library/react'+import { act, fireEvent, screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import * as i18n from 'react-i18next'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { withSelectorKey } from '@/test/i18n-mock'import ModerationSettingModal from '../moderation-setting-modal'@@ -77,7 +78,7 @@ const defaultData: ModerationConfig = {describe('ModerationSettingModal', () => {const onSave = vi.fn()- const renderModal = async (ui: React.ReactNode) => {+ const renderModal = async (ui: React.ReactElement) => {await act(async () => {render(ui)await Promise.resolve()diff --git a/web/app/components/base/zendesk/__tests__/index.spec.tsx b/web/app/components/base/zendesk/__tests__/index.spec.tsxindex 115ba2d5c4f..ea0cd4abebf 100644--- a/web/app/components/base/zendesk/__tests__/index.spec.tsx+++ b/web/app/components/base/zendesk/__tests__/index.spec.tsx@@ -1,13 +1,18 @@+import type { DeploymentEdition } from '@dify/contracts/api/console/system-features/types.gen'import type { ReactNode } from 'react'+import { QueryClient } from '@tanstack/react-query'import { render, screen } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'import Zendesk from '../index'// Shared state for mocks-let mockIsCeEdition = false+let mockDeploymentEdition: DeploymentEdition = 'CLOUD'let mockZendeskWidgetKey: string | undefined = 'test-key'let mockIsProd = falselet mockNonce: string | null = 'test-nonce'+let queryClient: QueryClient+const systemFeaturesQueryKey = ['console', 'system-features']+const getSystemFeatures = vi.fn()// Mock react's memo to just return the functionvi.mock('react', async (importOriginal) => {@@ -18,11 +23,7 @@ vi.mock('react', async (importOriginal) => {}})-// Mock configvi.mock('@/config', () => ({- get IS_CE_EDITION() {- return mockIsCeEdition- },get ZENDESK_WIDGET_KEY() {return mockZendeskWidgetKey},@@ -31,6 +32,24 @@ vi.mock('@/config', () => ({},}))+vi.mock('@/context/query-client-server', () => ({+ getQueryClientServer: () => queryClient,+}))++vi.mock('@/service/server', () => ({+ serverConsoleQuery: {+ systemFeatures: {+ get: {+ queryOptions: vi.fn(() => ({+ queryKey: systemFeaturesQueryKey,+ queryFn: getSystemFeatures,+ retry: false,+ })),+ },+ },+ },+}))+// Mock next/headersvi.mock('@/next/headers', () => ({headers: vi.fn(() => ({@@ -61,10 +80,14 @@ vi.mock('@/next/script', () => ({describe('Zendesk', () => {beforeEach(() => {vi.clearAllMocks()- mockIsCeEdition = false+ mockDeploymentEdition = 'CLOUD'mockZendeskWidgetKey = 'test-key'mockIsProd = falsemockNonce = 'test-nonce'+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ getSystemFeatures.mockImplementation(async () => ({+ deployment_edition: mockDeploymentEdition,+ }))})// Helper to call the async component@@ -73,15 +96,27 @@ describe('Zendesk', () => {return await Component()}- it('should render nothing when IS_CE_EDITION is true', async () => {- mockIsCeEdition = true+ it.each(['COMMUNITY', 'ENTERPRISE'] as const)(+ 'should render nothing when deployment edition is %s',+ async (deploymentEdition) => {+ mockDeploymentEdition = deploymentEdition+ const result = await renderZendesk()+ expect(result).toBeNull()+ },+ )++ it('should render nothing when ZENDESK_WIDGET_KEY is missing', async () => {+ mockZendeskWidgetKey = undefinedconst result = await renderZendesk()expect(result).toBeNull()+ expect(getSystemFeatures).not.toHaveBeenCalled()})- it('should render nothing when ZENDESK_WIDGET_KEY is missing', async () => {- mockZendeskWidgetKey = undefined+ it('should render nothing when System Features is unavailable', async () => {+ getSystemFeatures.mockRejectedValue(new Error('system features unavailable'))+const result = await renderZendesk()+expect(result).toBeNull()})diff --git a/web/app/components/base/zendesk/__tests__/utils.spec.ts b/web/app/components/base/zendesk/__tests__/utils.spec.tsindex 692b06aed83..ffac513a5de 100644--- a/web/app/components/base/zendesk/__tests__/utils.spec.ts+++ b/web/app/components/base/zendesk/__tests__/utils.spec.ts@@ -1,32 +1,27 @@+import { openZendeskWindow, setZendeskConversationFields } from '../utils'+describe('zendesk/utils', () => {- // Create mock for window.zEconst mockZE = vi.fn()beforeEach(() => {- vi.resetModules()vi.clearAllMocks()- // Set up window.zE mock before each testwindow.zE = mockZE})afterEach(() => {vi.useRealTimers()- // Clean up window.zE after each testwindow.zE = mockZE})describe('setZendeskConversationFields', () => {- it('should call window.zE with correct arguments when not CE edition and zE exists', async () => {- vi.doMock('@/config', () => ({ IS_CE_EDITION: false }))- const { setZendeskConversationFields } = await import('../utils')-+ it('sets conversation fields in Cloud when zE exists', () => {const fields = [{ id: 'field1', value: 'value1' },{ id: 'field2', value: 'value2' },]const callback = vi.fn()- setZendeskConversationFields(fields, callback)+ setZendeskConversationFields(fields, 'CLOUD', callback)expect(window.zE).toHaveBeenCalledWith('messenger:set',@@ -36,24 +31,19 @@ describe('zendesk/utils', () => {)})- it('should not call window.zE when IS_CE_EDITION is true', async () => {- vi.doMock('@/config', () => ({ IS_CE_EDITION: true }))- const { setZendeskConversationFields } = await import('../utils')-- const fields = [{ id: 'field1', value: 'value1' }]-- setZendeskConversationFields(fields)-- expect(window.zE).not.toHaveBeenCalled()- })+ it.each(['COMMUNITY', 'ENTERPRISE'] as const)(+ 'does not set fields when deployment edition is %s',+ (deploymentEdition) => {+ setZendeskConversationFields([{ id: 'field1', value: 'value1' }], deploymentEdition)- it('should work without callback', async () => {- vi.doMock('@/config', () => ({ IS_CE_EDITION: false }))- const { setZendeskConversationFields } = await import('../utils')+ expect(window.zE).not.toHaveBeenCalled()+ },+ )+ it('works without a callback', () => {const fields = [{ id: 'field1', value: 'value1' }]- setZendeskConversationFields(fields)+ setZendeskConversationFields(fields, 'CLOUD')expect(window.zE).toHaveBeenCalledWith('messenger:set',@@ -65,38 +55,32 @@ describe('zendesk/utils', () => {})describe('openZendeskWindow', () => {- it('should show and open messenger when zE exists', async () => {- vi.doMock('@/config', () => ({ IS_CE_EDITION: false }))- const { openZendeskWindow } = await import('../utils')-- openZendeskWindow()+ it('shows and opens the messenger in Cloud when zE exists', () => {+ openZendeskWindow('CLOUD')expect(window.zE).toHaveBeenCalledWith('messenger', 'show')expect(window.zE).toHaveBeenCalledWith('messenger', 'open')})- it('should retry opening until zE is ready', async () => {+ it('retries opening until zE is ready', () => {vi.useFakeTimers()- vi.doMock('@/config', () => ({ IS_CE_EDITION: false }))- const { openZendeskWindow } = await import('../utils')-window.zE = undefined- openZendeskWindow({ interval: 10, retries: 2 })++ openZendeskWindow('CLOUD', { interval: 10, retries: 2 })window.zE = mockZEvi.advanceTimersByTime(10)expect(window.zE).toHaveBeenCalledWith('messenger', 'show')expect(window.zE).toHaveBeenCalledWith('messenger', 'open')- vi.useRealTimers()})- it('should not call window.zE when IS_CE_EDITION is true', async () => {- vi.doMock('@/config', () => ({ IS_CE_EDITION: true }))- const { openZendeskWindow } = await import('../utils')-- openZendeskWindow()+ it.each(['COMMUNITY', 'ENTERPRISE'] as const)(+ 'does not open when deployment edition is %s',+ (deploymentEdition) => {+ openZendeskWindow(deploymentEdition)- expect(window.zE).not.toHaveBeenCalled()- })+ expect(window.zE).not.toHaveBeenCalled()+ },+ )})})diff --git a/web/app/components/base/zendesk/index.tsx b/web/app/components/base/zendesk/index.tsxindex a6a0288d054..0299654eda8 100644--- a/web/app/components/base/zendesk/index.tsx+++ b/web/app/components/base/zendesk/index.tsx@@ -1,10 +1,18 @@import { memo } from 'react'-import { IS_CE_EDITION, IS_PROD, ZENDESK_WIDGET_KEY } from '@/config'+import { IS_PROD, ZENDESK_WIDGET_KEY } from '@/config'+import { getQueryClientServer } from '@/context/query-client-server'import { headers } from '@/next/headers'import Script from '@/next/script'+import { serverConsoleQuery } from '@/service/server'const Zendesk = async () => {- if (IS_CE_EDITION || !ZENDESK_WIDGET_KEY) return null+ if (!ZENDESK_WIDGET_KEY) return null++ const queryClient = getQueryClientServer()+ const systemFeaturesQuery = serverConsoleQuery.systemFeatures.get.queryOptions()+ await queryClient.prefetchQuery(systemFeaturesQuery)+ const systemFeatures = queryClient.getQueryData(systemFeaturesQuery.queryKey)+ if (!systemFeatures || systemFeatures.deployment_edition !== 'CLOUD') return nullconst nonce = IS_PROD ? ((await headers()).get('x-nonce') ?? '') : ''/* v8 ignore next -- `nonce` is always a string (`''` or header value), so nullish fallback is unreachable in runtime. @preserve */diff --git a/web/app/components/base/zendesk/utils.ts b/web/app/components/base/zendesk/utils.tsindex 2f82468f227..d3a6ed74f41 100644--- a/web/app/components/base/zendesk/utils.ts+++ b/web/app/components/base/zendesk/utils.ts@@ -1,4 +1,4 @@-import { IS_CE_EDITION } from '@/config'+import type { DeploymentEdition } from '@dify/contracts/api/console/system-features/types.gen'type ConversationField = {id: string@@ -19,9 +19,10 @@ declare global {export const setZendeskConversationFields = (fields: ConversationField[],+ deploymentEdition: DeploymentEdition,callback?: () => unknown,) => {- if (!IS_CE_EDITION && window.zE)+ if (deploymentEdition === 'CLOUD' && window.zE)window.zE('messenger:set', 'conversationFields', fields, callback)}@@ -30,25 +31,25 @@ type OpenZendeskWindowOptions = {retries?: number}-const openZendeskWindowOnce = () => {- if (IS_CE_EDITION || !window.zE) return false+const openZendeskWindowOnce = (deploymentEdition: DeploymentEdition) => {+ if (deploymentEdition !== 'CLOUD' || !window.zE) return falsewindow.zE('messenger', 'show')window.zE('messenger', 'open')return true}-export const openZendeskWindow = ({- interval = 100,- retries = 20,-}: OpenZendeskWindowOptions = {}) => {- if (IS_CE_EDITION) return+export const openZendeskWindow = (+ deploymentEdition: DeploymentEdition,+ { interval = 100, retries = 20 }: OpenZendeskWindowOptions = {},+) => {+ if (deploymentEdition !== 'CLOUD') return- if (openZendeskWindowOnce()) return+ if (openZendeskWindowOnce(deploymentEdition)) returnlet attempts = 0const timer = window.setInterval(() => {attempts += 1- if (openZendeskWindowOnce() || attempts >= retries) window.clearInterval(timer)+ if (openZendeskWindowOnce(deploymentEdition) || attempts >= retries) window.clearInterval(timer)}, interval)}diff --git a/web/app/components/billing/partner-stack/__tests__/cookie-recorder.spec.tsx b/web/app/components/billing/partner-stack/__tests__/cookie-recorder.spec.tsxnew file mode 100644index 00000000000..0d39887f0f4--- /dev/null+++ b/web/app/components/billing/partner-stack/__tests__/cookie-recorder.spec.tsx@@ -0,0 +1,33 @@+import { waitFor } from '@testing-library/react'+import { renderWithConsoleQuery } from '@/test/console/query-data'+import { PartnerStackCookieRecorder } from '../cookie-recorder'++const mocks = vi.hoisted(() => ({+ saveOrUpdate: vi.fn(),+}))++vi.mock('../use-ps-info', () => ({+ default: () => ({ saveOrUpdate: mocks.saveOrUpdate }),+}))++describe('PartnerStackCookieRecorder', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ it('records PartnerStack cookies in Cloud deployments', async () => {+ renderWithConsoleQuery(<PartnerStackCookieRecorder />, {+ systemFeatures: { deployment_edition: 'CLOUD' },+ })++ await waitFor(() => expect(mocks.saveOrUpdate).toHaveBeenCalledTimes(1))+ })++ it('does not record PartnerStack cookies outside Cloud deployments', () => {+ renderWithConsoleQuery(<PartnerStackCookieRecorder />, {+ systemFeatures: { deployment_edition: 'COMMUNITY' },+ })++ expect(mocks.saveOrUpdate).not.toHaveBeenCalled()+ })+})diff --git a/web/app/components/billing/partner-stack/cookie-recorder.tsx b/web/app/components/billing/partner-stack/cookie-recorder.tsxindex 91097d78b70..06439bd3671 100644--- a/web/app/components/billing/partner-stack/cookie-recorder.tsx+++ b/web/app/components/billing/partner-stack/cookie-recorder.tsx@@ -1,18 +1,27 @@'use client'+import { useSuspenseQuery } from '@tanstack/react-query'import { useEffect } from 'react'-import { IS_CLOUD_EDITION } from '@/config'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import usePSInfo from './use-ps-info'-const PartnerStackCookieRecorder = () => {+export function PartnerStackCookieRecorder() {+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })++ if (deploymentEdition !== 'CLOUD') return null++ return <CookieRecorder />+}++function CookieRecorder() {const { saveOrUpdate } = usePSInfo()useEffect(() => {- if (!IS_CLOUD_EDITION) returnsaveOrUpdate()- }, [])+ }, [saveOrUpdate])return null}--export default PartnerStackCookieRecorderdiff --git a/web/app/components/billing/partner-stack/index.tsx b/web/app/components/billing/partner-stack/index.tsxindex c0155ae2fc5..4db93236acd 100644--- a/web/app/components/billing/partner-stack/index.tsx+++ b/web/app/components/billing/partner-stack/index.tsx@@ -1,19 +1,27 @@'use client'import type { FC } from 'react'+import { useSuspenseQuery } from '@tanstack/react-query'import * as React from 'react'import { useEffect } from 'react'-import { IS_CLOUD_EDITION } from '@/config'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import usePSInfo from './use-ps-info'const PartnerStack: FC = () => {+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })+ const isCloudEdition = deploymentEdition === 'CLOUD'const { saveOrUpdate, bind } = usePSInfo()+ const hasProcessedRef = React.useRef(false)useEffect(() => {- if (!IS_CLOUD_EDITION) return+ if (!isCloudEdition || hasProcessedRef.current) return+ hasProcessedRef.current = true// Save PartnerStack info in cookie first. Because if user hasn't logged in, redirecting to login page would cause lose the partnerStack info in URL.saveOrUpdate()// bind PartnerStack info after user logged inbind()- }, [])+ }, [bind, isCloudEdition, saveOrUpdate])return null}diff --git a/web/app/components/billing/plan/index.tsx b/web/app/components/billing/plan/index.tsxindex 9230105fe2c..d65c8cf1766 100644--- a/web/app/components/billing/plan/index.tsx+++ b/web/app/components/billing/plan/index.tsx@@ -2,6 +2,7 @@import type { FC } from 'react'import { Button } from '@langgenius/dify-ui/button'import { RiBook2Line, RiFileEditLine, RiGroupLine } from '@remixicon/react'+import { useSuspenseQuery } from '@tanstack/react-query'import { useUnmountedRef } from 'ahooks'import { useAtomValue } from 'jotai'import * as React from 'react'@@ -11,11 +12,11 @@ import { ApiAggregate, TriggerAll } from '@/app/components/base/icons/src/venderimport UsageInfo from '@/app/components/billing/usage-info'import { useSetEducationVerifying } from '@/app/education-apply/storage'import VerifyStateModal from '@/app/education-apply/verify-state-modal'-import { IS_CLOUD_EDITION } from '@/config'import { userProfileEmailAtom } from '@/context/account-state'import { useModalContextSelector } from '@/context/modal-context'import { useProviderContext } from '@/context/provider-context'import { isCurrentWorkspaceManagerAtom } from '@/context/workspace-state'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { usePathname, useRouter } from '@/next/navigation'import { useEducationVerify } from '@/service/use-education'import { getDaysUntilEndOfMonth } from '@/utils/time'@@ -34,6 +35,11 @@ type Props = Readonly<{const PlanComp: FC<Props> = ({ loc }) => {const { t } = useTranslation()+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })+ const isCloudEdition = deploymentEdition === 'CLOUD'const router = useRouter()const path = usePathname()const userProfileEmail = useAtomValue(userProfileEmailAtom)@@ -97,16 +103,14 @@ const PlanComp: FC<Props> = ({ loc }) => {</div></div><div className="flex shrink-0 items-center gap-1">- {IS_CLOUD_EDITION &&- enableEducationPlan &&- (!isEducationAccount || isAboutToExpire) && (- <Button variant="ghost" onClick={handleVerify} disabled={isPending}>- <span className="mr-1 i-ri-graduation-cap-line size-4" />- {t(($) => $.toVerified, { ns: 'education' })}- {isPending && <Loading className="ml-1 animate-spin-slow" />}- </Button>- )}- {IS_CLOUD_EDITION &&+ {isCloudEdition && enableEducationPlan && (!isEducationAccount || isAboutToExpire) && (+ <Button variant="ghost" onClick={handleVerify} disabled={isPending}>+ <span className="mr-1 i-ri-graduation-cap-line size-4" />+ {t(($) => $.toVerified, { ns: 'education' })}+ {isPending && <Loading className="ml-1 animate-spin-slow" />}+ </Button>+ )}+ {isCloudEdition &&enableEducationPlan &&isEducationAccount &&type === Plan.sandbox &&@@ -121,7 +125,7 @@ const PlanComp: FC<Props> = ({ loc }) => {{isEducationDiscountLoading && <Loading className="ml-1 animate-spin-slow" />}</Button>)}- {IS_CLOUD_EDITION && !isEnterprisePlan && (+ {isCloudEdition && !isEnterprisePlan && (<UpgradeBtn className="shrink-0" isPlain={type === Plan.team} isShort loc={loc} />)}</div>diff --git a/web/app/components/billing/upgrade-btn/index.tsx b/web/app/components/billing/upgrade-btn/index.tsxindex c84c2daa149..a6c109a3321 100644--- a/web/app/components/billing/upgrade-btn/index.tsx+++ b/web/app/components/billing/upgrade-btn/index.tsx@@ -2,11 +2,12 @@import type { CSSProperties, FC } from 'react'import type { I18nKeysWithPrefix } from '@/types/i18n'import { Button } from '@langgenius/dify-ui/button'+import { useSuspenseQuery } from '@tanstack/react-query'import * as React from 'react'import { useTranslation } from 'react-i18next'import { SparklesSoft } from '@/app/components/base/icons/src/public/common'-import { IS_CLOUD_EDITION } from '@/config'import { useModalContext } from '@/context/modal-context'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { PremiumBadgeButton } from '../../base/premium-badge'type Props = Readonly<{@@ -37,9 +38,13 @@ const UpgradeBtn: FC<Props> = ({labelKey,}) => {const { t } = useTranslation()+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })const { setShowPricingModal } = useModalContext()- if (!IS_CLOUD_EDITION) return null+ if (deploymentEdition !== 'CLOUD') return nullconst handleClick = () => {if (_onClick) _onClick()diff --git a/web/app/components/custom/custom-page/__tests__/index.spec.tsx b/web/app/components/custom/custom-page/__tests__/index.spec.tsxindex 6e375ab2aed..09a88bc054b 100644--- a/web/app/components/custom/custom-page/__tests__/index.spec.tsx+++ b/web/app/components/custom/custom-page/__tests__/index.spec.tsx@@ -14,13 +14,13 @@ vi.mock('@/config', async (importOriginal) => {const actual = await importOriginal<typeof import('@/config')>()return {...actual,- IS_CLOUD_EDITION: true,}})const render = (ui: ReactElement) =>renderWithConsoleQuery(ui, {systemFeatures: {+ deployment_edition: 'CLOUD',branding: {enabled: true,workspace_logo: 'https://example.com/workspace-logo.png',diff --git a/web/app/components/custom/custom-page/index.tsx b/web/app/components/custom/custom-page/index.tsxindex 5e420ec46c0..11edcd923fb 100644--- a/web/app/components/custom/custom-page/index.tsx+++ b/web/app/components/custom/custom-page/index.tsx@@ -1,16 +1,22 @@+import { useSuspenseQuery } from '@tanstack/react-query'import { useTranslation } from 'react-i18next'import { contactSalesUrl } from '@/app/components/billing/config'import { Plan } from '@/app/components/billing/type'-import { IS_CLOUD_EDITION } from '@/config'import { useModalContext } from '@/context/modal-context'import { useProviderContext } from '@/context/provider-context'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import CustomWebAppBrand from '../custom-web-app-brand'const CustomPage = () => {const { t } = useTranslation()+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })const { plan, enableBilling } = useProviderContext()const { setShowPricingModal } = useModalContext()- const showBillingTip = IS_CLOUD_EDITION && enableBilling && plan.type === Plan.sandbox+ const showBillingTip =+ deploymentEdition === 'CLOUD' && enableBilling && plan.type === Plan.sandboxconst showContact = enableBilling && (plan.type === Plan.professional || plan.type === Plan.team)return (diff --git a/web/app/components/datasets/access-config/__tests__/index.spec.tsx b/web/app/components/datasets/access-config/__tests__/index.spec.tsxindex 307059e9bd2..4aa1cf8e6c8 100644--- a/web/app/components/datasets/access-config/__tests__/index.spec.tsx+++ b/web/app/components/datasets/access-config/__tests__/index.spec.tsx@@ -97,17 +97,6 @@ vi.mock('@/context/permission-state', async () => {return createPermissionStateModuleMock(() => mockConsoleState)})-vi.mock('@/context/system-features-state', async () => {- const { createSystemFeaturesStateModuleMock } = await import('@/test/console/state-fixture')-- return createSystemFeaturesStateModuleMock(() => ({- ...(() => mockConsoleState)(),- datasetRbacEnabled: (() => ({- isRbacEnabled: mockIsRbacEnabled,- }))().isRbacEnabled,- }))-})-vi.mock('@/app/components/access-rules-editor', () => ({default: (props: AccessRulesEditorProps) => {mockAccessRulesEditor.props = propsdiff --git a/web/app/components/datasets/access-config/index.tsx b/web/app/components/datasets/access-config/index.tsxindex 03244f2b486..b7830a8737b 100644--- a/web/app/components/datasets/access-config/index.tsx+++ b/web/app/components/datasets/access-config/index.tsx@@ -2,6 +2,7 @@import type { ResourceOpenScope } from '@/models/access-control'import { ScrollArea } from '@langgenius/dify-ui/scroll-area'+import { useSuspenseQuery } from '@tanstack/react-query'import { useAtomValue } from 'jotai'import { useCallback, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'@@ -11,7 +12,7 @@ import { userProfileIdAtom } from '@/context/account-state'import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'import { useLocale } from '@/context/i18n'import { workspacePermissionKeysAtom } from '@/context/permission-state'-import { datasetRbacEnabledAtom } from '@/context/system-features-state'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { getAccessControlTemplateLanguage } from '@/i18n-config/language'import {useDatasetAccessRules,@@ -33,7 +34,10 @@ const DatasetAccessConfigPage = ({ datasetId }: DatasetAccessConfigPageProps) =>const dataset = useDatasetDetailContextWithSelector((state) => state.dataset)const currentUserId = useAtomValue(userProfileIdAtom)const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)- const isRbacEnabled = useAtomValue(datasetRbacEnabledAtom)+ const { data: isRbacEnabled } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ rbac_enabled }) => rbac_enabled,+ })const canAccessConfig = getDatasetACLCapabilities(dataset?.permission_keys, {currentUserId,resourceMaintainer: dataset?.maintainer,diff --git a/web/app/components/datasets/create/file-uploader/__tests__/index.spec.tsx b/web/app/components/datasets/create/file-uploader/__tests__/index.spec.tsxindex 2a7f7ef4d5e..41bed909bcd 100644--- a/web/app/components/datasets/create/file-uploader/__tests__/index.spec.tsx+++ b/web/app/components/datasets/create/file-uploader/__tests__/index.spec.tsx@@ -1,9 +1,13 @@import type { CustomFile as File, FileItem } from '@/models/datasets'-import { fireEvent, render, screen } from '@testing-library/react'+import { fireEvent, screen } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'+import { renderWithConsoleQuery } from '@/test/console/query-data'import { PROGRESS_NOT_STARTED } from '../constants'import FileUploader from '../index'+const render = (ui: React.ReactElement) =>+ renderWithConsoleQuery(ui, { systemFeatures: { deployment_edition: 'CLOUD' } })+const mockNotify = vi.fn()vi.mock('use-context-selector', async () => {const actual =@@ -31,10 +35,6 @@ vi.mock('@/i18n-config/language', () => ({LanguagesSupported: ['en-US', 'zh-Hans'],}))-vi.mock('@/config', () => ({- IS_CE_EDITION: false,-}))-vi.mock('@/app/components/base/file-uploader/utils', () => ({getFileUploadErrorMessage: () => 'Upload error',}))@@ -44,7 +44,8 @@ vi.mock('@/hooks/use-theme', () => ({default: () => ({ theme: 'light' }),}))-vi.mock('@/types/app', () => ({+vi.mock('@/types/app', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/types/app')>()),Theme: { dark: 'dark', light: 'light' },}))diff --git a/web/app/components/datasets/create/file-uploader/hooks/__tests__/use-file-upload.spec.tsx b/web/app/components/datasets/create/file-uploader/hooks/__tests__/use-file-upload.spec.tsxindex 26938422ee2..43f1a984bce 100644--- a/web/app/components/datasets/create/file-uploader/hooks/__tests__/use-file-upload.spec.tsx+++ b/web/app/components/datasets/create/file-uploader/hooks/__tests__/use-file-upload.spec.tsx@@ -1,7 +1,8 @@-import type { ReactNode } from 'react'+import type { ReactElement } from 'react'import type { CustomFile, FileItem } from '@/models/datasets'-import { act, render, renderHook, waitFor } from '@testing-library/react'+import { act, renderHook, waitFor } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'+import { createConsoleQueryWrapper, renderWithConsoleQuery } from '@/test/console/query-data'import { PROGRESS_COMPLETE, PROGRESS_ERROR, PROGRESS_NOT_STARTED } from '../../constants'// Import after mocksimport { useFileUpload } from '../use-file-upload'@@ -40,18 +41,15 @@ vi.mock('@/i18n-config/language', () => ({LanguagesSupported: ['en-US', 'zh-Hans'],}))-vi.mock('@/config', () => ({- IS_CE_EDITION: false,-}))-// Mock file upload error messagevi.mock('@/app/components/base/file-uploader/utils', () => ({getFileUploadErrorMessage: (_e: unknown, defaultMsg: string) => defaultMsg,}))-const createWrapper = () => {- return ({ children }: { children: ReactNode }) => <>{children}</>-}+const createWrapper = () =>+ createConsoleQueryWrapper({ systemFeatures: { deployment_edition: 'CLOUD' } }).wrapper+const render = (ui: ReactElement) =>+ renderWithConsoleQuery(ui, { systemFeatures: { deployment_edition: 'CLOUD' } })describe('useFileUpload', () => {const defaultOptions = {diff --git a/web/app/components/datasets/create/file-uploader/hooks/use-file-upload.ts b/web/app/components/datasets/create/file-uploader/hooks/use-file-upload.tsindex 8e1a4f4f11a..be86ccab1b6 100644--- a/web/app/components/datasets/create/file-uploader/hooks/use-file-upload.ts+++ b/web/app/components/datasets/create/file-uploader/hooks/use-file-upload.ts@@ -2,11 +2,12 @@import type { RefObject } from 'react'import type { CustomFile as File, FileItem } from '@/models/datasets'import { toast } from '@langgenius/dify-ui/toast'+import { useSuspenseQuery } from '@tanstack/react-query'import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import { getFileUploadErrorMessage } from '@/app/components/base/file-uploader/utils'-import { IS_CE_EDITION } from '@/config'import { useLocale } from '@/context/i18n'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { LanguagesSupported } from '@/i18n-config/language'import { upload } from '@/service/base'import { useFileSupportTypes, useFileUploadConfig } from '@/service/use-common'@@ -69,6 +70,11 @@ export const useFileUpload = ({allowedExtensions,}: UseFileUploadOptions): UseFileUploadReturn => {const { t } = useTranslation()+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })+ const isCloudEdition = deploymentEdition === 'CLOUD'const locale = useLocale()const [dragging, setDragging] = useState(false)@@ -219,7 +225,7 @@ export const useFileUpload = ({const filesCountLimit = fileUploadConfig.file_upload_limitif (!files.length) return false- if (files.length + fileList.length > filesCountLimit && !IS_CE_EDITION) {+ if (files.length + fileList.length > filesCountLimit && isCloudEdition) {toast.error(t(($) => $['stepOne.uploader.validation.filesNumber'], {ns: 'datasetCreation',@@ -239,7 +245,7 @@ export const useFileUpload = ({fileListRef.current = newFilesuploadMultipleFiles(preparedFiles)},- [prepareFileList, uploadMultipleFiles, t, fileList, fileUploadConfig],+ [prepareFileList, uploadMultipleFiles, t, fileList, fileUploadConfig, isCloudEdition],)const traverseFileEntry = useCallback(diff --git a/web/app/components/datasets/create/step-one/__tests__/index.spec.tsx b/web/app/components/datasets/create/step-one/__tests__/index.spec.tsxindex 99aa4a875c6..6f37d56ae70 100644--- a/web/app/components/datasets/create/step-one/__tests__/index.spec.tsx+++ b/web/app/components/datasets/create/step-one/__tests__/index.spec.tsx@@ -1,14 +1,18 @@import type { DataSourceAuth } from '@/app/components/header/account-setting/data-source-page-new/types'import type { NotionPage } from '@/models/common'import type { CrawlOptions, CrawlResultItem, DataSet, FileItem } from '@/models/datasets'-import { fireEvent, render, screen } from '@testing-library/react'+import { fireEvent, screen } from '@testing-library/react'import { Plan } from '@/app/components/billing/type'import { DataSourceType } from '@/models/datasets'+import { renderWithConsoleQuery } from '@/test/console/query-data'import StepOne from '../index'+const render = (ui: React.ReactElement) =>+ renderWithConsoleQuery(ui, { systemFeatures: { deployment_edition: 'CLOUD' } })+// Mock config for website crawl features-vi.mock('@/config', () => ({- IS_CLOUD_EDITION: false,+vi.mock('@/config', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/config')>()),ENABLE_WEBSITE_FIRECRAWL: true,ENABLE_WEBSITE_JINAREADER: false,ENABLE_WEBSITE_WATERCRAWL: false,diff --git a/web/app/components/datasets/create/step-one/__tests__/upgrade-card.spec.tsx b/web/app/components/datasets/create/step-one/__tests__/upgrade-card.spec.tsxindex 1bc8c27c9c8..65d97b30c5a 100644--- a/web/app/components/datasets/create/step-one/__tests__/upgrade-card.spec.tsx+++ b/web/app/components/datasets/create/step-one/__tests__/upgrade-card.spec.tsx@@ -1,13 +1,12 @@-import { render, screen } from '@testing-library/react'+import { screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { renderWithConsoleQuery } from '@/test/console/query-data'import UpgradeCard from '../upgrade-card'const mockSetShowPricingModal = vi.fn()-vi.mock('@/config', async (importOriginal) => ({- ...(await importOriginal<typeof import('@/config')>()),- IS_CLOUD_EDITION: true,-}))+const render = (ui: React.ReactElement) =>+ renderWithConsoleQuery(ui, { systemFeatures: { deployment_edition: 'CLOUD' } })vi.mock('@/context/modal-context', () => ({useModalContext: () => ({ setShowPricingModal: mockSetShowPricingModal }),diff --git a/web/app/components/datasets/create/step-one/components/__tests__/preview-panel.spec.tsx b/web/app/components/datasets/create/step-one/components/__tests__/preview-panel.spec.tsxindex f0d229e95fd..bd703d01390 100644--- a/web/app/components/datasets/create/step-one/components/__tests__/preview-panel.spec.tsx+++ b/web/app/components/datasets/create/step-one/components/__tests__/preview-panel.spec.tsx@@ -1,6 +1,7 @@import type { NotionPage } from '@/models/common'-import { render, screen } from '@testing-library/react'+import { screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import PreviewPanel from '../preview-panel'vi.mock('../../../file-preview', () => ({diff --git a/web/app/components/datasets/create/step-one/upgrade-card.tsx b/web/app/components/datasets/create/step-one/upgrade-card.tsxindex 20838d115f1..06c7f1a0b3b 100644--- a/web/app/components/datasets/create/step-one/upgrade-card.tsx+++ b/web/app/components/datasets/create/step-one/upgrade-card.tsx@@ -1,21 +1,26 @@'use client'import type { FC } from 'react'+import { useSuspenseQuery } from '@tanstack/react-query'import * as React from 'react'import { useCallback } from 'react'import { useTranslation } from 'react-i18next'import UpgradeBtn from '@/app/components/billing/upgrade-btn'-import { IS_CLOUD_EDITION } from '@/config'import { useModalContext } from '@/context/modal-context'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'const UpgradeCard: FC = () => {const { t } = useTranslation()+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })const { setShowPricingModal } = useModalContext()const handleUpgrade = useCallback(() => {setShowPricingModal()}, [setShowPricingModal])- if (!IS_CLOUD_EDITION) return null+ if (deploymentEdition !== 'CLOUD') return nullreturn (<div className="flex items-center justify-between rounded-xl border-[0.5px] border-components-panel-border-subtle bg-components-panel-on-panel-item-bg py-3 pr-3.5 pl-4 shadow-xs backdrop-blur-[5px]">diff --git a/web/app/components/datasets/create/step-two/__tests__/index.spec.tsx b/web/app/components/datasets/create/step-two/__tests__/index.spec.tsxindex c1ae19fb4f8..e7ec1c0762a 100644--- a/web/app/components/datasets/create/step-two/__tests__/index.spec.tsx+++ b/web/app/components/datasets/create/step-two/__tests__/index.spec.tsx@@ -10,7 +10,7 @@ import type {Rules,} from '@/models/datasets'import type { RetrievalConfig } from '@/types/app'-import { act, cleanup, fireEvent, render, renderHook, screen } from '@testing-library/react'+import { act, cleanup, fireEvent, renderHook, screen } from '@testing-library/react'import {ConfigurationMethodEnum,ModelStatusEnum,@@ -18,6 +18,7 @@ import {} from '@/app/components/header/account-setting/model-provider-page/declarations'import { ChunkingMode, DataSourceType, ProcessMode } from '@/models/datasets'import { expectLoadingButton } from '@/test/button'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { RETRIEVE_METHOD } from '@/types/app'import { PreviewPanel } from '../components/preview-panel'import { StepTwoFooter } from '../components/step-two-footer'@@ -196,12 +197,6 @@ vi.mock('@/app/components/base/amplitude', () => ({trackEvent: vi.fn(),}))-// Enable IS_CE_EDITION to show QA checkbox in tests-vi.mock('@/config', async () => {- const actual = await vi.importActual('@/config')- return { ...actual, IS_CE_EDITION: true }-})-// Mock PreviewDocumentPicker to allow testing handlePickerChangevi.mock('@/app/components/datasets/common/document-picker/preview-document-picker', () => ({/* oxlint-disable typescript/no-explicit-any */diff --git a/web/app/components/datasets/create/step-two/components/__tests__/general-chunking-options.spec.tsx b/web/app/components/datasets/create/step-two/components/__tests__/general-chunking-options.spec.tsxindex 81e9eabdf1c..916c848d7d8 100644--- a/web/app/components/datasets/create/step-two/components/__tests__/general-chunking-options.spec.tsx+++ b/web/app/components/datasets/create/step-two/components/__tests__/general-chunking-options.spec.tsx@@ -1,7 +1,8 @@import type { PreProcessingRule } from '@/models/datasets'-import { fireEvent, render, screen } from '@testing-library/react'+import { fireEvent, screen } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'import { ChunkingMode } from '@/models/datasets'+import { renderWithConsoleQuery } from '@/test/console/query-data'import { GeneralChunkingOptions } from '../general-chunking-options'vi.mock('@/app/components/datasets/settings/summary-index-setting', () => ({@@ -21,11 +22,9 @@ vi.mock('@/app/components/datasets/settings/summary-index-setting', () => ({),}))-vi.mock('@/config', () => ({- IS_CE_EDITION: true,-}))-const ns = 'datasetCreation'+const render = (ui: React.ReactElement) =>+ renderWithConsoleQuery(ui, { systemFeatures: { deployment_edition: 'COMMUNITY' } })const createRules = (): PreProcessingRule[] => [{ id: 'remove_extra_spaces', enabled: true },diff --git a/web/app/components/datasets/create/step-two/components/__tests__/indexing-mode-section.spec.tsx b/web/app/components/datasets/create/step-two/components/__tests__/indexing-mode-section.spec.tsxindex 785710f78d2..a43a6ec2232 100644--- a/web/app/components/datasets/create/step-two/components/__tests__/indexing-mode-section.spec.tsx+++ b/web/app/components/datasets/create/step-two/components/__tests__/indexing-mode-section.spec.tsx@@ -1,8 +1,9 @@import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations'import type { RetrievalConfig } from '@/types/app'-import { fireEvent, render, screen } from '@testing-library/react'+import { fireEvent, screen } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'import { ChunkingMode } from '@/models/datasets'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { IndexingType } from '../../hooks'import { IndexingModeSection } from '../indexing-mode-section'diff --git a/web/app/components/datasets/create/step-two/components/__tests__/parent-child-options.spec.tsx b/web/app/components/datasets/create/step-two/components/__tests__/parent-child-options.spec.tsxindex b4de17a4cfc..92d4dd5a1ff 100644--- a/web/app/components/datasets/create/step-two/components/__tests__/parent-child-options.spec.tsx+++ b/web/app/components/datasets/create/step-two/components/__tests__/parent-child-options.spec.tsx@@ -1,8 +1,9 @@import type { ParentChildConfig } from '../../hooks'import type { PreProcessingRule } from '@/models/datasets'-import { fireEvent, render, screen } from '@testing-library/react'+import { fireEvent, screen } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'import { ChunkingMode } from '@/models/datasets'+import { renderWithConsoleQuery } from '@/test/console/query-data'import { ParentChildOptions } from '../parent-child-options'vi.mock('@/app/components/datasets/settings/summary-index-setting', () => ({@@ -22,11 +23,9 @@ vi.mock('@/app/components/datasets/settings/summary-index-setting', () => ({),}))-vi.mock('@/config', () => ({- IS_CE_EDITION: true,-}))-const ns = 'datasetCreation'+const render = (ui: React.ReactElement) =>+ renderWithConsoleQuery(ui, { systemFeatures: { deployment_edition: 'COMMUNITY' } })const createRules = (): PreProcessingRule[] => [{ id: 'remove_extra_spaces', enabled: true },diff --git a/web/app/components/datasets/create/step-two/components/general-chunking-options.tsx b/web/app/components/datasets/create/step-two/components/general-chunking-options.tsxindex 16649ea04a4..564a7df3cfe 100644--- a/web/app/components/datasets/create/step-two/components/general-chunking-options.tsx+++ b/web/app/components/datasets/create/step-two/components/general-chunking-options.tsx@@ -8,11 +8,12 @@ import type {import { Button } from '@langgenius/dify-ui/button'import { Checkbox } from '@langgenius/dify-ui/checkbox'import { RiAlertFill, RiSearchEyeLine } from '@remixicon/react'+import { useSuspenseQuery } from '@tanstack/react-query'import { useTranslation } from 'react-i18next'import Divider from '@/app/components/base/divider'import { Infotip } from '@/app/components/base/infotip'import SummaryIndexSetting from '@/app/components/datasets/settings/summary-index-setting'-import { IS_CE_EDITION } from '@/config'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { ChunkingMode } from '@/models/datasets'import SettingCog from '../../assets/setting-gear-mod.svg'import s from '../index.module.css'@@ -82,6 +83,11 @@ export const GeneralChunkingOptions: FC<GeneralChunkingOptionsProps> = ({onSummaryIndexSettingChange,}) => {const { t } = useTranslation()+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })+ const isNonCloudEdition = deploymentEdition === 'COMMUNITY' || deploymentEdition === 'ENTERPRISE'const getRuleName = (key: string): string => {const ruleNameMap: Record<string, string> = {@@ -150,7 +156,7 @@ export const GeneralChunkingOptions: FC<GeneralChunkingOptionsProps> = ({</span></label>))}- {showSummaryIndexSetting && IS_CE_EDITION && (+ {showSummaryIndexSetting && isNonCloudEdition && (<div className="mt-3"><SummaryIndexSettingentry="create-document"@@ -159,7 +165,7 @@ export const GeneralChunkingOptions: FC<GeneralChunkingOptionsProps> = ({/></div>)}- {IS_CE_EDITION && (+ {isNonCloudEdition && (<><Divider type="horizontal" className="my-4 bg-divider-subtle" /><div className="flex items-center py-0.5">diff --git a/web/app/components/datasets/create/step-two/components/parent-child-options.tsx b/web/app/components/datasets/create/step-two/components/parent-child-options.tsxindex c5fe1374680..224d9bcf7a3 100644--- a/web/app/components/datasets/create/step-two/components/parent-child-options.tsx+++ b/web/app/components/datasets/create/step-two/components/parent-child-options.tsx@@ -11,12 +11,13 @@ import { Button } from '@langgenius/dify-ui/button'import { Checkbox } from '@langgenius/dify-ui/checkbox'import { RadioGroup } from '@langgenius/dify-ui/radio'import { RiSearchEyeLine } from '@remixicon/react'+import { useSuspenseQuery } from '@tanstack/react-query'import { useTranslation } from 'react-i18next'import Divider from '@/app/components/base/divider'import { ParentChildChunk } from '@/app/components/base/icons/src/vender/knowledge'import RadioCard from '@/app/components/base/radio-card'import SummaryIndexSetting from '@/app/components/datasets/settings/summary-index-setting'-import { IS_CE_EDITION } from '@/config'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { ChunkingMode } from '@/models/datasets'import FileList from '../../assets/file-list-3-fill.svg'import Note from '../../assets/note-mod.svg'@@ -78,6 +79,11 @@ export const ParentChildOptions: FC<ParentChildOptionsProps> = ({showSummaryIndexSetting,}) => {const { t } = useTranslation()+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })+ const isNonCloudEdition = deploymentEdition === 'COMMUNITY' || deploymentEdition === 'ENTERPRISE'const getRuleName = (key: string): string => {const ruleNameMap: Record<string, string> = {@@ -202,7 +208,7 @@ export const ParentChildOptions: FC<ParentChildOptionsProps> = ({</span></label>))}- {showSummaryIndexSetting && IS_CE_EDITION && (+ {showSummaryIndexSetting && isNonCloudEdition && (<div className="mt-3"><SummaryIndexSettingentry="create-document"diff --git a/web/app/components/datasets/documents/components/__tests__/documents-header.spec.tsx b/web/app/components/datasets/documents/components/__tests__/documents-header.spec.tsxindex 95efcf8eca1..0165dbcd937 100644--- a/web/app/components/datasets/documents/components/__tests__/documents-header.spec.tsx+++ b/web/app/components/datasets/documents/components/__tests__/documents-header.spec.tsx@@ -1,7 +1,8 @@import type { SortType } from '@/service/datasets'-import { fireEvent, render, screen } from '@testing-library/react'+import { fireEvent, screen } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'import { DataSourceType } from '@/models/datasets'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import DocumentsHeader from '../documents-header'// Mock the context hooksdiff --git a/web/app/components/datasets/documents/components/__tests__/operations.spec.tsx b/web/app/components/datasets/documents/components/__tests__/operations.spec.tsxindex 30538d0f4a5..7ca82af06ba 100644--- a/web/app/components/datasets/documents/components/__tests__/operations.spec.tsx+++ b/web/app/components/datasets/documents/components/__tests__/operations.spec.tsx@@ -1,6 +1,7 @@-import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { act, cleanup, fireEvent, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import Operations from '../operations'const mockPush = vi.fn()diff --git a/web/app/components/datasets/documents/components/document-list/__tests__/index.spec.tsx b/web/app/components/datasets/documents/components/document-list/__tests__/index.spec.tsxindex 9b55bb8099f..b07c2636406 100644--- a/web/app/components/datasets/documents/components/document-list/__tests__/index.spec.tsx+++ b/web/app/components/datasets/documents/components/document-list/__tests__/index.spec.tsx@@ -1,10 +1,8 @@-import type { ReactNode } from 'react'import type { SimpleDocumentDetail } from '@/models/datasets'-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { act, fireEvent, screen } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'import { ChunkingMode, DataSourceType } from '@/models/datasets'-import { seedAccountProfileQuery } from '@/test/console/account-profile'+import { createConsoleQueryWrapper } from '@/test/console/query-data'import { render } from '@/test/console/render'import DocumentList from '../../list'@@ -83,25 +81,7 @@ vi.mock('@/app/components/datasets/metadata/hooks/use-batch-edit-document-metada}),}))-const createConsoleQueryClient = () =>- new QueryClient({- defaultOptions: {- queries: {- retry: false,- gcTime: Number.POSITIVE_INFINITY,- staleTime: Number.POSITIVE_INFINITY,- },- mutations: { retry: false },- },- })--const createWrapper = () => {- const queryClient = createConsoleQueryClient()- seedAccountProfileQuery(queryClient)- return ({ children }: { children: ReactNode }) => (- <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>- )-}+const createWrapper = () => createConsoleQueryWrapper().wrapperconst createMockDoc = (overrides: Partial<SimpleDocumentDetail> = {}): SimpleDocumentDetail =>({diff --git a/web/app/components/datasets/documents/components/document-list/components/__tests__/document-table-row.spec.tsx b/web/app/components/datasets/documents/components/document-list/components/__tests__/document-table-row.spec.tsxindex 25fb82479db..b7a15f210c7 100644--- a/web/app/components/datasets/documents/components/document-list/components/__tests__/document-table-row.spec.tsx+++ b/web/app/components/datasets/documents/components/document-list/components/__tests__/document-table-row.spec.tsx@@ -4,8 +4,7 @@ import { CheckboxGroup } from '@langgenius/dify-ui/checkbox-group'import { fireEvent, screen } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'import { DataSourceType } from '@/models/datasets'-import { createAccountProfileQueryClient } from '@/test/console/account-profile'-import { createQueryClientWrapper } from '@/test/console/query-client'+import { createConsoleQueryWrapper } from '@/test/console/query-data'import { render } from '@/test/console/render'import DocumentTableRow from '../document-table-row'@@ -27,7 +26,7 @@ vi.mock('@/next/navigation', () => ({}))const createWrapper = (value: string[] = [], onValueChange = vi.fn()) => {- const QueryClientWrapper = createQueryClientWrapper(createAccountProfileQueryClient())+ const { wrapper: QueryClientWrapper } = createConsoleQueryWrapper()return ({ children }: { children: ReactNode }) => (<QueryClientWrapper><CheckboxGroupdiff --git a/web/app/components/datasets/documents/components/operations.tsx b/web/app/components/datasets/documents/components/operations.tsxindex 14dc1bf502e..ac843da0d0e 100644--- a/web/app/components/datasets/documents/components/operations.tsx+++ b/web/app/components/datasets/documents/components/operations.tsx@@ -19,13 +19,14 @@ import {import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'import { Switch } from '@langgenius/dify-ui/switch'import { toast } from '@langgenius/dify-ui/toast'+import { useSuspenseQuery } from '@tanstack/react-query'import { useBoolean, useDebounceFn } from 'ahooks'import { noop } from 'es-toolkit/function'import * as React from 'react'import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'import Divider from '@/app/components/base/divider'-import { IS_CE_EDITION } from '@/config'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { DataSourceType, DocumentActionType } from '@/models/datasets'import { useRouter } from '@/next/navigation'import {@@ -82,6 +83,11 @@ const Operations = ({canDelete,canViewSettings,}: OperationsProps) => {+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })+ const isNonCloudEdition = deploymentEdition === 'COMMUNITY' || deploymentEdition === 'ENTERPRISE'const {id,name,@@ -108,7 +114,7 @@ const Operations = ({const { mutateAsync: resumeDocument } = useDocumentResume()const isListScene = scene === 'list'const canShowRenameAction = canEdit && !archived- const canShowSummaryAction = canEdit && !archived && IS_CE_EDITION+ const canShowSummaryAction = canEdit && !archived && isNonCloudEditionconst canShowSettingsAction = canViewSettingsconst canShowDownloadAction = canDownload && data_source_type === DataSourceType.FILEconst canShowSyncAction =diff --git a/web/app/components/datasets/documents/create-from-pipeline/data-source/local-file/hooks/__tests__/use-local-file-upload.spec.tsx b/web/app/components/datasets/documents/create-from-pipeline/data-source/local-file/hooks/__tests__/use-local-file-upload.spec.tsxindex da2411a885d..485b4cf0fa3 100644--- a/web/app/components/datasets/documents/create-from-pipeline/data-source/local-file/hooks/__tests__/use-local-file-upload.spec.tsx+++ b/web/app/components/datasets/documents/create-from-pipeline/data-source/local-file/hooks/__tests__/use-local-file-upload.spec.tsx@@ -1,7 +1,8 @@-import type { ReactNode } from 'react'+import type { ReactElement } from 'react'import type { CustomFile, FileItem } from '@/models/datasets'-import { act, render, renderHook, waitFor } from '@testing-library/react'+import { act, renderHook, waitFor } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'+import { createConsoleQueryWrapper, renderWithConsoleQuery } from '@/test/console/query-data'import { PROGRESS_ERROR } from '../../constants'const { mockNotify, mockToast } = vi.hoisted(() => {@@ -39,10 +40,6 @@ vi.mock('@/i18n-config/language', () => ({LanguagesSupported: ['en-US', 'zh-Hans'],}))-vi.mock('@/config', () => ({- IS_CE_EDITION: false,-}))-// Mock store functionsconst mockSetLocalFileList = vi.fn()const mockSetCurrentLocalFile = vi.fn()@@ -86,9 +83,10 @@ vi.mock('@/service/base', () => ({// Import after all mocks are set upconst { useLocalFileUpload } = await import('../use-local-file-upload')-const createWrapper = () => {- return ({ children }: { children: ReactNode }) => <>{children}</>-}+const createWrapper = () =>+ createConsoleQueryWrapper({ systemFeatures: { deployment_edition: 'CLOUD' } }).wrapper+const render = (ui: ReactElement) =>+ renderWithConsoleQuery(ui, { systemFeatures: { deployment_edition: 'CLOUD' } })describe('useLocalFileUpload', () => {beforeEach(() => {diff --git a/web/app/components/datasets/documents/create-from-pipeline/processing/embedding-process/__tests__/index.spec.tsx b/web/app/components/datasets/documents/create-from-pipeline/processing/embedding-process/__tests__/index.spec.tsxindex 03d5f39cda0..a7d5da50ae5 100644--- a/web/app/components/datasets/documents/create-from-pipeline/processing/embedding-process/__tests__/index.spec.tsx+++ b/web/app/components/datasets/documents/create-from-pipeline/processing/embedding-process/__tests__/index.spec.tsx@@ -1,11 +1,12 @@import type { Mock } from 'vitest'import type { DocumentIndexingStatus, IndexingStatusResponse } from '@/models/datasets'import type { InitialDocumentDetail } from '@/models/pipeline'-import { fireEvent, render, screen, waitFor } from '@testing-library/react'+import { fireEvent, screen, waitFor } from '@testing-library/react'import * as React from 'react'import { Plan } from '@/app/components/billing/type'import { IndexingType } from '@/app/components/datasets/create/step-two'import { DatasourceType } from '@/models/pipeline'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { RETRIEVE_METHOD } from '@/types/app'import EmbeddingProcess from '../index'diff --git a/web/app/components/datasets/documents/create-from-pipeline/steps/__tests__/step-one-content.spec.tsx b/web/app/components/datasets/documents/create-from-pipeline/steps/__tests__/step-one-content.spec.tsxindex 9d32d8d3a38..d0e12496d7f 100644--- a/web/app/components/datasets/documents/create-from-pipeline/steps/__tests__/step-one-content.spec.tsx+++ b/web/app/components/datasets/documents/create-from-pipeline/steps/__tests__/step-one-content.spec.tsx@@ -1,18 +1,14 @@import type { Datasource } from '@/app/components/rag-pipeline/components/panel/test-run/types'import type { DataSourceNodeType } from '@/app/components/workflow/nodes/data-source/types'import type { Node } from '@/app/components/workflow/types'-import { render, screen } from '@testing-library/react'+import { screen } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'import { DatasourceType } from '@/models/pipeline'+import { renderWithConsoleQuery } from '@/test/console/query-data'import StepOneContent from '../step-one-content'-vi.mock('@/config', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/config')>()- return {- ...actual,- IS_CLOUD_EDITION: true,- }-})+const render = (ui: React.ReactElement) =>+ renderWithConsoleQuery(ui, { systemFeatures: { deployment_edition: 'CLOUD' } })// Mock context providers and hooks (底层依赖)vi.mock('@/context/modal-context', () => ({diff --git a/web/app/components/datasets/documents/detail/completed/common/__tests__/batch-action.spec.tsx b/web/app/components/datasets/documents/detail/completed/common/__tests__/batch-action.spec.tsxindex 8302ec12b93..4ef9d563e0a 100644--- a/web/app/components/datasets/documents/detail/completed/common/__tests__/batch-action.spec.tsx+++ b/web/app/components/datasets/documents/detail/completed/common/__tests__/batch-action.spec.tsx@@ -1,5 +1,6 @@-import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'+import { fireEvent, screen, waitFor, within } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import BatchAction from '../batch-action'describe('BatchAction', () => {diff --git a/web/app/components/datasets/documents/detail/completed/common/batch-action.tsx b/web/app/components/datasets/documents/detail/completed/common/batch-action.tsxindex a5bfe516cc3..924fe84e05c 100644--- a/web/app/components/datasets/documents/detail/completed/common/batch-action.tsx+++ b/web/app/components/datasets/documents/detail/completed/common/batch-action.tsx@@ -19,12 +19,13 @@ import {RiDraftLine,RiRefreshLine,} from '@remixicon/react'+import { useSuspenseQuery } from '@tanstack/react-query'import { useBoolean } from 'ahooks'import * as React from 'react'import { useTranslation } from 'react-i18next'import Divider from '@/app/components/base/divider'import { SearchLinesSparkle } from '@/app/components/base/icons/src/vender/knowledge'-import { IS_CE_EDITION } from '@/config'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'const i18nPrefix = 'batchAction'type IBatchActionProps = {@@ -55,6 +56,11 @@ const BatchAction: FC<IBatchActionProps> = ({onCancel,}) => {const { t } = useTranslation()+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })+ const isNonCloudEdition = deploymentEdition === 'COMMUNITY' || deploymentEdition === 'ENTERPRISE'const [isShowDeleteConfirm, { setTrue: showDeleteConfirm, setFalse: hideDeleteConfirm }] =useBoolean(false)const [isDeleting, { setTrue: setIsDeleting }] = useBoolean(false)@@ -98,7 +104,7 @@ const BatchAction: FC<IBatchActionProps> = ({<span className="px-0.5">{t(($) => $['metadata.metadata'], { ns: 'dataset' })}</span></Button>)}- {onBatchSummary && IS_CE_EDITION && (+ {onBatchSummary && isNonCloudEdition && (<Button variant="ghost" className="gap-x-0.5 px-3" onClick={onBatchSummary}><SearchLinesSparkle className="size-4" /><span className="px-0.5">diff --git a/web/app/components/datasets/documents/detail/segment-add/__tests__/index.spec.tsx b/web/app/components/datasets/documents/detail/segment-add/__tests__/index.spec.tsxindex 4c65bbee67c..246891d84b3 100644--- a/web/app/components/datasets/documents/detail/segment-add/__tests__/index.spec.tsx+++ b/web/app/components/datasets/documents/detail/segment-add/__tests__/index.spec.tsx@@ -1,7 +1,8 @@import type { SegmentImportStatus } from '@/types/dataset'-import { fireEvent, render, screen } from '@testing-library/react'+import { fireEvent, screen } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'import { Plan } from '@/app/components/billing/type'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { segmentImportStatus } from '@/types/dataset'import { SegmentAdd } from '../index'diff --git a/web/app/components/datasets/external-api/external-api-modal/__tests__/index.spec.tsx b/web/app/components/datasets/external-api/external-api-modal/__tests__/index.spec.tsxindex c0721aa794f..f0942a2cbcc 100644--- a/web/app/components/datasets/external-api/external-api-modal/__tests__/index.spec.tsx+++ b/web/app/components/datasets/external-api/external-api-modal/__tests__/index.spec.tsx@@ -1,8 +1,9 @@import type { CreateExternalAPIReq } from '../../declarations'-import { fireEvent, render, screen, waitFor } from '@testing-library/react'+import { fireEvent, screen, waitFor } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'// Import mocked serviceimport { createExternalAPI } from '@/service/datasets'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import AddExternalAPIModal from '../index'// Mock API servicediff --git a/web/app/components/datasets/hit-testing/__tests__/modify-retrieval-modal.spec.tsx b/web/app/components/datasets/hit-testing/__tests__/modify-retrieval-modal.spec.tsxindex 23f7aa03285..59ed9296bf2 100644--- a/web/app/components/datasets/hit-testing/__tests__/modify-retrieval-modal.spec.tsx+++ b/web/app/components/datasets/hit-testing/__tests__/modify-retrieval-modal.spec.tsx@@ -1,6 +1,7 @@import type { RetrievalConfig } from '@/types/app'-import { fireEvent, render, screen } from '@testing-library/react'+import { fireEvent, screen } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { RETRIEVE_METHOD } from '@/types/app'import ModifyRetrievalModal from '../modify-retrieval-modal'diff --git a/web/app/components/datasets/list/__tests__/index.spec.tsx b/web/app/components/datasets/list/__tests__/index.spec.tsxindex 80a1ce5c359..b787406e41a 100644--- a/web/app/components/datasets/list/__tests__/index.spec.tsx+++ b/web/app/components/datasets/list/__tests__/index.spec.tsx@@ -1,4 +1,4 @@-import type { ReactNode } from 'react'+import type { ReactElement, ReactNode } from 'react'import { act, fireEvent, screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { createStore, Provider } from 'jotai'@@ -6,12 +6,14 @@ import { hydrateRoot } from 'react-dom/client'import { renderToString } from 'react-dom/server'import { beforeEach, describe, expect, it, vi } from 'vitest'import { useNewKnowledgeGuideDismissedValue } from '@/features/new-rag/storage'-import { render } from '@/test/console/render'+import { createConsoleQueryWrapper } from '@/test/console/query-data'+import { render as renderWithConsoleState } from '@/test/console/render'import { seedRegisteredConsoleStateFixture } from '@/test/console/state-fixture'-import { createNuqsTestWrapper, renderWithNuqs } from '@/test/nuqs-testing'+import { createNuqsTestWrapper } from '@/test/nuqs-testing'import List from '../index'const knowledgeFsInfiniteOptionsMock = vi.hoisted(() => vi.fn(() => ({})))+const systemFeaturesQueryKey = ['console', 'systemFeatures', 'get'] as constconst useInfiniteQueryMock = vi.hoisted(() =>vi.fn(() => ({data: { pageParams: [null], pages: [{ items: [] }] },@@ -33,15 +35,31 @@ vi.mock('@tanstack/react-query', async (importOriginal) => {}})-vi.mock('@/service/client', () => ({- consoleQuery: {- knowledgeFs: {- listKnowledgeSpaces: {- infiniteOptions: knowledgeFsInfiniteOptionsMock,+vi.mock('@/service/client', async (importOriginal) => {+ const original = await importOriginal<typeof import('@/service/client')>()+ return {+ ...original,+ consoleQuery: {+ ...original.consoleQuery,+ systemFeatures: {+ get: {+ queryKey: () => systemFeaturesQueryKey,+ queryOptions: (options: Record<string, unknown> = {}) => ({+ queryKey: systemFeaturesQueryKey,+ queryFn: () => new Promise(() => {}),+ ...options,+ }),+ },+ },+ knowledgeFs: {+ ...original.consoleQuery.knowledgeFs,+ listKnowledgeSpaces: {+ infiniteOptions: knowledgeFsInfiniteOptionsMock,+ },},},- },-}))+ }+})function NewKnowledgeGuideDismissedProbe() {const dismissed = useNewKnowledgeGuideDismissedValue()@@ -82,11 +100,31 @@ vi.mock('@/context/permission-state', async () => {return createPermissionStateModuleMock(() => mockConsoleState)})-vi.mock('@/context/system-features-state', async () => {- const { createSystemFeaturesStateModuleMock } = await import('@/test/console/state-fixture')- return createSystemFeaturesStateModuleMock(() => mockConsoleState)-})+const renderList = (+ ui: ReactElement,+ options: Parameters<typeof createNuqsTestWrapper>[0] = {},+) => {+ const { wrapper: QueryWrapper } = createConsoleQueryWrapper({+ systemFeatures: {+ knowledge_fs_enabled: mockConsoleState.knowledgeFsEnabled,+ },+ })+ const { wrapper: NuqsWrapper, onUrlUpdate } = createNuqsTestWrapper(options)+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryWrapper>+ <NuqsWrapper>{children}</NuqsWrapper>+ </QueryWrapper>+ )++ return {+ ...renderWithConsoleState(ui, { wrapper }),+ onUrlUpdate,+ }+}++const render = (ui: ReactElement) => renderList(ui)+const renderWithNuqs = renderList// Mock external api panel contextconst mockSetShowExternalApiPanel = vi.fn()@@ -346,15 +384,22 @@ describe('List', () => {const store = createStore()seedRegisteredConsoleStateFixture(store)const { wrapper: NuqsWrapper } = createNuqsTestWrapper()+ const { wrapper: QueryWrapper } = createConsoleQueryWrapper({+ systemFeatures: {+ knowledge_fs_enabled: mockConsoleState.knowledgeFsEnabled,+ },+ })const app = (- <Provider store={store}>- <NuqsWrapper>- <>- <List />- <NewKnowledgeGuideDismissedProbe />- </>- </NuqsWrapper>- </Provider>+ <QueryWrapper>+ <Provider store={store}>+ <NuqsWrapper>+ <>+ <List />+ <NewKnowledgeGuideDismissedProbe />+ </>+ </NuqsWrapper>+ </Provider>+ </QueryWrapper>)const container = document.createElement('div')document.body.append(container)diff --git a/web/app/components/datasets/list/dataset-card/components/__tests__/operations-dropdown.spec.tsx b/web/app/components/datasets/list/dataset-card/components/__tests__/operations-dropdown.spec.tsxindex bd486ac93fa..9cc3f750a41 100644--- a/web/app/components/datasets/list/dataset-card/components/__tests__/operations-dropdown.spec.tsx+++ b/web/app/components/datasets/list/dataset-card/components/__tests__/operations-dropdown.spec.tsx@@ -37,17 +37,6 @@ vi.mock('@/context/permission-state', async () => {return createPermissionStateModuleMock(() => mockConsoleState)})-vi.mock('@/context/system-features-state', async () => {- const { createSystemFeaturesStateModuleMock } = await import('@/test/console/state-fixture')-- return createSystemFeaturesStateModuleMock(() => ({- ...(() => mockConsoleState)(),- datasetRbacEnabled: (() => ({- isRbacEnabled: mockIsRbacEnabled,- }))().isRbacEnabled,- }))-})-describe('OperationsDropdown', () => {const createMockDataset = (overrides: Partial<DataSet> = {}): DataSet =>({diff --git a/web/app/components/datasets/list/dataset-card/components/operations-dropdown.tsx b/web/app/components/datasets/list/dataset-card/components/operations-dropdown.tsxindex 84374a1634d..2b7a269cea9 100644--- a/web/app/components/datasets/list/dataset-card/components/operations-dropdown.tsx+++ b/web/app/components/datasets/list/dataset-card/components/operations-dropdown.tsx@@ -5,6 +5,7 @@ import {DropdownMenuContent,DropdownMenuTrigger,} from '@langgenius/dify-ui/dropdown-menu'+import { useSuspenseQuery } from '@tanstack/react-query'import { useAtomValue } from 'jotai'import * as React from 'react'import {@@ -13,7 +14,7 @@ import {} from '@/app/components/step-by-step-tour/dropdown-menu'import { userProfileIdAtom } from '@/context/account-state'import { workspacePermissionKeysAtom } from '@/context/permission-state'-import { datasetRbacEnabledAtom } from '@/context/system-features-state'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { getDatasetACLCapabilities } from '@/utils/permission'import Operations from '../operations'@@ -44,7 +45,10 @@ const OperationsDropdown = ({const setOpen = operationsMenu.onOpenChangeconst currentUserId = useAtomValue(userProfileIdAtom)const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)- const isRbacEnabled = useAtomValue(datasetRbacEnabledAtom)+ const { data: isRbacEnabled } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ rbac_enabled }) => rbac_enabled,+ })const datasetACLCapabilities = React.useMemo(() =>getDatasetACLCapabilities(dataset.permission_keys, {diff --git a/web/app/components/datasets/list/index.tsx b/web/app/components/datasets/list/index.tsxindex f2d3f7af8e5..ed907c3b304 100644--- a/web/app/components/datasets/list/index.tsx+++ b/web/app/components/datasets/list/index.tsx@@ -2,6 +2,7 @@import type { KnowledgeViewSwitcherProps } from '@/features/new-rag/components/knowledge-view-switcher'// Libraries+import { useSuspenseQuery } from '@tanstack/react-query'import { useBoolean, useDebounceFn } from 'ahooks'import { useAtomValue, useSetAtom } from 'jotai'import { parseAsStringLiteral, useQueryState } from 'nuqs'@@ -19,9 +20,9 @@ import {} from '@/app/components/step-by-step-tour/target-registry'import { useExternalApiPanel } from '@/context/external-api-panel-context'import { workspacePermissionKeysAtom } from '@/context/permission-state'-import { systemFeaturesAtom } from '@/context/system-features-state'import { isCurrentWorkspaceOwnerAtom } from '@/context/workspace-state'import { NewKnowledgeList } from '@/features/new-rag/new-knowledge-list'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { TagManagementModal } from '@/features/tag-management/components/tag-management-modal'import useDocumentTitle from '@/hooks/use-document-title'import { useRouter } from '@/next/navigation'@@ -228,7 +229,10 @@ function KnowledgeFsList() {}function List() {- const { knowledge_fs_enabled: knowledgeFsEnabled } = useAtomValue(systemFeaturesAtom)+ const { data: knowledgeFsEnabled } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ knowledge_fs_enabled }) => knowledge_fs_enabled,+ })if (!knowledgeFsEnabled) return <LegacyList />diff --git a/web/app/components/datasets/settings/form/__tests__/index.spec.tsx b/web/app/components/datasets/settings/form/__tests__/index.spec.tsxindex d6ae4d2e487..78c6556f422 100644--- a/web/app/components/datasets/settings/form/__tests__/index.spec.tsx+++ b/web/app/components/datasets/settings/form/__tests__/index.spec.tsx@@ -1,9 +1,11 @@+import type { ReactElement } from 'react'import type { DataSet } from '@/models/datasets'import type { RetrievalConfig } from '@/types/app'import { fireEvent, screen, waitFor } from '@testing-library/react'import { ChunkingMode, DatasetPermission, DataSourceType } from '@/models/datasets'import { expectLoadingButton } from '@/test/button'-import { render } from '@/test/console/render'+import { createConsoleQueryWrapper } from '@/test/console/query-data'+import { render as renderWithConsoleState } from '@/test/console/render'import { RETRIEVE_METHOD } from '@/types/app'import { DatasetACLPermission } from '@/utils/permission'import { IndexingType } from '../../../create/step-two'@@ -26,18 +28,6 @@ const mockUserProfile = {}let mockWorkspacePermissionKeys = ['dataset.create_and_management']-vi.mock('@tanstack/react-query', async (importOriginal) => {- const actual = await importOriginal<typeof import('@tanstack/react-query')>()- return {- ...actual,- useSuspenseQuery: () => ({- data: {- rbac_enabled: false,- },- }),- }-})-vi.mock('@/context/account-state', async () => {const { createAccountStateModuleMock } = await import('@/test/console/state-fixture')@@ -62,19 +52,13 @@ vi.mock('@/context/permission-state', async () => {workspacePermissionKeys: mockWorkspacePermissionKeys,}))})-vi.mock('@/context/system-features-state', async () => {- const { createSystemFeaturesStateModuleMock } = await import('@/test/console/state-fixture')-- return createSystemFeaturesStateModuleMock(() => ({- ...(() => ({- userProfile: mockUserProfile,- workspacePermissionKeys: mockWorkspacePermissionKeys,- }))(),- datasetRbacEnabled: (() => ({- isRbacEnabled: false,- }))().isRbacEnabled,- }))-})++const render = (ui: ReactElement) => {+ const { wrapper } = createConsoleQueryWrapper({+ systemFeatures: { rbac_enabled: false },+ })+ return renderWithConsoleState(ui, { wrapper })+}const createMockDataset = (overrides: Partial<DataSet> = {}): DataSet => ({id: 'dataset-1',diff --git a/web/app/components/datasets/settings/form/components/__tests__/basic-info-section.spec.tsx b/web/app/components/datasets/settings/form/components/__tests__/basic-info-section.spec.tsxindex e654d45fcfd..e7b41259aff 100644--- a/web/app/components/datasets/settings/form/components/__tests__/basic-info-section.spec.tsx+++ b/web/app/components/datasets/settings/form/components/__tests__/basic-info-section.spec.tsx@@ -1,25 +1,15 @@+import type { ReactElement } from 'react'import type { Member } from '@/models/common'import type { DataSet, IconInfo } from '@/models/datasets'import type { RetrievalConfig } from '@/types/app'import { fireEvent, screen, waitFor } from '@testing-library/react'import { ChunkingMode, DatasetPermission, DataSourceType } from '@/models/datasets'-import { render } from '@/test/console/render'+import { createConsoleQueryWrapper } from '@/test/console/query-data'+import { render as renderWithConsoleState } from '@/test/console/render'import { RETRIEVE_METHOD } from '@/types/app'import { IndexingType } from '../../../../create/step-two'import BasicInfoSection from '../basic-info-section'-vi.mock('@tanstack/react-query', async (importOriginal) => {- const actual = await importOriginal<typeof import('@tanstack/react-query')>()- return {- ...actual,- useSuspenseQuery: () => ({- data: {- rbac_enabled: false,- },- }),- }-})-const mockConsoleState = vi.hoisted(() => ({userProfile: {id: 'user-1',@@ -47,16 +37,13 @@ vi.mock('@/context/permission-state', async () => {return createPermissionStateModuleMock(() => mockConsoleState)})-vi.mock('@/context/system-features-state', async () => {- const { createSystemFeaturesStateModuleMock } = await import('@/test/console/state-fixture')-- return createSystemFeaturesStateModuleMock(() => ({- ...(() => mockConsoleState)(),- datasetRbacEnabled: (() => ({- isRbacEnabled: false,- }))().isRbacEnabled,- }))-})++const render = (ui: ReactElement) => {+ const { wrapper } = createConsoleQueryWrapper({+ systemFeatures: { rbac_enabled: false },+ })+ return renderWithConsoleState(ui, { wrapper })+}// Mock image uploader hooks for AppIconPickervi.mock('@/app/components/base/image-uploader/hooks', () => ({diff --git a/web/app/components/datasets/settings/form/components/__tests__/indexing-section.spec.tsx b/web/app/components/datasets/settings/form/components/__tests__/indexing-section.spec.tsxindex e9a370f1b4b..1ad8f493e95 100644--- a/web/app/components/datasets/settings/form/components/__tests__/indexing-section.spec.tsx+++ b/web/app/components/datasets/settings/form/components/__tests__/indexing-section.spec.tsx@@ -4,13 +4,14 @@ import type {} from '@/app/components/header/account-setting/model-provider-page/declarations'import type { DataSet, SummaryIndexSetting } from '@/models/datasets'import type { RetrievalConfig } from '@/types/app'-import { fireEvent, render, screen } from '@testing-library/react'+import { fireEvent, screen } from '@testing-library/react'import {ConfigurationMethodEnum,ModelStatusEnum,ModelTypeEnum,} from '@/app/components/header/account-setting/model-provider-page/declarations'import { ChunkingMode, DatasetPermission, DataSourceType } from '@/models/datasets'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { RETRIEVE_METHOD } from '@/types/app'import { IndexingType } from '../../../../create/step-two'import IndexingSection from '../indexing-section'diff --git a/web/app/components/datasets/settings/form/components/indexing-section.tsx b/web/app/components/datasets/settings/form/components/indexing-section.tsxindex 1a18fa247e4..ddb9f601369 100644--- a/web/app/components/datasets/settings/form/components/indexing-section.tsx+++ b/web/app/components/datasets/settings/form/components/indexing-section.tsx@@ -5,13 +5,14 @@ import type {} from '@/app/components/header/account-setting/model-provider-page/declarations'import type { DataSet, SummaryIndexSetting as SummaryIndexSettingType } from '@/models/datasets'import type { RetrievalConfig } from '@/types/app'+import { useSuspenseQuery } from '@tanstack/react-query'import { useTranslation } from 'react-i18next'import Divider from '@/app/components/base/divider'import EconomicalRetrievalMethodConfig from '@/app/components/datasets/common/economical-retrieval-method-config'import RetrievalMethodConfig from '@/app/components/datasets/common/retrieval-method-config'import ModelSelector from '@/app/components/header/account-setting/model-provider-page/model-selector'-import { IS_CE_EDITION } from '@/config'import { useDocLink } from '@/context/i18n'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { ChunkingMode } from '@/models/datasets'import { IndexingType } from '../../../create/step-two'import ChunkStructure from '../../chunk-structure'@@ -55,6 +56,11 @@ const IndexingSection = ({readonly = false,}: IndexingSectionProps) => {const { t } = useTranslation()+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })+ const isNonCloudEdition = deploymentEdition === 'COMMUNITY' || deploymentEdition === 'ENTERPRISE'const docLink = useDocLink()const isShowIndexMethod =@@ -72,7 +78,7 @@ const IndexingSection = ({[ChunkingMode.text, ChunkingMode.parentChild].includes(currentDataset?.doc_form as ChunkingMode,) &&- IS_CE_EDITION+ isNonCloudEditionreturn (<>diff --git a/web/app/components/datasets/settings/permission-selector/__tests__/index.spec.tsx b/web/app/components/datasets/settings/permission-selector/__tests__/index.spec.tsxindex 34639684b2e..80ac4e7aa97 100644--- a/web/app/components/datasets/settings/permission-selector/__tests__/index.spec.tsx+++ b/web/app/components/datasets/settings/permission-selector/__tests__/index.spec.tsx@@ -1,12 +1,13 @@import type { ComponentProps, ReactNode } from 'react'import type { Member } from '@/models/common'+import { QueryClientProvider } from '@tanstack/react-query'import { render, screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { Provider } from 'jotai'import { userProfileQueryOptions } from '@/features/account-profile/client'import { systemFeaturesQueryOptions } from '@/features/system-features/client'-import { defaultSystemFeatures } from '@/features/system-features/config'import { DatasetPermission } from '@/models/datasets'+import { createSystemFeaturesFixture } from '@/test/console/system-features'import { createQueryAtomTestStore } from '@/test/query-atom'import PermissionSelector from '../index'@@ -73,12 +74,16 @@ const renderSelector = (profile: currentUser,meta: { currentVersion: null, currentEnv: null },})- queryClient.setQueryData(systemFeaturesQueryOptions().queryKey, {- ...defaultSystemFeatures,- rbac_enabled: options.rbacEnabled ?? false,- })+ queryClient.setQueryData(+ systemFeaturesQueryOptions().queryKey,+ createSystemFeaturesFixture({+ rbac_enabled: options.rbacEnabled ?? false,+ }),+ )const wrapper = ({ children }: { children: ReactNode }) => (- <Provider store={store}>{children}</Provider>+ <QueryClientProvider client={queryClient}>+ <Provider store={store}>{children}</Provider>+ </QueryClientProvider>)return render(<PermissionSelector {...defaultProps} {...props} />, { wrapper })diff --git a/web/app/components/datasets/settings/permission-selector/index.tsx b/web/app/components/datasets/settings/permission-selector/index.tsxindex c492ce7b7d1..b2c302bc1db 100644--- a/web/app/components/datasets/settings/permission-selector/index.tsx+++ b/web/app/components/datasets/settings/permission-selector/index.tsx@@ -4,12 +4,13 @@ import { cn } from '@langgenius/dify-ui/cn'import { Input } from '@langgenius/dify-ui/input'import { Popover, PopoverContent, PopoverTitle, PopoverTrigger } from '@langgenius/dify-ui/popover'import { RadioGroup } from '@langgenius/dify-ui/radio'+import { useSuspenseQuery } from '@tanstack/react-query'import { useDebounceFn } from 'ahooks'import { useAtomValue } from 'jotai'import { useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import { userProfileAtom } from '@/context/account-state'-import { datasetRbacEnabledAtom } from '@/context/system-features-state'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { DatasetPermission } from '@/models/datasets'import MemberItem from './member-item'import PermissionItem from './permission-item'@@ -33,7 +34,10 @@ const PermissionSelector = ({}: PermissionSelectorProps) => {const { t } = useTranslation()const userProfile = useAtomValue(userProfileAtom)- const isRbacEnabled = useAtomValue(datasetRbacEnabledAtom)+ const { data: isRbacEnabled } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ rbac_enabled }) => rbac_enabled,+ })const [keywords, setKeywords] = useState('')const [searchKeywords, setSearchKeywords] = useState('')const { run: handleSearch } = useDebounceFn(diff --git a/web/app/components/explore/__tests__/index.spec.tsx b/web/app/components/explore/__tests__/index.spec.tsxindex 9d0927042f7..a35d5926730 100644--- a/web/app/components/explore/__tests__/index.spec.tsx+++ b/web/app/components/explore/__tests__/index.spec.tsx@@ -1,5 +1,6 @@-import { render, screen } from '@testing-library/react'+import { screen } from '@testing-library/react'import { MediaType } from '@/hooks/use-breakpoints'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import Explore from '../index'const mockReplace = vi.fn()diff --git a/web/app/components/explore/app-card/__tests__/index.spec.tsx b/web/app/components/explore/app-card/__tests__/index.spec.tsxindex 8abe4db3a5d..96a782c40ff 100644--- a/web/app/components/explore/app-card/__tests__/index.spec.tsx+++ b/web/app/components/explore/app-card/__tests__/index.spec.tsx@@ -1,10 +1,11 @@+import type { DeploymentEdition } from '@dify/contracts/api/console/system-features/types.gen'import type { AppCardProps } from '../index'import type { App } from '@/models/explore'import { fireEvent, screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import * as React from 'react'import { trackEvent } from '@/app/components/base/amplitude'-import { renderWithConsoleQuery as render } from '@/test/console/query-data'+import { renderWithConsoleQuery } from '@/test/console/query-data'import { AppModeEnum } from '@/types/app'import AppCard from '../index'@@ -16,20 +17,6 @@ vi.mock('@/app/components/base/amplitude', () => ({trackEvent: vi.fn(),}))-const mockConfig = vi.hoisted(() => ({- isCloudEdition: true,-}))--vi.mock('@/config', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/config')>()- return {- ...actual,- get IS_CLOUD_EDITION() {- return mockConfig.isCloudEdition- },- }-})-const createApp = (overrides?: Partial<App>): App => ({can_trial: true,app_id: 'app-id',@@ -63,6 +50,7 @@ describe('AppCard', () => {const onCreate = vi.fn()const onTry = vi.fn()const mockTrackEvent = vi.mocked(trackEvent)+ let deploymentEdition: DeploymentEdition = 'CLOUD'const renderComponent = (props?: Partial<AppCardProps>) => {const mergedProps: AppCardProps = {@@ -73,11 +61,13 @@ describe('AppCard', () => {isExplore: false,...props,}- return render(<AppCard {...mergedProps} />)+ return renderWithConsoleQuery(<AppCard {...mergedProps} />, {+ systemFeatures: { deployment_edition: deploymentEdition },+ })}beforeEach(() => {- mockConfig.isCloudEdition = true+ deploymentEdition = 'CLOUD'vi.clearAllMocks()})@@ -138,14 +128,14 @@ describe('AppCard', () => {})it('should make the app card clickable outside cloud edition when create is allowed', () => {- mockConfig.isCloudEdition = false+ deploymentEdition = 'COMMUNITY'renderComponent({ canCreate: true, isExplore: true })expect(screen.getByRole('button', { name: 'Sample App' })).toHaveClass('cursor-pointer')})it('should not make the app card clickable outside cloud edition when create is not allowed', () => {- mockConfig.isCloudEdition = false+ deploymentEdition = 'COMMUNITY'renderComponent({ canCreate: false, isExplore: true })expect(screen.queryByRole('button', { name: 'Sample App' })).not.toBeInTheDocument()@@ -195,7 +185,7 @@ describe('AppCard', () => {})it('should call onCreate when app card is clicked outside cloud edition', () => {- mockConfig.isCloudEdition = false+ deploymentEdition = 'COMMUNITY'renderComponent({ canCreate: true, isExplore: true })diff --git a/web/app/components/explore/app-card/index.tsx b/web/app/components/explore/app-card/index.tsxindex e138b41fd06..639c9a7ee7f 100644--- a/web/app/components/explore/app-card/index.tsx+++ b/web/app/components/explore/app-card/index.tsx@@ -2,11 +2,12 @@import type { App } from '@/models/explore'import type { TryAppSelection } from '@/types/try-app'import { cn } from '@langgenius/dify-ui/cn'+import { useSuspenseQuery } from '@tanstack/react-query'import { useId } from 'react'import { useTranslation } from 'react-i18next'import { trackEvent } from '@/app/components/base/amplitude'import AppIcon from '@/app/components/base/app-icon'-import { IS_CLOUD_EDITION } from '@/config'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { AppModeEnum } from '@/types/app'import { AppTypeIcon } from '../../app/type-selector'@@ -20,10 +21,14 @@ export type AppCardProps = {const AppCard = ({ app, canCreate, onCreate, onTry, isExplore = true }: AppCardProps) => {const { t } = useTranslation()+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })const nameId = useId()const descriptionId = useId()const { app: appBasicInfo } = app- const canViewApp = IS_CLOUD_EDITION+ const canViewApp = deploymentEdition === 'CLOUD'const isClickable = isExplore && (canViewApp || canCreate)const handleTryApp = () => {trackEvent('preview_template', {@@ -36,7 +41,7 @@ const AppCard = ({ app, canCreate, onCreate, onTry, isExplore = true }: AppCardPonTry({ appId: app.app_id, app })}const handleCardClick = () => {- if (IS_CLOUD_EDITION) {+ if (canViewApp) {handleTryApp()return}diff --git a/web/app/components/explore/app-list/__tests__/index.spec.tsx b/web/app/components/explore/app-list/__tests__/index.spec.tsxindex 8691f937487..aa034c60408 100644--- a/web/app/components/explore/app-list/__tests__/index.spec.tsx+++ b/web/app/components/explore/app-list/__tests__/index.spec.tsx@@ -2,6 +2,7 @@ import type {StepByStepTourStatePatchPayload,StepByStepTourStateResponse,} from '@dify/contracts/api/console/onboarding/types.gen'+import type { DeploymentEdition } from '@dify/contracts/api/console/system-features/types.gen'import type { ReactNode } from 'react'import type { Mock } from 'vitest'import type { CreateAppModalProps } from '@/app/components/explore/create-app-modal'@@ -230,6 +231,10 @@ vi.mock('@/service/client', () => ({systemFeatures: {get: {queryKey: () => ['console', 'systemFeatures'],+ queryOptions: (options: Record<string, unknown> = {}) => ({+ queryKey: ['console', 'systemFeatures'],+ ...options,+ }),},},apps: {@@ -346,20 +351,6 @@ vi.mock('@/utils/create-app-tracking', () => ({trackCreateApp: (...args: unknown[]) => mockTrackCreateApp(...args),}))-const mockConfig = vi.hoisted(() => ({- isCloudEdition: false,-}))--vi.mock('@/config', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/config')>()- return {- ...actual,- get IS_CLOUD_EDITION() {- return mockConfig.isCloudEdition- },- }-})-vi.mock('@/app/components/explore/create-app-modal', () => ({default: (props: CreateAppModalProps) => {if (!props.show) return null@@ -514,7 +505,7 @@ type RenderOptions = {enableExploreBanner?: booleanenableLearnApp?: booleanextra?: ReactNode- isCloudEdition?: boolean+ deploymentEdition?: DeploymentEdition}const localeInput = { query: { language: 'en-US' } }@@ -527,10 +518,10 @@ const renderAppList = (searchParams?: Record<string, string>,options: RenderOptions = {},) => {- mockConfig.isCloudEdition = options.isCloudEdition ?? falsemockAppCreatePermission(hasEditPermission)const { wrapper: ConsoleQueryWrapper, queryClient } = createConsoleQueryWrapper({systemFeatures: {+ deployment_edition: options.deploymentEdition ?? 'COMMUNITY',enable_explore_banner: options.enableExploreBanner ?? false,enable_learn_app: options.enableLearnApp ?? true,},@@ -620,7 +611,6 @@ describe('AppList', () => {mockBannersLoading = falsemockIsLoading = falsemockIsError = false- mockConfig.isCloudEdition = falsemockStepByStepTour.reset()})@@ -1045,7 +1035,7 @@ describe('AppList', () => {minimized: true,})- renderAppList(true, undefined, undefined, { isCloudEdition: true })+ renderAppList(true, undefined, undefined, { deploymentEdition: 'CLOUD' })await user.click(await screen.findByRole('button', { name: 'Learn Workflow Basics' }))@@ -1072,7 +1062,7 @@ describe('AppList', () => {renderAppList(true, undefined, undefined, {extra: <SkipHomeGuideProbe />,- isCloudEdition: true,+ deploymentEdition: 'CLOUD',})await user.click(await screen.findByRole('button', { name: 'Learn Workflow Basics' }))@@ -1103,7 +1093,7 @@ describe('AppList', () => {minimized: true,})- renderAppList(false, undefined, undefined, { isCloudEdition: true })+ renderAppList(false, undefined, undefined, { deploymentEdition: 'CLOUD' })await user.click(await screen.findByRole('button', { name: 'Learn Workflow Basics' }))@@ -1153,7 +1143,7 @@ describe('AppList', () => {},)- renderAppList(true, undefined, undefined, { isCloudEdition: true })+ renderAppList(true, undefined, undefined, { deploymentEdition: 'CLOUD' })await user.click(await screen.findByRole('button', { name: 'Learn Workflow Basics' }))await user.click(await screen.findByTestId('try-app-create'))@@ -1210,7 +1200,7 @@ describe('AppList', () => {},)- renderAppList(true, undefined, undefined, { isCloudEdition: true })+ renderAppList(true, undefined, undefined, { deploymentEdition: 'CLOUD' })await user.click(await screen.findByRole('button', { name: 'Learn Workflow Basics' }))await user.click(await screen.findByTestId('try-app-create'))@@ -1277,7 +1267,7 @@ describe('AppList', () => {},)- renderAppList(true, undefined, undefined, { isCloudEdition: true })+ renderAppList(true, undefined, undefined, { deploymentEdition: 'CLOUD' })await user.click(await screen.findByRole('button', { name: 'Learn Workflow Basics' }))await user.click(await screen.findByTestId('try-app-create'))@@ -1307,7 +1297,7 @@ describe('AppList', () => {minimized: true,})- renderAppList(true, undefined, undefined, { isCloudEdition: true })+ renderAppList(true, undefined, undefined, { deploymentEdition: 'CLOUD' })await user.click(await screen.findByRole('button', { name: 'Learn Workflow Basics' }))const createFromDetailsButton = await screen.findByTestId('try-app-create')@@ -1465,7 +1455,7 @@ describe('AppList', () => {allList: [createApp()],}- renderAppList(true, undefined, undefined, { isCloudEdition: true })+ renderAppList(true, undefined, undefined, { deploymentEdition: 'CLOUD' })fireEvent.click(screen.getByRole('button', { name: 'Alpha' }))expect(await screen.findByTestId('try-app-panel')).toBeInTheDocument()@@ -1496,7 +1486,7 @@ describe('AppList', () => {},)- renderAppList(true, undefined, undefined, { isCloudEdition: true })+ renderAppList(true, undefined, undefined, { deploymentEdition: 'CLOUD' })fireEvent.click(screen.getByRole('button', { name: 'Alpha' }))await screen.findByTestId('try-app-panel')@@ -1519,7 +1509,7 @@ describe('AppList', () => {allList: [createApp()],}- renderAppList(true, undefined, undefined, { isCloudEdition: true })+ renderAppList(true, undefined, undefined, { deploymentEdition: 'CLOUD' })fireEvent.click(screen.getByRole('button', { name: 'Alpha' }))expect(await screen.findByTestId('try-app-panel')).toBeInTheDocument()diff --git a/web/app/components/explore/learn-dify/__tests__/item.spec.tsx b/web/app/components/explore/learn-dify/__tests__/item.spec.tsxindex 5ca768b3918..fc2f328110a 100644--- a/web/app/components/explore/learn-dify/__tests__/item.spec.tsx+++ b/web/app/components/explore/learn-dify/__tests__/item.spec.tsx@@ -1,22 +1,15 @@+import type { DeploymentEdition } from '@dify/contracts/api/console/system-features/types.gen'+import type { ReactElement } from 'react'import type { App } from '@/models/explore'-import { fireEvent, render, screen } from '@testing-library/react'+import { fireEvent, screen } from '@testing-library/react'import { trackEvent } from '@/app/components/base/amplitude'+import { renderWithConsoleQuery } from '@/test/console/query-data'import { AppModeEnum } from '@/types/app'import LearnDifyItem from '../item'-const mockConfig = vi.hoisted(() => ({- isCloudEdition: true,-}))--vi.mock('@/config', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/config')>()- return {- ...actual,- get IS_CLOUD_EDITION() {- return mockConfig.isCloudEdition- },- }-})+let deploymentEdition: DeploymentEdition = 'CLOUD'+const render = (ui: ReactElement) =>+ renderWithConsoleQuery(ui, { systemFeatures: { deployment_edition: deploymentEdition } })vi.mock('@/app/components/base/amplitude', () => ({trackEvent: vi.fn(),@@ -53,7 +46,7 @@ describe('LearnDifyItem', () => {const mockTrackEvent = vi.mocked(trackEvent)beforeEach(() => {- mockConfig.isCloudEdition = true+ deploymentEdition = 'CLOUD'vi.clearAllMocks()})@@ -65,7 +58,7 @@ describe('LearnDifyItem', () => {})it('should create app when card is clicked outside cloud edition', () => {- mockConfig.isCloudEdition = false+ deploymentEdition = 'COMMUNITY'const app = createApp()const onCreate = vi.fn()@@ -78,7 +71,7 @@ describe('LearnDifyItem', () => {})it('should not make the card clickable outside cloud edition when create is unavailable', () => {- mockConfig.isCloudEdition = false+ deploymentEdition = 'COMMUNITY'render(<LearnDifyItem canCreate={false} item={createApp()} onTry={vi.fn()} />)diff --git a/web/app/components/explore/learn-dify/item.tsx b/web/app/components/explore/learn-dify/item.tsxindex 122c6e1b005..351c4576fb6 100644--- a/web/app/components/explore/learn-dify/item.tsx+++ b/web/app/components/explore/learn-dify/item.tsx@@ -4,10 +4,11 @@ import type { KeyboardEvent } from 'react'import type { App } from '@/models/explore'import type { TryAppSelection } from '@/types/try-app'import { cn } from '@langgenius/dify-ui/cn'+import { useSuspenseQuery } from '@tanstack/react-query'import * as React from 'react'import { trackEvent } from '@/app/components/base/amplitude'import AppIcon from '@/app/components/base/app-icon'-import { IS_CLOUD_EDITION } from '@/config'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'type LearnDifyItemProps = {canCreate: boolean@@ -17,8 +18,12 @@ type LearnDifyItemProps = {}const LearnDifyItem = ({ canCreate, item, onCreate, onTry }: LearnDifyItemProps) => {+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })const appBasicInfo = item.app- const canViewApp = IS_CLOUD_EDITION+ const canViewApp = deploymentEdition === 'CLOUD'const canShowCreate = canCreate && !!onCreateconst isClickable = canViewApp || canShowCreate@@ -33,7 +38,7 @@ const LearnDifyItem = ({ canCreate, item, onCreate, onTry }: LearnDifyItemProps)onTry?.({ appId: item.app_id, app: item })}const handleCardClick = () => {- if (IS_CLOUD_EDITION) {+ if (canViewApp) {handleTryApp()return}diff --git a/web/app/components/explore/sidebar/__tests__/index.spec.tsx b/web/app/components/explore/sidebar/__tests__/index.spec.tsxindex b2abcc8c15c..6635ca051e9 100644--- a/web/app/components/explore/sidebar/__tests__/index.spec.tsx+++ b/web/app/components/explore/sidebar/__tests__/index.spec.tsx@@ -1,6 +1,7 @@import type { InstalledApp } from '@/models/explore'-import { fireEvent, render, screen, waitFor } from '@testing-library/react'+import { fireEvent, screen, waitFor } from '@testing-library/react'import { expectLoadingButton } from '@/test/button'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { AppModeEnum } from '@/types/app'import SideBar from '../index'diff --git a/web/app/components/explore/try-app/__tests__/index.spec.tsx b/web/app/components/explore/try-app/__tests__/index.spec.tsxindex f83cedc4d16..5ddb69b0a70 100644--- a/web/app/components/explore/try-app/__tests__/index.spec.tsx+++ b/web/app/components/explore/try-app/__tests__/index.spec.tsx@@ -1,17 +1,12 @@import type { TryAppInfo } from '@/service/try-app'import { cleanup, fireEvent, screen, waitFor } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { renderWithConsoleQuery as render } from '@/test/console/query-data'+import { renderWithConsoleQuery } from '@/test/console/query-data'import TryApp from '../index'import { TypeEnum } from '../types'-vi.mock('@/config', async (importOriginal) => {- const actual = (await importOriginal()) as object- return {- ...actual,- IS_CLOUD_EDITION: true,- }-})+const render = (ui: React.ReactElement) =>+ renderWithConsoleQuery(ui, { systemFeatures: { deployment_edition: 'CLOUD' } })const mockUseGetTryAppInfo = vi.fn()diff --git a/web/app/components/explore/try-app/index.tsx b/web/app/components/explore/try-app/index.tsxindex d0c419db965..32f3ba7a367 100644--- a/web/app/components/explore/try-app/index.tsx+++ b/web/app/components/explore/try-app/index.tsx@@ -11,7 +11,6 @@ import { useState } from 'react'import { useTranslation } from 'react-i18next'import AppUnavailable from '@/app/components/base/app-unavailable'import Loading from '@/app/components/base/loading'-import { IS_CLOUD_EDITION } from '@/config'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { useGetTryAppInfo } from '@/service/use-try-app'import App from './app'@@ -41,7 +40,7 @@ const TryApp: FC<Props> = ({const { t } = useTranslation()const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())const isTrialApp = !!(app && app.can_trial && systemFeatures.enable_trial_app)- const canUseTryTab = IS_CLOUD_EDITION && (app ? isTrialApp : true)+ const canUseTryTab = systemFeatures.deployment_edition === 'CLOUD' && (app ? isTrialApp : true)const [type, setType] = useState<TypeEnum>(() => (canUseTryTab ? TypeEnum.TRY : TypeEnum.DETAIL))const activeType = canUseTryTab ? type : TypeEnum.DETAILconst { data: appDetail, isLoading, isError, error } = useGetTryAppInfo(appId)@@ -78,7 +77,7 @@ const TryApp: FC<Props> = ({><div className="flex shrink-0 justify-between pl-4"><TabsList>- {IS_CLOUD_EDITION && (+ {systemFeatures.deployment_edition === 'CLOUD' && (<TabsTabvalue={TypeEnum.TRY}disabled={app ? !isTrialApp : false}@@ -110,7 +109,7 @@ const TryApp: FC<Props> = ({</div>{/* Main content */}<div className="mt-2 flex h-0 grow justify-between space-x-2">- {IS_CLOUD_EDITION && (+ {systemFeatures.deployment_edition === 'CLOUD' && (<TabsPanel value={TypeEnum.TRY} className="min-w-0 flex-1"><App appId={appId} appDetail={appDetail} /></TabsPanel>diff --git a/web/app/components/external-attribution-recorder.tsx b/web/app/components/external-attribution-recorder.tsxindex b2a00263a25..ef761323b68 100644--- a/web/app/components/external-attribution-recorder.tsx+++ b/web/app/components/external-attribution-recorder.tsx@@ -3,7 +3,6 @@import Cookies from 'js-cookie'import { useEffect } from 'react'import { useAnalyticsConsent } from '@/app/components/base/analytics-consent/consent-store'-import { IS_CLOUD_EDITION } from '@/config'import { useSearchParams } from '@/next/navigation'import { rememberCreateAppExternalAttribution } from '@/utils/create-app-tracking'@@ -74,7 +73,7 @@ const ExternalAttributionRecorder = () => {const searchParams = useSearchParams()useEffect(() => {- if (!IS_CLOUD_EDITION || analyticsConsent !== 'granted') return+ if (analyticsConsent !== 'granted') returnconst attributionSearchParams = resolveAttributionSearchParams(searchParams)if (!attributionSearchParams) returndiff --git a/web/app/components/goto-anything/actions/commands/__tests__/slash.spec.tsx b/web/app/components/goto-anything/actions/commands/__tests__/slash.spec.tsxindex b2f94af91c4..57cb861897b 100644--- a/web/app/components/goto-anything/actions/commands/__tests__/slash.spec.tsx+++ b/web/app/components/goto-anything/actions/commands/__tests__/slash.spec.tsx@@ -1,5 +1,5 @@import type { SearchResult } from '../../types'-import { render } from '@testing-library/react'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { slashAction } from '../slash'import { SlashCommandProvider } from '../slash-provider'@@ -27,11 +27,16 @@ const {featureFlag: { enabled: false },}))-vi.mock('@/config', () => ({- get ENABLE_FEATURE_PREVIEW() {- return featureFlag.enabled- },-}))+vi.mock('@/config', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/config')>()++ return {+ ...actual,+ get ENABLE_FEATURE_PREVIEW() {+ return featureFlag.enabled+ },+ }+})vi.mock('next-themes', () => ({useTheme: () => ({diff --git a/web/app/components/header/account-about/__tests__/index.spec.tsx b/web/app/components/header/account-about/__tests__/index.spec.tsxindex 01545443f55..ff965d9a08c 100644--- a/web/app/components/header/account-about/__tests__/index.spec.tsx+++ b/web/app/components/header/account-about/__tests__/index.spec.tsx@@ -3,17 +3,6 @@ import { fireEvent, screen } from '@testing-library/react'import { renderWithConsoleQuery } from '@/test/console/query-data'import AccountAbout from '../index'-let mockIsCEEdition = false-vi.mock('@/config', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/config')>()- return {- ...actual,- get IS_CE_EDITION() {- return mockIsCEEdition- },- }-})-describe('AccountAbout', () => {const mockVersionInfo: LangGeniusVersionInfo = {current_version: '0.6.0',@@ -33,7 +22,6 @@ describe('AccountAbout', () => {beforeEach(() => {vi.clearAllMocks()- mockIsCEEdition = false})describe('Rendering', () => {@@ -41,7 +29,7 @@ describe('AccountAbout', () => {renderWithConsoleQuery(<AccountAbout langGeniusVersionInfo={mockVersionInfo} onCancel={mockOnCancel} />,{- systemFeatures: { branding: { enabled: false } },+ systemFeatures: { deployment_edition: 'CLOUD', branding: { enabled: false } },},)@@ -53,7 +41,10 @@ describe('AccountAbout', () => {renderWithConsoleQuery(<AccountAbout langGeniusVersionInfo={mockVersionInfo} onCancel={mockOnCancel} />,{- systemFeatures: { branding: { enabled: true, workspace_logo: 'custom-logo.png' } },+ systemFeatures: {+ deployment_edition: 'CLOUD',+ branding: { enabled: true, workspace_logo: 'custom-logo.png' },+ },},)@@ -67,6 +58,7 @@ describe('AccountAbout', () => {it('should show "Latest Available" when current version equals latest', () => {renderWithConsoleQuery(<AccountAbout langGeniusVersionInfo={mockVersionInfo} onCancel={mockOnCancel} />,+ { systemFeatures: { deployment_edition: 'CLOUD' } },)expect(screen.getByText(/about.latestAvailable/)).toBeInTheDocument()@@ -77,6 +69,7 @@ describe('AccountAbout', () => {renderWithConsoleQuery(<AccountAbout langGeniusVersionInfo={behindVersionInfo} onCancel={mockOnCancel} />,+ { systemFeatures: { deployment_edition: 'CLOUD' } },)expect(screen.getByText(/about.nowAvailable/)).toBeInTheDocument()@@ -86,21 +79,20 @@ describe('AccountAbout', () => {describe('Community Edition', () => {it('should render correctly in Community Edition', () => {- mockIsCEEdition = true-renderWithConsoleQuery(<AccountAbout langGeniusVersionInfo={mockVersionInfo} onCancel={mockOnCancel} />,+ { systemFeatures: { deployment_edition: 'COMMUNITY' } },)expect(screen.getByText(/Open Source License/)).toBeInTheDocument()})it('should hide update button in Community Edition when behind version', () => {- mockIsCEEdition = trueconst behindVersionInfo = { ...mockVersionInfo, latest_version: '0.7.0' }renderWithConsoleQuery(<AccountAbout langGeniusVersionInfo={behindVersionInfo} onCancel={mockOnCancel} />,+ { systemFeatures: { deployment_edition: 'COMMUNITY' } },)expect(screen.queryByText(/about.updateNow/)).not.toBeInTheDocument()@@ -111,6 +103,7 @@ describe('AccountAbout', () => {it('should call onCancel when close button is clicked', () => {renderWithConsoleQuery(<AccountAbout langGeniusVersionInfo={mockVersionInfo} onCancel={mockOnCancel} />,+ { systemFeatures: { deployment_edition: 'CLOUD' } },)fireEvent.click(screen.getByRole('button', { name: 'common.operation.close' }))diff --git a/web/app/components/header/account-about/index.tsx b/web/app/components/header/account-about/index.tsxindex f93746869b3..e4c497c5f3b 100644--- a/web/app/components/header/account-about/index.tsx+++ b/web/app/components/header/account-about/index.tsx@@ -7,7 +7,6 @@ import { useSuspenseQuery } from '@tanstack/react-query'import dayjs from 'dayjs'import { useTranslation } from 'react-i18next'import DifyLogo from '@/app/components/base/logo/dify-logo'-import { IS_CE_EDITION } from '@/config'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import Link from '@/next/link'@@ -20,6 +19,9 @@ export default function AccountAbout({ langGeniusVersionInfo, onCancel }: IAccouconst { t } = useTranslation()const isLatest = langGeniusVersionInfo.current_version === langGeniusVersionInfo.latest_versionconst { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())+ const isNonCloudEdition =+ systemFeatures.deployment_edition === 'COMMUNITY' ||+ systemFeatures.deployment_edition === 'ENTERPRISE'return (<Dialog@@ -56,7 +58,7 @@ export default function AccountAbout({ langGeniusVersionInfo, onCancel }: IAccou<div className="flex flex-col items-center gap-2 text-center text-xs font-normal text-text-secondary"><div>©{dayjs().year()} LangGenius, Inc., Contributors.</div><div className="text-text-accent">- {IS_CE_EDITION ? (+ {isNonCloudEdition && (<Linkhref="https://github.com/langgenius/dify/blob/main/LICENSE"target="_blank"@@ -64,7 +66,8 @@ export default function AccountAbout({ langGeniusVersionInfo, onCancel }: IAccou>Open Source License</Link>- ) : (+ )}+ {systemFeatures.deployment_edition === 'CLOUD' && (<><Link href="https://dify.ai/privacy" target="_blank" rel="noopener noreferrer">Privacy Policy@@ -101,7 +104,7 @@ export default function AccountAbout({ langGeniusVersionInfo, onCancel }: IAccou{t(($) => $['about.changeLog'], { ns: 'common' })}</Link></Button>- {!isLatest && !IS_CE_EDITION && (+ {!isLatest && systemFeatures.deployment_edition === 'CLOUD' && (<Button variant="primary" size="small"><Linkhref={langGeniusVersionInfo.release_notes}diff --git a/web/app/components/header/account-dropdown/__tests__/index.spec.tsx b/web/app/components/header/account-dropdown/__tests__/index.spec.tsxindex 022b3db0fac..b01e39a0c61 100644--- a/web/app/components/header/account-dropdown/__tests__/index.spec.tsx+++ b/web/app/components/header/account-dropdown/__tests__/index.spec.tsx@@ -2,6 +2,7 @@ import type { GetSystemFeaturesResponse } from '@dify/contracts/api/console/systimport type { ModalContextState } from '@/context/modal-context'import type { ProviderContextState } from '@/context/provider-context'import type { ConsoleStateFixture } from '@/test/console/state-fixture'+import type { DeepPartial } from '@/test/console/system-features'import { fireEvent, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { renderToString } from 'react-dom/server'@@ -15,13 +16,6 @@ import { createAccountProfileQueryClient } from '@/test/console/account-profile'import { renderWithConsoleQuery } from '@/test/console/query-data'import AppSelector from '../index'-type DeepPartial<T> =- T extends Array<infer U>- ? Array<U>- : T extends object- ? { [K in keyof T]?: DeepPartial<T[K]> }- : T-vi.mock('../../account-setting', () => ({default: () => <div data-testid="account-setting">AccountSetting</div>,}))@@ -104,7 +98,6 @@ vi.mock('@/next/navigation', async (importOriginal) => {// Mock config and envconst { mockConfig, mockEnv } = vi.hoisted(() => ({mockConfig: {- IS_CLOUD_EDITION: false,AMPLITUDE_API_KEY: '',ZENDESK_WIDGET_KEY: '',SUPPORT_EMAIL_ADDRESS: '',@@ -119,15 +112,9 @@ vi.mock('@/config', async (importOriginal) => {const actual = await importOriginal<typeof import('@/config')>()return {...actual,- get IS_CLOUD_EDITION() {- return mockConfig.IS_CLOUD_EDITION- },get AMPLITUDE_API_KEY() {return mockConfig.AMPLITUDE_API_KEY},- get isAmplitudeEnabled() {- return mockConfig.IS_CLOUD_EDITION && !!mockConfig.AMPLITUDE_API_KEY- },get ZENDESK_WIDGET_KEY() {return mockConfig.ZENDESK_WIDGET_KEY},@@ -135,7 +122,6 @@ vi.mock('@/config', async (importOriginal) => {return mockConfig.SUPPORT_EMAIL_ADDRESS},IS_DEV: false,- IS_CE_EDITION: false,}})vi.mock('@/env', () => mockEnv)@@ -191,6 +177,7 @@ describe('AccountDropdown', () => {const mockPush = vi.fn()const mockLogout = vi.fn()const mockSetShowAccountSettingModal = vi.fn()+ let deploymentEdition: GetSystemFeaturesResponse['deployment_edition'] = 'COMMUNITY'const renderWithRouter = (ui: React.ReactElement,@@ -202,14 +189,17 @@ describe('AccountDropdown', () => {})return renderWithConsoleQuery(ui, {queryClient,- systemFeatures: options.systemFeatures ?? { branding: { enabled: false } },+ systemFeatures: options.systemFeatures ?? {+ deployment_edition: deploymentEdition,+ branding: { enabled: false },+ },})}beforeEach(() => {vi.clearAllMocks()vi.stubGlobal('localStorage', { removeItem: vi.fn() })- mockConfig.IS_CLOUD_EDITION = false+ deploymentEdition = 'COMMUNITY'mockEnv.env.NEXT_PUBLIC_SITE_ABOUT = 'show'setConsoleState(baseConsoleState)@@ -337,7 +327,7 @@ describe('AccountDropdown', () => {it('should show Compliance in Cloud Edition for workspace owner', () => {// Arrange- mockConfig.IS_CLOUD_EDITION = true+ deploymentEdition = 'CLOUD'setConsoleState({...baseConsoleState,userProfile: { ...baseConsoleState.userProfile, name: 'User' },@@ -357,10 +347,9 @@ describe('AccountDropdown', () => {expect(screen.getByText('common.userProfile.compliance')).toBeInTheDocument()})- // Compound AND middle-false: IS_CLOUD_EDITION=true but isCurrentWorkspaceOwner=falseit('should hide Compliance in Cloud Edition when user is not workspace owner', () => {// Arrange- mockConfig.IS_CLOUD_EDITION = true+ deploymentEdition = 'CLOUD'setConsoleState({...baseConsoleState,isCurrentWorkspaceOwner: false,diff --git a/web/app/components/header/account-dropdown/default-menu-content.tsx b/web/app/components/header/account-dropdown/default-menu-content.tsxindex 06497ee17a8..9af4dad1a7a 100644--- a/web/app/components/header/account-dropdown/default-menu-content.tsx+++ b/web/app/components/header/account-dropdown/default-menu-content.tsx@@ -15,7 +15,6 @@ import { useTranslation } from 'react-i18next'import PremiumBadge from '@/app/components/base/premium-badge'import ThemeSwitcher from '@/app/components/base/theme-switcher'import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'-import { IS_CLOUD_EDITION } from '@/config'import { userProfileAtom } from '@/context/account-state'import { useDocLink } from '@/context/i18n'import { useModalContext } from '@/context/modal-context'@@ -159,7 +158,9 @@ export function DefaultMenuContent({label={t(($) => $['userProfile.helpCenter'], { ns: 'common' })}trailing={<ExternalLinkIndicator />}/>- {IS_CLOUD_EDITION && isCurrentWorkspaceOwner && <Compliance />}+ {systemFeatures.deployment_edition === 'CLOUD' && isCurrentWorkspaceOwner && (+ <Compliance />+ )}</AccountMenuSection><DropdownMenuSeparator className="my-0! bg-divider-subtle" /><AccountMenuSection>diff --git a/web/app/components/header/account-setting/__tests__/index.spec.tsx b/web/app/components/header/account-setting/__tests__/index.spec.tsxindex 1f32f24cb68..e57deed6831 100644--- a/web/app/components/header/account-setting/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/__tests__/index.spec.tsx@@ -10,23 +10,10 @@ import { ACCOUNT_SETTING_TAB } from '../constants'import AccountSetting from '../index'const mockResetModelProviderListExpanded = vi.fn()-const mockConfig = vi.hoisted(() => ({- IS_CLOUD_EDITION: true,-}))const mockConsoleState = vi.hoisted(() => ({current: null as unknown,}))-vi.mock('@/config', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/config')>()- return {- ...actual,- get IS_CLOUD_EDITION() {- return mockConfig.IS_CLOUD_EDITION- },- }-})-vi.mock('@/context/provider-context', async (importOriginal) => {const actual = await importOriginal<typeof import('@/context/provider-context')>()return {@@ -210,12 +197,14 @@ describe('AccountSetting', () => {onCancel?: () => voidonTabChange?: (tab: AccountSettingTab) => voidrbacEnabled?: boolean+ deploymentEdition?: 'COMMUNITY' | 'ENTERPRISE' | 'CLOUD'}) => {const {initialTab = ACCOUNT_SETTING_TAB.MEMBERS,onCancel = mockOnCancel,onTabChange = mockOnTabChange,rbacEnabled = true,+ deploymentEdition = 'CLOUD',} = props ?? {}const StatefulAccountSetting = () => {@@ -235,6 +224,7 @@ describe('AccountSetting', () => {return renderWithConsoleQuery(<StatefulAccountSetting />, {systemFeatures: {+ deployment_edition: deploymentEdition,webapp_auth: { enabled: true },branding: { enabled: false },enable_marketplace: true,@@ -246,7 +236,6 @@ describe('AccountSetting', () => {beforeEach(() => {vi.clearAllMocks()- mockConfig.IS_CLOUD_EDITION = truevi.mocked(useProviderContext).mockReturnValue({...baseProviderContextValue,enableBilling: true,@@ -535,10 +524,8 @@ describe('AccountSetting', () => {it('should hide workflow log archives outside cloud edition', () => {// Arrange- mockConfig.IS_CLOUD_EDITION = false-// Act- renderAccountSetting()+ renderAccountSetting({ deploymentEdition: 'COMMUNITY' })// Assertexpect(@@ -574,10 +561,11 @@ describe('AccountSetting', () => {it('should not render workflow log archives page outside cloud edition', () => {// Arrange- mockConfig.IS_CLOUD_EDITION = false-// Act- renderAccountSetting({ initialTab: ACCOUNT_SETTING_TAB.WORKFLOW_LOG_ARCHIVES })+ renderAccountSetting({+ initialTab: ACCOUNT_SETTING_TAB.WORKFLOW_LOG_ARCHIVES,+ deploymentEdition: 'COMMUNITY',+ })// Assertexpect(screen.queryByText('appLog.archives.upgradeTip.title')).not.toBeInTheDocument()diff --git a/web/app/components/header/account-setting/api-based-extension-page/__tests__/index.spec.tsx b/web/app/components/header/account-setting/api-based-extension-page/__tests__/index.spec.tsxindex d9a1e892e32..7c95d94b908 100644--- a/web/app/components/header/account-setting/api-based-extension-page/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/api-based-extension-page/__tests__/index.spec.tsx@@ -1,6 +1,6 @@import type { ApiBasedExtensionResponse } from '@dify/contracts/api/console/api-based-extension/types.gen'import { fireEvent, screen, waitFor } from '@testing-library/react'-import { render } from '@/test/console/render'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { ApiBasedExtensionPage } from '../index'const {@@ -28,6 +28,15 @@ vi.mock('@/context/permission-state', async () => {vi.mock('@/service/client', () => ({consoleQuery: {+ systemFeatures: {+ get: {+ queryKey: () => ['system-features'],+ queryOptions: (options: Record<string, unknown> = {}) => ({+ queryKey: ['system-features'],+ ...options,+ }),+ },+ },apiBasedExtension: {get: {queryOptions: () => ({}),@@ -47,15 +56,19 @@ vi.mock('@/service/client', () => ({},}))-vi.mock('@tanstack/react-query', () => ({- useQuery: vi.fn(() => mockApiBasedExtensionsQuery()),- useMutation: vi.fn((options: { mutationFn: (variables: unknown) => Promise<unknown> }) => ({- isPending: false,- mutate: (variables: unknown, mutationOptions?: { onSuccess?: (data: unknown) => void }) => {- options.mutationFn(variables).then((data) => mutationOptions?.onSuccess?.(data))- },- })),-}))+vi.mock('@tanstack/react-query', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@tanstack/react-query')>()+ return {+ ...actual,+ useQuery: vi.fn(() => mockApiBasedExtensionsQuery()),+ useMutation: vi.fn((options: { mutationFn: (variables: unknown) => Promise<unknown> }) => ({+ isPending: false,+ mutate: (variables: unknown, mutationOptions?: { onSuccess?: (data: unknown) => void }) => {+ options.mutationFn(variables).then((data) => mutationOptions?.onSuccess?.(data))+ },+ })),+ }+})describe('ApiBasedExtensionPage', () => {beforeEach(() => {diff --git a/web/app/components/header/account-setting/api-based-extension-page/__tests__/selector.spec.tsx b/web/app/components/header/account-setting/api-based-extension-page/__tests__/selector.spec.tsxindex dc06f70e02d..ba06a51d27c 100644--- a/web/app/components/header/account-setting/api-based-extension-page/__tests__/selector.spec.tsx+++ b/web/app/components/header/account-setting/api-based-extension-page/__tests__/selector.spec.tsx@@ -16,6 +16,13 @@ vi.mock('@/context/modal-context', () => ({useModalContext: vi.fn(),}))+vi.mock('@/context/i18n', () => ({+ useDocLink:+ () =>+ (path = '') =>+ `https://docs.dify.ai${path}`,+}))+vi.mock('@/service/client', () => ({consoleQuery: {apiBasedExtension: {diff --git a/web/app/components/header/account-setting/index.tsx b/web/app/components/header/account-setting/index.tsxindex 6bcc9f335eb..39e8ea60306 100644--- a/web/app/components/header/account-setting/index.tsx+++ b/web/app/components/header/account-setting/index.tsx@@ -11,7 +11,6 @@ import BillingPage from '@/app/components/billing/billing-page'import CustomPage from '@/app/components/custom/custom-page'import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'import MenuDialog from '@/app/components/header/account-setting/menu-dialog'-import { IS_CLOUD_EDITION } from '@/config'import { workspacePermissionKeysAtom } from '@/context/permission-state'import { useProviderContext } from '@/context/provider-context'import {@@ -66,7 +65,8 @@ export default function AccountSetting({const canManageWorkspaceRoles =isRbacEnabled && hasPermission(workspacePermissionKeys, 'workspace.role.manage')const canViewBilling = enableBilling && !isCurrentWorkspaceDatasetOperator- const canViewWorkflowLogArchives = IS_CLOUD_EDITION && isCurrentWorkspaceManager+ const canViewWorkflowLogArchives =+ systemFeatures.deployment_edition === 'CLOUD' && isCurrentWorkspaceManager// Keep legacy `language` deep links opening Preferences during the tab rename migration.const normalizedActiveTab =activeTab === ACCOUNT_SETTING_TAB.LANGUAGE ? ACCOUNT_SETTING_TAB.PREFERENCES : activeTabdiff --git a/web/app/components/header/account-setting/members-page/invited-modal/__tests__/index.spec.tsx b/web/app/components/header/account-setting/members-page/invited-modal/__tests__/index.spec.tsxindex c486effbea5..b7a4b8de271 100644--- a/web/app/components/header/account-setting/members-page/invited-modal/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/members-page/invited-modal/__tests__/index.spec.tsx@@ -1,14 +1,13 @@+import type { DeploymentEdition } from '@dify/contracts/api/console/system-features/types.gen'import type { MemberInviteResponse } from '@dify/contracts/api/console/workspaces/types.gen'-import { render, screen } from '@testing-library/react'+import type { ReactElement } from 'react'+import { screen } from '@testing-library/react'+import { renderWithConsoleQuery } from '@/test/console/query-data'import InvitedModal from '../index'-const mockConfigState = vi.hoisted(() => ({ isCeEdition: true }))--vi.mock('@/config', () => ({- get IS_CE_EDITION() {- return mockConfigState.isCeEdition- },-}))+let deploymentEdition: DeploymentEdition = 'COMMUNITY'+const render = (ui: ReactElement) =>+ renderWithConsoleQuery(ui, { systemFeatures: { deployment_edition: deploymentEdition } })describe('InvitedModal', () => {const mockOnCancel = vi.fn()@@ -24,7 +23,7 @@ describe('InvitedModal', () => {beforeEach(() => {vi.clearAllMocks()- mockConfigState.isCeEdition = true+ deploymentEdition = 'COMMUNITY'})it('should show success and failed invitation sections', async () => {@@ -85,32 +84,26 @@ describe('InvitedModal', () => {})})-describe('InvitedModal (non-CE edition)', () => {+describe('InvitedModal (Cloud edition)', () => {const mockOnCancel = vi.fn()beforeEach(() => {vi.clearAllMocks()- mockConfigState.isCeEdition = false- })-- afterEach(() => {- mockConfigState.isCeEdition = true+ deploymentEdition = 'CLOUD'})- it('should render invitationSentTip without CE edition content when IS_CE_EDITION is false', async () => {+ it('should render invitationSentTip without self-hosted content', async () => {const results: MemberInviteResponse['invitation_results'] = [{ email: '[email protected]', status: 'success', url: 'http://invite.com/1' },]render(<InvitedModal invitationResults={results} onCancel={mockOnCancel} />)- // The !IS_CE_EDITION branch - should show the tip textexpect(await screen.findByText(/members\.invitationSentTip/i)).toBeInTheDocument()- // CE-only content should not be shownexpect(screen.queryByText(/members\.invitationLink/i)).not.toBeInTheDocument()})- it('should show already-member details when IS_CE_EDITION is false', () => {+ it('should show already-member details', () => {const results: MemberInviteResponse['invitation_results'] = [{email: '[email protected]',diff --git a/web/app/components/header/account-setting/members-page/invited-modal/index.tsx b/web/app/components/header/account-setting/members-page/invited-modal/index.tsxindex d01eae35a47..a7d5a956973 100644--- a/web/app/components/header/account-setting/members-page/invited-modal/index.tsx+++ b/web/app/components/header/account-setting/members-page/invited-modal/index.tsx@@ -7,8 +7,9 @@ import type {import { Button } from '@langgenius/dify-ui/button'import { Dialog, DialogCloseButton, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'+import { useSuspenseQuery } from '@tanstack/react-query'import { useTranslation } from 'react-i18next'-import { IS_CE_EDITION } from '@/config'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import InvitationLink from './invitation-link'type IInvitedModalProps = {@@ -17,6 +18,12 @@ type IInvitedModalProps = {}const InvitedModal = ({ invitationResults, onCancel }: IInvitedModalProps) => {const { t } = useTranslation()+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })+ const isCloudEdition = deploymentEdition === 'CLOUD'+ const isNonCloudEdition = deploymentEdition === 'COMMUNITY' || deploymentEdition === 'ENTERPRISE'const successInvitationResults = invitationResults.filter((item): item is MemberInviteSuccessResponse => item.status === 'success',@@ -57,12 +64,14 @@ const InvitedModal = ({ invitationResults, onCancel }: IInvitedModalProps) => {{ ns: 'common' },)}</DialogTitle>- {!IS_CE_EDITION && <div className="mb-5 text-sm text-text-tertiary">{description}</div>}- {(IS_CE_EDITION || !!alreadyMemberInvitationResults.length) && (+ {isCloudEdition && <div className="mb-5 text-sm text-text-tertiary">{description}</div>}+ {(isNonCloudEdition || !!alreadyMemberInvitationResults.length) && (<>- {IS_CE_EDITION && <div className="mb-5 text-sm text-text-tertiary">{description}</div>}+ {isNonCloudEdition && (+ <div className="mb-5 text-sm text-text-tertiary">{description}</div>+ )}<div className="mb-9 flex flex-col gap-2">- {IS_CE_EDITION && !!successInvitationResults.length && (+ {isNonCloudEdition && !!successInvitationResults.length && (<><div className="py-2 text-sm font-medium text-text-primary">{t(($) => $['members.invitationLink'], { ns: 'common' })}@@ -94,7 +103,7 @@ const InvitedModal = ({ invitationResults, onCancel }: IInvitedModalProps) => {</div></>)}- {IS_CE_EDITION && !!failedInvitationResults.length && (+ {isNonCloudEdition && !!failedInvitationResults.length && (<><div className="py-2 text-sm font-medium text-text-primary">{t(($) => $['members.failedInvitationEmails'], { ns: 'common' })}diff --git a/web/app/components/header/account-setting/model-provider-page/__tests__/index.non-cloud.spec.tsx b/web/app/components/header/account-setting/model-provider-page/__tests__/index.non-cloud.spec.tsxindex 5b391937808..52659532eb8 100644--- a/web/app/components/header/account-setting/model-provider-page/__tests__/index.non-cloud.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/__tests__/index.non-cloud.spec.tsx@@ -20,7 +20,6 @@ vi.mock('@/config', async (importOriginal) => {const actual = await importOriginal<typeof import('@/config')>()return {...actual,- IS_CLOUD_EDITION: false,}})diff --git a/web/app/components/header/account-setting/model-provider-page/__tests__/supports-credits.spec.ts b/web/app/components/header/account-setting/model-provider-page/__tests__/supports-credits.spec.tsindex 3497d6bda8d..4bcd627cc08 100644--- a/web/app/components/header/account-setting/model-provider-page/__tests__/supports-credits.spec.ts+++ b/web/app/components/header/account-setting/model-provider-page/__tests__/supports-credits.spec.ts@@ -2,11 +2,6 @@ import type { ModelProvider } from '../declarations'import { CurrentSystemQuotaTypeEnum } from '../declarations'import { providerSupportsCredits } from '../supports-credits'-vi.mock('@/config', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/config')>()- return { ...actual, IS_CLOUD_EDITION: true }-})-const makeProvider = (overrides: Partial<ModelProvider> = {}): ModelProvider =>({provider: 'langgenius/openai/openai',@@ -20,11 +15,15 @@ const makeProvider = (overrides: Partial<ModelProvider> = {}): ModelProvider =>describe('providerSupportsCredits', () => {it('returns true when the provider is system-enabled and listed in trial_models', () => {- expect(providerSupportsCredits(makeProvider(), ['langgenius/openai/openai'])).toBe(true)+ expect(providerSupportsCredits(makeProvider(), ['langgenius/openai/openai'], 'CLOUD')).toBe(+ true,+ )})it('returns false when the provider is not listed in trial_models', () => {- expect(providerSupportsCredits(makeProvider(), ['langgenius/anthropic/anthropic'])).toBe(false)+ expect(+ providerSupportsCredits(makeProvider(), ['langgenius/anthropic/anthropic'], 'CLOUD'),+ ).toBe(false)})it('returns false when system hosting is disabled', () => {@@ -38,11 +37,21 @@ describe('providerSupportsCredits', () => {},}),['langgenius/openai/openai'],+ 'CLOUD',),).toBe(false)})it('returns false for an undefined provider', () => {- expect(providerSupportsCredits(undefined, ['langgenius/openai/openai'])).toBe(false)+ expect(providerSupportsCredits(undefined, ['langgenius/openai/openai'], 'CLOUD')).toBe(false)})++ it.each(['COMMUNITY', 'ENTERPRISE'] as const)(+ 'returns false outside Cloud when deployment edition is %s',+ (deploymentEdition) => {+ expect(+ providerSupportsCredits(makeProvider(), ['langgenius/openai/openai'], deploymentEdition),+ ).toBe(false)+ },+ )})diff --git a/web/app/components/header/account-setting/model-provider-page/model-provider-page-body.tsx b/web/app/components/header/account-setting/model-provider-page/model-provider-page-body.tsxindex 97748322f2e..07b92215971 100644--- a/web/app/components/header/account-setting/model-provider-page/model-provider-page-body.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-provider-page-body.tsx@@ -1,11 +1,12 @@import type { FC } from 'react'import type { ModelProvider } from './declarations'import type { PluginDetail } from '@/app/components/plugins/types'+import { useSuspenseQuery } from '@tanstack/react-query'import { Trans, useTranslation } from 'react-i18next'import { SkeletonContainer, SkeletonRectangle, SkeletonRow } from '@/app/components/base/skeleton'import { PluginSource } from '@/app/components/plugins/types'import { STEP_BY_STEP_TOUR_TARGETS } from '@/app/components/step-by-step-tour/target-registry'-import { IS_CLOUD_EDITION } from '@/config'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import InstallFromMarketplace from './install-from-marketplace'import ProviderAddedCard from './provider-added-card'import QuotaPanel from './provider-added-card/quota-panel'@@ -169,10 +170,14 @@ const ModelProviderPageBody: FC<ModelProviderPageBodyProps> = ({onOpenMarketplace,}) => {const { t } = useTranslation()+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })return (<div className="flex flex-col gap-2">- {IS_CLOUD_EDITION && (+ {deploymentEdition === 'CLOUD' && (<divdata-step-by-step-tour-target={STEP_BY_STEP_TOUR_TARGETS.integrationModelProviderCredits}>diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/popup.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/popup.spec.tsxindex 311daddd960..0ef9b365805 100644--- a/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/popup.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/popup.spec.tsx@@ -123,6 +123,7 @@ const renderPopup = (options.systemFeatures === null? null: {+ deployment_edition: 'CLOUD',enable_marketplace: true,...(options.systemFeatures ?? {}),},@@ -153,11 +154,6 @@ vi.mock('next-themes', () => ({useTheme: () => ({ theme: 'light' }),}))-vi.mock('@/config', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/config')>()- return { ...actual, IS_CLOUD_EDITION: true }-})-const mockInstallMutateAsync = vi.hoisted(() => vi.fn())vi.mock('@/service/use-plugins', () => ({useInstallPackageFromMarketPlace: () => ({ mutateAsync: mockInstallMutateAsync }),diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/popup.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/popup.tsxindex 463af087248..ae4f4d5067f 100644--- a/web/app/components/header/account-setting/model-provider-page/model-selector/popup.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/popup.tsx@@ -20,7 +20,6 @@ import { useIntegrationsSetting } from '@/app/components/header/account-setting/import checkTaskStatus from '@/app/components/plugins/install-plugin/base/check-task-status'import useRefreshPluginList from '@/app/components/plugins/install-plugin/hooks/use-refresh-plugin-list'import useWorkspacePluginInstallPermission from '@/app/components/plugins/install-plugin/hooks/use-workspace-plugin-install-permission'-import { IS_CLOUD_EDITION } from '@/config'import { useProviderContext } from '@/context/provider-context'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { useSearchParams } from '@/next/navigation'@@ -102,6 +101,10 @@ function Popup({...systemFeaturesQueryOptions(),select: (systemFeatures) => systemFeatures.enable_marketplace,})+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })const { plugins: allPlugins, isLoading: isMarketplacePluginsLoading } = useMarketplaceAllPlugins(modelProviders,'',@@ -116,7 +119,7 @@ function Popup({const { isExhausted: isCreditsExhausted } = useTrialCredits()const { data: trialModels = [] } = useQuery(consoleQuery.trialModels.get.queryOptions({- enabled: IS_CLOUD_EDITION,+ enabled: deploymentEdition === 'CLOUD',select: (data) => data.trial_models,}),)@@ -129,18 +132,20 @@ function Popup({return new Set(modelProviders- .filter((provider) => providerSupportsCredits(provider, trialModels))+ .filter((provider) => providerSupportsCredits(provider, trialModels, deploymentEdition)).map((provider) => provider.provider),)- }, [enableMarketplace, isCreditsExhausted, modelProviders, trialModels])+ }, [deploymentEdition, enableMarketplace, isCreditsExhausted, modelProviders, trialModels])const showCreditsExhaustedAlert =enableMarketplace &&isCreditsExhausted &&- modelProviders.some((provider) => providerSupportsCredits(provider, trialModels))+ modelProviders.some((provider) =>+ providerSupportsCredits(provider, trialModels, deploymentEdition),+ )const hasApiKeyFallback = modelProviders.some((provider) => {const isApiKeyActive =provider.custom_configuration?.status === CustomConfigurationStatusEnum.active- return isApiKeyActive && providerSupportsCredits(provider, trialModels)+ return isApiKeyActive && providerSupportsCredits(provider, trialModels, deploymentEdition)})const handleInstallPlugin = useCallback(diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/credential-panel.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/credential-panel.spec.tsxindex 63df6ae6d0c..536959badb3 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/credential-panel.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/credential-panel.spec.tsx@@ -29,11 +29,6 @@ const {mockChangePriorityFn: vi.fn().mockResolvedValue({ result: 'success' }),}))-vi.mock('@/config', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/config')>()- return { ...actual, IS_CLOUD_EDITION: true }-})-vi.mock('@langgenius/dify-ui/toast', () => ({default: { notify: mockToastNotify },toast: {@@ -141,6 +136,7 @@ const createProvider = (overrides: Partial<ModelProvider> = {}): ModelProvider =const renderWithQueryClient = (provider: ModelProvider) => {return renderWithConsoleQuery(<CredentialPanel provider={provider} />, {+ systemFeatures: { deployment_edition: 'CLOUD' },trialModels: ['langgenius/openai/openai'],})}diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/index.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/index.spec.tsxindex 8f91f8a5ac8..2fce814e4f7 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/index.spec.tsx@@ -1,10 +1,10 @@-import type { ReactNode } from 'react'+import type { ReactElement } from 'react'import type { ModelProvider } from '../../declarations'-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { QueryClient } from '@tanstack/react-query'import { act, fireEvent, screen, waitFor } from '@testing-library/react'-import { createStore, Provider as JotaiProvider } from 'jotai'+import { createQueryClientWrapper } from '@/test/console/query-client'+import { seedSystemFeatures } from '@/test/console/query-data'import { render } from '@/test/console/render'-import { seedRegisteredConsoleStateFixture } from '@/test/console/state-fixture'import { useExpandModelProviderList } from '../../atoms'import { ConfigurationMethodEnum } from '../../declarations'import ProviderAddedCard from '../index'@@ -27,6 +27,15 @@ const mockQueryOptions = vi.fn(vi.mock('@/service/client', () => ({consoleQuery: {+ systemFeatures: {+ get: {+ queryKey: () => ['system-features'],+ queryOptions: (options: Record<string, unknown> = {}) => ({+ queryKey: ['system-features'],+ ...options,+ }),+ },+ },workspaces: {current: {modelProviders: {@@ -105,15 +114,10 @@ const createConsoleQueryClient = () =>},})-const renderWithQueryClient = (node: ReactNode) => {+const renderWithQueryClient = (node: ReactElement) => {const queryClient = createConsoleQueryClient()- const store = createStore()- seedRegisteredConsoleStateFixture(store)- return render(- <JotaiProvider store={store}>- <QueryClientProvider client={queryClient}>{node}</QueryClientProvider>- </JotaiProvider>,- )+ seedSystemFeatures(queryClient)+ return render(node, { wrapper: createQueryClientWrapper(queryClient) })}const ExternalExpandControls = () => {diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/model-load-balancing-configs.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/model-load-balancing-configs.spec.tsxindex 1c0c01c6d77..fe20648bebe 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/model-load-balancing-configs.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/model-load-balancing-configs.spec.tsx@@ -5,18 +5,17 @@ import type {ModelLoadBalancingConfig,ModelProvider,} from '../../declarations'-import { act, fireEvent, render, screen } from '@testing-library/react'+import { act, fireEvent, screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { useState } from 'react'import { AddCredentialInLoadBalancing } from '@/app/components/header/account-setting/model-provider-page/model-auth'+import { renderWithConsoleQuery } from '@/test/console/query-data'import { ConfigurationMethodEnum } from '../../declarations'import ModelLoadBalancingConfigs from '../model-load-balancing-configs'let mockModelLoadBalancingEnabled = true--vi.mock('@/config', () => ({- IS_CE_EDITION: false,-}))+const render = (ui: React.ReactElement) =>+ renderWithConsoleQuery(ui, { systemFeatures: { deployment_edition: 'CLOUD' } })vi.mock('@/context/provider-context', () => ({useProviderContextSelector: (diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/use-credential-panel-state.spec.ts b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/use-credential-panel-state.spec.tsindex 90809502cf7..6171fbdc520 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/use-credential-panel-state.spec.ts+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/use-credential-panel-state.spec.ts@@ -21,14 +21,10 @@ vi.mock('../use-trial-credits', () => ({useTrialCredits: () => mockTrialCredits,}))-vi.mock('@/config', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/config')>()- return { ...actual, IS_CLOUD_EDITION: true }-})-const renderPanelHook = (provider: ModelProvider | undefined) => {// oxlint-disable-next-line eslint-react/use-state -- This is a domain hook, not React's useState.return renderHookWithConsoleQuery(() => useCredentialPanelState(provider), {+ systemFeatures: { deployment_edition: 'CLOUD' },trialModels: mockTrialModels,})}diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/index.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/index.tsxindex 7eb36f84cbd..09279b5a971 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/index.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/index.tsx@@ -3,7 +3,7 @@ import type { ModelProvider } from '../declarations'import type { ModelProviderQuotaGetPaid } from '../utils'import type { PluginDetail } from '@/app/components/plugins/types'import { cn } from '@langgenius/dify-ui/cn'-import { useQuery } from '@tanstack/react-query'+import { useQuery, useSuspenseQuery } from '@tanstack/react-query'import { useAtomValue } from 'jotai'import { memo, useCallback } from 'react'import { useTranslation } from 'react-i18next'@@ -11,9 +11,9 @@ import {AddCustomModel,ManageCustomModelCredentials,} from '@/app/components/header/account-setting/model-provider-page/model-auth'-import { IS_CE_EDITION } from '@/config'import { workspacePermissionKeysAtom } from '@/context/permission-state'import { useProviderContextSelector } from '@/context/provider-context'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { useCredentialPermissions } from '@/hooks/use-credential-permissions'import { renderI18nObject } from '@/i18n-config'import { consoleQuery } from '@/service/client'@@ -45,6 +45,10 @@ const ProviderAddedCard: FC<ProviderAddedCardProps> = ({pluginDetail,}) => {const { t } = useTranslation()+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })const language = useLanguage()const refreshModelProviders = useProviderContextSelector((state) => state.refreshModelProviders)const currentProviderName = provider.provider@@ -76,7 +80,7 @@ const ProviderAddedCard: FC<ProviderAddedCardProps> = ({const showModelProvider =systemConfig.enabled &&MODEL_PROVIDER_QUOTA_GET_PAID.includes(currentProviderName as ModelProviderQuotaGetPaid) &&- !IS_CE_EDITION+ deploymentEdition === 'CLOUD'const canConfigureModels = hasPermission(workspacePermissionKeys, 'plugin.model_config')const { canUseCredential, canCreateCredential, canManageCredential } = useCredentialPermissions()const canAccessCredentials = canUseCredential || canCreateCredential || canManageCredentialdiff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/__tests__/dropdown-content.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/__tests__/dropdown-content.spec.tsxindex 94b1730d085..2b60d16a0e7 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/__tests__/dropdown-content.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/__tests__/dropdown-content.spec.tsx@@ -1,7 +1,7 @@import type { ModelProvider } from '../../../declarations'import type { CredentialPanelState } from '../../use-credential-panel-state'import { fireEvent, screen } from '@testing-library/react'-import { render } from '@/test/console/render'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { CustomConfigurationStatusEnum, PreferredProviderTypeEnum } from '../../../declarations'import DropdownContent from '../dropdown-content'diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/credits-exhausted-alert.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/credits-exhausted-alert.tsxindex 55f8aff87e5..eb17feaca04 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/credits-exhausted-alert.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/credits-exhausted-alert.tsx@@ -1,8 +1,9 @@import { Meter, MeterIndicator, MeterLabel, MeterTrack } from '@langgenius/dify-ui/meter'+import { useSuspenseQuery } from '@tanstack/react-query'import { Trans, useTranslation } from 'react-i18next'import { CreditsCoin } from '@/app/components/base/icons/src/vender/line/financeAndECommerce'-import { IS_CLOUD_EDITION } from '@/config'import { useModalContextSelector } from '@/context/modal-context'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { formatNumber } from '@/utils/format'import { useTrialCredits } from '../use-trial-credits'@@ -18,6 +19,10 @@ export default function CreditsExhaustedAlert({totalCredits: totalCreditsOverride,}: CreditsExhaustedAlertProps) {const { t } = useTranslation()+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })const setShowPricingModal = useModalContextSelector((s) => s.setShowPricingModal)const trialCredits = useTrialCredits()const credits = creditsOverride ?? trialCredits.credits@@ -46,15 +51,16 @@ export default function CreditsExhaustedAlert({i18nKey={($) => $[descriptionKey]}ns="common"components={{- upgradeLink: IS_CLOUD_EDITION ? (- <button- type="button"- className="cursor-pointer border-0 bg-transparent p-0 text-left system-xs-medium text-text-accent"- onClick={() => setShowPricingModal()}- />- ) : (- <span />- ),+ upgradeLink:+ deploymentEdition === 'CLOUD' ? (+ <button+ type="button"+ className="cursor-pointer border-0 bg-transparent p-0 text-left system-xs-medium text-text-accent"+ onClick={() => setShowPricingModal()}+ />+ ) : (+ <span />+ ),}}/></div>diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-load-balancing-configs.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-load-balancing-configs.tsxindex 2e1523fce7a..2ac24462f10 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-load-balancing-configs.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-load-balancing-configs.tsx@@ -12,6 +12,7 @@ import { cn } from '@langgenius/dify-ui/cn'import { StatusDot } from '@langgenius/dify-ui/status-dot'import { Switch } from '@langgenius/dify-ui/switch'import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'+import { useSuspenseQuery } from '@tanstack/react-query'import { useCallback, useMemo } from 'react'import { useTranslation } from 'react-i18next'import Badge from '@/app/components/base/badge/index'@@ -20,8 +21,8 @@ import { Infotip } from '@/app/components/base/infotip'import UpgradeBtn from '@/app/components/billing/upgrade-btn'import s from '@/app/components/custom/style.module.css'import { AddCredentialInLoadBalancing } from '@/app/components/header/account-setting/model-provider-page/model-auth'-import { IS_CE_EDITION } from '@/config'import { useProviderContextSelector } from '@/context/provider-context'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { ConfigurationMethodEnum } from '../declarations'import CooldownTimer from './cooldown-timer'@@ -53,6 +54,10 @@ const ModelLoadBalancingConfigs = ({onRemove,}: ModelLoadBalancingConfigsProps) => {const { t } = useTranslation()+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })const providerFormSchemaPredefined =configurationMethod === ConfigurationMethodEnum.predefinedModelconst modelLoadBalancingEnabled = useProviderContextSelector(@@ -308,7 +313,7 @@ const ModelLoadBalancingConfigs = ({)}</div>- {!modelLoadBalancingEnabled && !IS_CE_EDITION && (+ {!modelLoadBalancingEnabled && deploymentEdition === 'CLOUD' && (<GridMask canvasClassName="rounded-xl!"><div className="mt-2 flex h-14 items-center justify-between rounded-xl border-[0.5px] border-components-panel-border px-4 shadow-md"><div className={cn('text-gradient text-sm/tight font-semibold', s.textGradient)}>diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/quota-panel.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/quota-panel.tsxindex c129b2fd463..dd67eca4853 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/quota-panel.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/quota-panel.tsx@@ -5,7 +5,7 @@ import type { ModelProviderQuotaGetPaid } from '@/types/model-provider'import { cn } from '@langgenius/dify-ui/cn'import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'-import { useQuery } from '@tanstack/react-query'+import { useQuery, useSuspenseQuery } from '@tanstack/react-query'import { useBoolean } from 'ahooks'import * as React from 'react'import { useCallback, useEffect, useMemo, useRef, useState } from 'react'@@ -14,7 +14,7 @@ import Loading from '@/app/components/base/loading'import { PluginInstallPermissionProvider } from '@/app/components/plugins/install-plugin/components/plugin-install-permission-provider'import useWorkspacePluginInstallPermission from '@/app/components/plugins/install-plugin/hooks/use-workspace-plugin-install-permission'import InstallFromMarketplace from '@/app/components/plugins/install-plugin/install-from-marketplace'-import { IS_CLOUD_EDITION } from '@/config'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import useTimestamp from '@/hooks/use-timestamp'import { consoleQuery } from '@/service/client'import { formatNumber } from '@/utils/format'@@ -73,11 +73,15 @@ type QuotaPanelProps = {}const QuotaPanel: FC<QuotaPanelProps> = ({ providers }) => {const { t } = useTranslation()+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })const { usedCredits, totalCredits, isExhausted, isLoading, exhaustedAt, nextCreditResetDate } =useTrialCredits()const { data: trialModels = [] } = useQuery(consoleQuery.trialModels.get.queryOptions({- enabled: IS_CLOUD_EDITION,+ enabled: deploymentEdition === 'CLOUD',select: (data) => data.trial_models,}),)diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-credential-panel-state.ts b/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-credential-panel-state.tsindex 75ec31d6fae..8ca1dea75bf 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-credential-panel-state.ts+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-credential-panel-state.ts@@ -1,7 +1,7 @@import type { ModelProvider } from '../declarations'-import { useQuery } from '@tanstack/react-query'+import { useQuery, useSuspenseQuery } from '@tanstack/react-query'import { useCredentialStatus } from '@/app/components/header/account-setting/model-provider-page/model-auth/hooks'-import { IS_CLOUD_EDITION } from '@/config'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { consoleQuery } from '@/service/client'import { PreferredProviderTypeEnum } from '../declarations'import { providerSupportsCredits } from '../supports-credits'@@ -65,19 +65,23 @@ function deriveVariant(}export function useCredentialPanelState(provider: ModelProvider | undefined): CredentialPanelState {+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })const { isExhausted, credits } = useTrialCredits()const { hasCredential, authorized, current_credential_name } = useCredentialStatus(provider)const { data: trialModels = [] } = useQuery(consoleQuery.trialModels.get.queryOptions({- enabled: IS_CLOUD_EDITION,+ enabled: deploymentEdition === 'CLOUD',select: (data) => data.trial_models,}),)const preferredType = provider?.preferred_provider_type- const supportsCredits = providerSupportsCredits(provider, trialModels)+ const supportsCredits = providerSupportsCredits(provider, trialModels, deploymentEdition)const priority: UsagePriority = !supportsCredits? 'apiKeyOnly'diff --git a/web/app/components/header/account-setting/model-provider-page/supports-credits.ts b/web/app/components/header/account-setting/model-provider-page/supports-credits.tsindex d981e98e96c..df76e48dd6e 100644--- a/web/app/components/header/account-setting/model-provider-page/supports-credits.ts+++ b/web/app/components/header/account-setting/model-provider-page/supports-credits.ts@@ -1,13 +1,14 @@+import type { DeploymentEdition } from '@dify/contracts/api/console/system-features/types.gen'import type { ModelProvider } from './declarations'-import { IS_CLOUD_EDITION } from '@/config'type CreditAwareProvider = Pick<ModelProvider, 'provider' | 'system_configuration'>export const providerSupportsCredits = (provider: CreditAwareProvider | undefined,trialModels: readonly string[] | undefined,+ deploymentEdition: DeploymentEdition,): boolean => {- if (!IS_CLOUD_EDITION || !provider?.system_configuration.enabled) return false+ if (deploymentEdition !== 'CLOUD' || !provider?.system_configuration.enabled) return falsereturn !!provider.provider && !!trialModels?.includes(provider.provider)}diff --git a/web/app/components/header/account-setting/workflow-log-archives-page/__tests__/index.spec.tsx b/web/app/components/header/account-setting/workflow-log-archives-page/__tests__/index.spec.tsxindex 9fbae99cb82..99bcf13a709 100644--- a/web/app/components/header/account-setting/workflow-log-archives-page/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/workflow-log-archives-page/__tests__/index.spec.tsx@@ -14,7 +14,6 @@ vi.mock('@/config', async (importOriginal) => {const actual = await importOriginal<typeof import('@/config')>()return {...actual,- IS_CLOUD_EDITION: true,}})@@ -76,6 +75,7 @@ function renderPage() {return renderWithConsoleQuery(<WorkflowLogArchivesPage />, {queryClient,+ systemFeatures: { deployment_edition: 'CLOUD' },})}diff --git a/web/app/components/header/account-setting/workflow-log-archives-page/index.tsx b/web/app/components/header/account-setting/workflow-log-archives-page/index.tsxindex d38ac1d815d..c8cf69a29cf 100644--- a/web/app/components/header/account-setting/workflow-log-archives-page/index.tsx+++ b/web/app/components/header/account-setting/workflow-log-archives-page/index.tsx@@ -9,14 +9,15 @@ import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'import { toast } from '@langgenius/dify-ui/toast'import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'-import { skipToken, useMutation, useQuery } from '@tanstack/react-query'+import { skipToken, useMutation, useQuery, useSuspenseQuery } from '@tanstack/react-query'import { useEffect, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import { SkeletonRectangle } from '@/app/components/base/skeleton'import { Plan } from '@/app/components/billing/type'-import { API_PREFIX, IS_CLOUD_EDITION } from '@/config'+import { API_PREFIX } from '@/config'import { useModalContext } from '@/context/modal-context'import { useProviderContext } from '@/context/provider-context'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { consoleQuery } from '@/service/client'const numberFormatter = new Intl.NumberFormat()@@ -64,10 +65,15 @@ const tableGridClassName = 'grid-cols-[0.66fr_0.78fr_0.78fr_1fr]'export default function WorkflowLogArchivesPage() {const { t } = useTranslation()+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })const { plan, enableBilling } = useProviderContext()const [visibleArchiveMonthCount, setVisibleArchiveMonthCount] = useState(ARCHIVE_MONTH_PAGE_SIZE)const loadMoreRef = useRef<HTMLDivElement | null>(null)- const canViewArchiveContent = IS_CLOUD_EDITION && enableBilling && plan.type !== Plan.sandbox+ const canViewArchiveContent =+ deploymentEdition === 'CLOUD' && enableBilling && plan.type !== Plan.sandboxconst archiveListQuery = useQuery(consoleQuery.workflowRunArchives.get.queryOptions({enabled: canViewArchiveContent,diff --git a/web/app/components/header/license-env/__tests__/index.spec.tsx b/web/app/components/header/license-env/__tests__/index.spec.tsxindex ad3089d5814..a4c5f6ebd47 100644--- a/web/app/components/header/license-env/__tests__/index.spec.tsx+++ b/web/app/components/header/license-env/__tests__/index.spec.tsx@@ -1,9 +1,26 @@import { screen } from '@testing-library/react'import dayjs from 'dayjs'import { LicenseStatus } from '@/features/system-features/constants'-import { renderWithConsoleQuery } from '@/test/console/query-data'+import { consoleQuery } from '@/service/client'+import {+ createConsoleQueryClient,+ renderWithConsoleQuery,+ seedSystemFeaturesLicense,+} from '@/test/console/query-data'import LicenseNav from '../index'+const renderLicenseNav = (license?: Parameters<typeof seedSystemFeaturesLicense>[1]) => {+ const queryClient = createConsoleQueryClient()+ if (license) seedSystemFeaturesLicense(queryClient, license)+ else {+ void queryClient.prefetchQuery({+ queryKey: consoleQuery.systemFeatures.license.get.queryOptions().queryKey,+ queryFn: () => new Promise(() => {}),+ })+ }+ return renderWithConsoleQuery(<LicenseNav />, { queryClient })+}+describe('LicenseNav', () => {beforeEach(() => {vi.clearAllMocks()@@ -16,61 +33,38 @@ describe('LicenseNav', () => {vi.useRealTimers()})- it('should render null when license status is NONE', () => {- const { container } = renderWithConsoleQuery(<LicenseNav />)+ it('should render nothing while license detail is loading', () => {+ const { container } = renderLicenseNav()+ expect(container).toBeEmptyDOMElement()+ })++ it('should render nothing when license status is NONE', () => {+ const { container } = renderLicenseNav({})expect(container).toBeEmptyDOMElement()})it('should render Enterprise badge when license status is ACTIVE', () => {- renderWithConsoleQuery(<LicenseNav />, {- systemFeatures: {- license: {- status: LicenseStatus.ACTIVE,- expired_at: '',- },- },- })+ renderLicenseNav({ status: LicenseStatus.ACTIVE })expect(screen.getByText('Enterprise')).toBeInTheDocument()})it('should render singular expiring message when license expires in 0 days', () => {const expiredAt = dayjs().add(2, 'hours').toISOString()- renderWithConsoleQuery(<LicenseNav />, {- systemFeatures: {- license: {- status: LicenseStatus.EXPIRING,- expired_at: expiredAt,- },- },- })+ renderLicenseNav({ status: LicenseStatus.EXPIRING, expired_at: expiredAt })expect(screen.getByText(/license\.expiring/)).toBeInTheDocument()expect(screen.getByText(/count":0/)).toBeInTheDocument()})it('should render singular expiring message when license expires in 1 day', () => {const tomorrow = dayjs().add(1, 'day').add(1, 'hour').toISOString()- renderWithConsoleQuery(<LicenseNav />, {- systemFeatures: {- license: {- status: LicenseStatus.EXPIRING,- expired_at: tomorrow,- },- },- })+ renderLicenseNav({ status: LicenseStatus.EXPIRING, expired_at: tomorrow })expect(screen.getByText(/license\.expiring/)).toBeInTheDocument()expect(screen.getByText(/count":1/)).toBeInTheDocument()})it('should render plural expiring message when license expires in 5 days', () => {const fiveDaysLater = dayjs().add(5, 'day').add(1, 'hour').toISOString()- renderWithConsoleQuery(<LicenseNav />, {- systemFeatures: {- license: {- status: LicenseStatus.EXPIRING,- expired_at: fiveDaysLater,- },- },- })+ renderLicenseNav({ status: LicenseStatus.EXPIRING, expired_at: fiveDaysLater })expect(screen.getByText(/license\.expiring_plural/)).toBeInTheDocument()expect(screen.getByText(/count":5/)).toBeInTheDocument()})diff --git a/web/app/components/header/license-env/index.tsx b/web/app/components/header/license-env/index.tsxindex d966f72fd57..f6ba602c04c 100644--- a/web/app/components/header/license-env/index.tsx+++ b/web/app/components/header/license-env/index.tsx@@ -1,25 +1,25 @@'use client'-import { RiHourglass2Fill } from '@remixicon/react'-import { useSuspenseQuery } from '@tanstack/react-query'+import { useQuery } from '@tanstack/react-query'import dayjs from 'dayjs'import { useTranslation } from 'react-i18next'-import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { LicenseStatus } from '@/features/system-features/constants'+import { consoleQuery } from '@/service/client'import PremiumBadge from '../../base/premium-badge'-const LicenseNav = () => {+function LicenseNav() {const { t } = useTranslation()- const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())+ const { data: license } = useQuery(consoleQuery.systemFeatures.license.get.queryOptions())- if (systemFeatures.license?.status === LicenseStatus.EXPIRING) {- const expiredAt = systemFeatures.license?.expired_at- const count = dayjs(expiredAt).diff(dayjs(), 'days')+ if (license?.status === LicenseStatus.EXPIRING) {+ const count = dayjs(license.expired_at).diff(dayjs(), 'days')return (<PremiumBadge color="orange" className="select-none">- <RiHourglass2Fill+ <span+ className={+ 'i-ri-hourglass-2-fill flex size-3 items-center pl-0.5 text-components-premium-badge-indigo-text-stop-0'+ }aria-hidden="true"- className="flex size-3 items-center pl-0.5 text-components-premium-badge-indigo-text-stop-0"/>{count <= 1 && (<span className="px-0.5 system-xs-medium">@@ -34,7 +34,7 @@ const LicenseNav = () => {</PremiumBadge>)}- if (systemFeatures.license.status === LicenseStatus.ACTIVE) {+ if (license?.status === LicenseStatus.ACTIVE) {return (<PremiumBadge color="indigo" className="select-none"><span className="px-1 system-xs-medium">Enterprise</span>diff --git a/web/app/components/header/plan-badge/__tests__/index.spec.tsx b/web/app/components/header/plan-badge/__tests__/index.spec.tsxindex 3d1dfaa3f16..a707bf34e96 100644--- a/web/app/components/header/plan-badge/__tests__/index.spec.tsx+++ b/web/app/components/header/plan-badge/__tests__/index.spec.tsx@@ -1,21 +1,14 @@+import type { DeploymentEdition } from '@dify/contracts/api/console/system-features/types.gen'+import type { ReactElement } from 'react'import type { Mock } from 'vitest'-import { fireEvent, render, screen } from '@testing-library/react'+import { fireEvent, screen } from '@testing-library/react'import { vi } from 'vitest'import { createMockProviderContextValue } from '@/__mocks__/provider-context'import { useProviderContext } from '@/context/provider-context'+import { renderWithConsoleQuery } from '@/test/console/query-data'import { Plan } from '../../../billing/type'import { PlanBadge } from '../index'-const mockConfig = vi.hoisted(() => ({- isCloudEdition: true,-}))--vi.mock('@/config', () => ({- get IS_CLOUD_EDITION() {- return mockConfig.isCloudEdition- },-}))-vi.mock('@/context/provider-context', () => ({useProviderContext: vi.fn(),baseProviderContextValue: {},@@ -23,10 +16,13 @@ vi.mock('@/context/provider-context', () => ({describe('PlanBadge', () => {const mockUseProviderContext = useProviderContext as Mock+ let deploymentEdition: DeploymentEdition = 'CLOUD'+ const render = (ui: ReactElement) =>+ renderWithConsoleQuery(ui, { systemFeatures: { deployment_edition: deploymentEdition } })beforeEach(() => {vi.clearAllMocks()- mockConfig.isCloudEdition = true+ deploymentEdition = 'CLOUD'})it('should return null if isFetchedPlan is false', () => {@@ -47,7 +43,7 @@ describe('PlanBadge', () => {})it('should render sandbox badge instead of upgrade badge in self-hosted edition', () => {- mockConfig.isCloudEdition = false+ deploymentEdition = 'COMMUNITY'mockUseProviderContext.mockReturnValue(createMockProviderContextValue({ isFetchedPlan: true }))render(<PlanBadge plan={Plan.sandbox} sandboxAsUpgrade={true} />)diff --git a/web/app/components/header/plan-badge/index.tsx b/web/app/components/header/plan-badge/index.tsxindex fc61be8566a..cee3851e1e8 100644--- a/web/app/components/header/plan-badge/index.tsx+++ b/web/app/components/header/plan-badge/index.tsx@@ -1,8 +1,9 @@import type { ReactNode } from 'react'import { RiGraduationCapFill } from '@remixicon/react'+import { useSuspenseQuery } from '@tanstack/react-query'import { useTranslation } from 'react-i18next'-import { IS_CLOUD_EDITION } from '@/config'import { useProviderContext } from '@/context/provider-context'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { SparklesSoft } from '../../base/icons/src/public/common'import PremiumBadge, { PremiumBadgeButton } from '../../base/premium-badge'import { Plan } from '../../billing/type'@@ -47,11 +48,15 @@ function PlanBadgeShell({}export function PlanBadge({ plan, allowHover, sandboxAsUpgrade = false, onClick }: PlanBadgeProps) {+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })const { isFetchedPlan, isEducationWorkspace } = useProviderContext()const { t } = useTranslation()if (!isFetchedPlan) return null- if (plan === Plan.sandbox && sandboxAsUpgrade && IS_CLOUD_EDITION) {+ if (plan === Plan.sandbox && sandboxAsUpgrade && deploymentEdition === 'CLOUD') {return (<PlanBadgeShell color="blue" allowHover={allowHover} onClick={onClick}><SparklesSoftdiff --git a/web/app/components/integrations/__tests__/page.spec.tsx b/web/app/components/integrations/__tests__/page.spec.tsxindex 129b3263b2d..06b51b257c8 100644--- a/web/app/components/integrations/__tests__/page.spec.tsx+++ b/web/app/components/integrations/__tests__/page.spec.tsx@@ -1,9 +1,29 @@import { screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { STEP_BY_STEP_TOUR_TARGETS } from '@/app/components/step-by-step-tour/target-registry'-import { renderWithNuqs } from '@/test/nuqs-testing'+import { createConsoleQueryWrapper } from '@/test/console/query-data'+import { render } from '@/test/console/render'+import { createNuqsTestWrapper } from '@/test/nuqs-testing'import IntegrationsPage from '../page'+const renderWithNuqs = (+ ui: React.ReactElement,+ options: Parameters<typeof createNuqsTestWrapper>[0] = {},+) => {+ const { wrapper: ConsoleQueryWrapper } = createConsoleQueryWrapper()+ const { wrapper: NuqsWrapper, onUrlUpdate } = createNuqsTestWrapper(options)+ const Wrapper = ({ children }: { children: React.ReactNode }) => (+ <ConsoleQueryWrapper>+ <NuqsWrapper>{children}</NuqsWrapper>+ </ConsoleQueryWrapper>+ )++ return {+ ...render(ui, { wrapper: Wrapper }),+ onUrlUpdate,+ }+}+const { mockRouterPush, mockWindowOpen } = vi.hoisted(() => ({mockRouterPush: vi.fn(),mockWindowOpen: vi.fn(),diff --git a/web/app/components/main-nav/__tests__/index.spec.tsx b/web/app/components/main-nav/__tests__/index.spec.tsxindex c385164cd3a..b15ca8e5806 100644--- a/web/app/components/main-nav/__tests__/index.spec.tsx+++ b/web/app/components/main-nav/__tests__/index.spec.tsx@@ -322,7 +322,6 @@ vi.mock('@/config', async (importOriginal) => {const actual = await importOriginal<typeof import('@/config')>()return {...actual,- IS_CLOUD_EDITION: true,SUPPORT_EMAIL_ADDRESS: '',ZENDESK_WIDGET_KEY: '',}@@ -422,6 +421,7 @@ type MainNavSystemFeatures = Exclude<>const defaultMainNavSystemFeatures: MainNavSystemFeatures = {+ deployment_edition: 'CLOUD',branding: { enabled: false },enable_marketplace: true,enable_step_by_step_tour: true,diff --git a/web/app/components/main-nav/components/__tests__/support-menu.spec.tsx b/web/app/components/main-nav/components/__tests__/support-menu.spec.tsxindex b841f35ef6d..4afbf38f333 100644--- a/web/app/components/main-nav/components/__tests__/support-menu.spec.tsx+++ b/web/app/components/main-nav/components/__tests__/support-menu.spec.tsx@@ -10,13 +10,13 @@ import { Plan } from '@/app/components/billing/type'import { mailToSupport } from '@/app/components/header/utils/util'import { useModalContext } from '@/context/modal-context'import { useProviderContext } from '@/context/provider-context'+import { createConsoleQueryWrapper } from '@/test/console/query-data'import { render } from '@/test/console/render'import SupportMenu from '../support-menu'const { mockConfig, mockOpenZendeskWindow, mockMailToSupport, mockSetShowPricingModal } =vi.hoisted(() => ({mockConfig: {- isCloudEdition: true,supportEmailAddress: '',zendeskWidgetKey: 'zendesk-key',},@@ -43,9 +43,6 @@ vi.mock('@/config', async (importOriginal) => {const actual = await importOriginal<typeof import('@/config')>()return {...actual,- get IS_CLOUD_EDITION() {- return mockConfig.isCloudEdition- },get SUPPORT_EMAIL_ADDRESS() {return mockConfig.supportEmailAddress},@@ -73,9 +70,11 @@ vi.mock('@/context/provider-context', () => ({}))describe('SupportMenu', () => {+ let deploymentEdition: 'COMMUNITY' | 'ENTERPRISE' | 'CLOUD' = 'CLOUD'+beforeEach(() => {vi.clearAllMocks()- mockConfig.isCloudEdition = true+ deploymentEdition = 'CLOUD'mockConfig.supportEmailAddress = ''mockConfig.zendeskWidgetKey = 'zendesk-key'mockConsoleState.current = {@@ -93,6 +92,9 @@ describe('SupportMenu', () => {})const renderSupportMenu = (onContactUsClick = vi.fn()) => {+ const { wrapper } = createConsoleQueryWrapper({+ systemFeatures: { deployment_edition: deploymentEdition },+ })return render(<DropdownMenu open={true} onOpenChange={() => {}}><DropdownMenuTrigger>open</DropdownMenuTrigger>@@ -100,6 +102,7 @@ describe('SupportMenu', () => {<SupportMenu onContactUsClick={onContactUsClick} /></DropdownMenuContent></DropdownMenu>,+ { wrapper },)}@@ -122,7 +125,7 @@ describe('SupportMenu', () => {fireEvent.click(screen.getByRole('menuitem', { name: 'common.userProfile.contactUs' }))- expect(openZendeskWindow).toHaveBeenCalled()+ expect(openZendeskWindow).toHaveBeenCalledWith('CLOUD')expect(onContactUsClick).toHaveBeenCalled()})@@ -183,7 +186,7 @@ describe('SupportMenu', () => {expect(screen.queryByText('billing.upgradeBtn.encourageShort')).not.toBeInTheDocument()fireEvent.click(screen.getByRole('menuitem', { name: 'common.userProfile.contactUs' }))- expect(openZendeskWindow).toHaveBeenCalled()+ expect(openZendeskWindow).toHaveBeenCalledWith('CLOUD')expect(mockSetShowPricingModal).not.toHaveBeenCalled()})@@ -209,7 +212,7 @@ describe('SupportMenu', () => {})it('hides dedicated support channels for non-Cloud sandbox plan without support email', () => {- mockConfig.isCloudEdition = false+ deploymentEdition = 'COMMUNITY';(useProviderContext as Mock).mockReturnValue({enableBilling: true,plan: { type: Plan.sandbox },diff --git a/web/app/components/main-nav/components/__tests__/workspace-card.spec.tsx b/web/app/components/main-nav/components/__tests__/workspace-card.spec.tsxindex 0bcee2f37bc..2beb8ae09f0 100644--- a/web/app/components/main-nav/components/__tests__/workspace-card.spec.tsx+++ b/web/app/components/main-nav/components/__tests__/workspace-card.spec.tsx@@ -8,36 +8,26 @@ import { useModalContext } from '@/context/modal-context'import { useProviderContext } from '@/context/provider-context'import { LicenseStatus } from '@/features/system-features/constants'import { consoleQuery } from '@/service/client'-import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'+import {+ createConsoleQueryClient,+ renderWithConsoleQuery,+ seedSystemFeaturesLicense,+} from '@/test/console/query-data'import { WorkspaceCard } from '../workspace-card'-const {- mockSwitchWorkspace,- mockIsCloudEdition,- mockCurrentWorkspaceQueryKey,- mockWorkspacesQueryKey,-} = vi.hoisted(() => ({- mockSwitchWorkspace: vi.fn(),- mockIsCloudEdition: { value: false },- mockCurrentWorkspaceQueryKey: ['console', 'workspaces', 'current', 'post'] as const,- mockWorkspacesQueryKey: ['console', 'workspaces', 'get'] as const,-}))+const { mockSwitchWorkspace, mockCurrentWorkspaceQueryKey, mockWorkspacesQueryKey } = vi.hoisted(+ () => ({+ mockSwitchWorkspace: vi.fn(),+ mockCurrentWorkspaceQueryKey: ['console', 'workspaces', 'current', 'post'] as const,+ mockWorkspacesQueryKey: ['console', 'workspaces', 'get'] as const,+ }),+)const mockConsoleState = vi.hoisted(() => ({current: {workspacePermissionKeys: [] as string[],},}))-vi.mock('@/config', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/config')>()- return {- ...actual,- get IS_CLOUD_EDITION() {- return mockIsCloudEdition.value- },- }-})-vi.mock('@/context/provider-context', () => ({useProviderContext: vi.fn(),}))@@ -127,15 +117,17 @@ const mockCurrentWorkspaceQuery = (type RenderWorkspaceCardOptions = Parameters<typeof renderWithConsoleQuery>[1] & {seedWorkspaces?: boolean+ systemFeaturesLicense?: Parameters<typeof seedSystemFeaturesLicense>[1]}const renderWorkspaceCard = (options?: RenderWorkspaceCardOptions) => {- const { seedWorkspaces = true, ...renderOptions } = options ?? {}+ const { seedWorkspaces = true, systemFeaturesLicense, ...renderOptions } = options ?? {}const queryClient = createConsoleQueryClient()if (mockCurrentWorkspace)queryClient.setQueryData(consoleQuery.workspaces.current.post.queryKey(), mockCurrentWorkspace)if (seedWorkspaces)queryClient.setQueryData(consoleQuery.workspaces.get.queryKey(), { workspaces: mockWorkspaces })+ if (systemFeaturesLicense) seedSystemFeaturesLicense(queryClient, systemFeaturesLicense)return renderWithConsoleQuery(<WorkspaceCard />, {...renderOptions,@@ -153,7 +145,6 @@ const mockWorkspacePermissionKeys = (workspacePermissionKeys: string[]) => {describe('WorkspaceCard', () => {beforeEach(() => {vi.clearAllMocks()- mockIsCloudEdition.value = falsemockWorkspaces = [{id: 'workspace-1',@@ -201,9 +192,7 @@ describe('WorkspaceCard', () => {})it('links workspace credits to model provider settings in cloud edition', () => {- mockIsCloudEdition.value = true-- renderWorkspaceCard()+ renderWorkspaceCard({ systemFeatures: { deployment_edition: 'CLOUD' } })expect(screen.getByRole('link', { name: /common\.mainNav\.workspace\.credits/ }),@@ -231,7 +220,6 @@ describe('WorkspaceCard', () => {})it('uses the workspaces query current item for billing plan UI', () => {- mockIsCloudEdition.value = truemockCurrentWorkspaceQuery({...currentWorkspaceValue,plan: Plan.team,@@ -244,7 +232,7 @@ describe('WorkspaceCard', () => {plan: { type: Plan.team },} as ProviderContextState)- renderWorkspaceCard()+ renderWorkspaceCard({ systemFeatures: { deployment_edition: 'CLOUD' } })expect(screen.getByText(Plan.sandbox)).toBeInTheDocument()expect(screen.getByText('billing.upgradeBtn.encourageShort')).toBeInTheDocument()@@ -253,7 +241,6 @@ describe('WorkspaceCard', () => {})it('uses the original paid plan badge for paid workspaces', () => {- mockIsCloudEdition.value = truemockWorkspaces = [{id: 'workspace-1',@@ -272,14 +259,14 @@ describe('WorkspaceCard', () => {plan: { type: Plan.team },} as ProviderContextState)- renderWorkspaceCard()+ renderWorkspaceCard({ systemFeatures: { deployment_edition: 'CLOUD' } })expect(screen.getByText(Plan.team)).toBeInTheDocument()})- it('shows the license status instead of a billing plan when billing is disabled', () => {+ it('shows the Enterprise license status independently of the Cloud billing state', () => {vi.mocked(useProviderContext).mockReturnValue({- enableBilling: false,+ enableBilling: true,isEducationAccount: false,isEducationWorkspace: false,isFetchedPlan: false,@@ -288,10 +275,10 @@ describe('WorkspaceCard', () => {renderWorkspaceCard({systemFeatures: {- license: {- status: LicenseStatus.ACTIVE,- expired_at: '',- },+ deployment_edition: 'ENTERPRISE',+ },+ systemFeaturesLicense: {+ status: LicenseStatus.ACTIVE,},})diff --git a/web/app/components/main-nav/components/help-menu.tsx b/web/app/components/main-nav/components/help-menu.tsxindex 227a11a3c1d..992f302219f 100644--- a/web/app/components/main-nav/components/help-menu.tsx+++ b/web/app/components/main-nav/components/help-menu.tsx@@ -37,7 +37,6 @@ import {stepByStepTourStateUpdatingAtom,} from '@/app/components/step-by-step-tour/state'import { useSetStepByStepTourShellMode } from '@/app/components/step-by-step-tour/storage'-import { IS_CLOUD_EDITION } from '@/config'import { useDocLink } from '@/context/i18n'import { langGeniusVersionInfoAtom } from '@/context/version-state'import {@@ -199,7 +198,7 @@ const HelpMenu = ({ triggerIcon = defaultTriggerIcon, triggerClassName }: HelpMe<MenuSwitchIndicator checked={!learnDifyHidden} /></DropdownMenuCheckboxItem>)}- {IS_CLOUD_EDITION && shouldShowStepByStepTourSwitch && (+ {systemFeatures.deployment_edition === 'CLOUD' && shouldShowStepByStepTourSwitch && (<DropdownMenuCheckboxItemchecked={stepByStepTourEnabled}closeOnClick={false}@@ -217,7 +216,9 @@ const HelpMenu = ({ triggerIcon = defaultTriggerIcon, triggerClassName }: HelpMe<MenuSwitchIndicator checked={stepByStepTourEnabled} /></DropdownMenuCheckboxItem>)}- {IS_CLOUD_EDITION && isCurrentWorkspaceOwner && <Compliance />}+ {systemFeatures.deployment_edition === 'CLOUD' && isCurrentWorkspaceOwner && (+ <Compliance />+ )}</DropdownMenuGroup><DropdownMenuSeparator className="my-0!" /><DropdownMenuGroup className="p-1">diff --git a/web/app/components/main-nav/components/support-menu.tsx b/web/app/components/main-nav/components/support-menu.tsxindex 25dfada4c8a..5438db7c6c8 100644--- a/web/app/components/main-nav/components/support-menu.tsx+++ b/web/app/components/main-nav/components/support-menu.tsx@@ -1,4 +1,5 @@import { DropdownMenuItem, DropdownMenuLinkItem } from '@langgenius/dify-ui/dropdown-menu'+import { useSuspenseQuery } from '@tanstack/react-query'import { useAtomValue } from 'jotai'import { useTranslation } from 'react-i18next'import { openZendeskWindow } from '@/app/components/base/zendesk/utils'@@ -8,11 +9,12 @@ import {MenuItemContent,} from '@/app/components/header/account-dropdown/menu-item-content'import { mailToSupport } from '@/app/components/header/utils/util'-import { IS_CLOUD_EDITION, SUPPORT_EMAIL_ADDRESS, ZENDESK_WIDGET_KEY } from '@/config'+import { SUPPORT_EMAIL_ADDRESS, ZENDESK_WIDGET_KEY } from '@/config'import { userProfileAtom } from '@/context/account-state'import { useModalContext } from '@/context/modal-context'import { useProviderContext } from '@/context/provider-context'import { langGeniusVersionInfoAtom } from '@/context/version-state'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'type SupportMenuProps = {onContactUsClick?: () => void@@ -20,14 +22,21 @@ type SupportMenuProps = {export default function SupportMenu({ onContactUsClick }: SupportMenuProps) {const { t } = useTranslation()+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })const { enableBilling, plan } = useProviderContext()const userProfile = useAtomValue(userProfileAtom)const langGeniusVersionInfo = useAtomValue(langGeniusVersionInfoAtom)const { setShowPricingModal } = useModalContext()const hasDedicatedChannel = plan.type !== Plan.sandbox || Boolean(SUPPORT_EMAIL_ADDRESS.trim())const shouldShowUpgradeContact =- IS_CLOUD_EDITION && enableBilling && plan.type === Plan.sandbox && !hasDedicatedChannel- const hasZendeskWidget = Boolean(ZENDESK_WIDGET_KEY.trim())+ deploymentEdition === 'CLOUD' &&+ enableBilling &&+ plan.type === Plan.sandbox &&+ !hasDedicatedChannel+ const hasZendeskWidget = deploymentEdition === 'CLOUD' && Boolean(ZENDESK_WIDGET_KEY.trim())return (<>@@ -62,7 +71,7 @@ export default function SupportMenu({ onContactUsClick }: SupportMenuProps) {<DropdownMenuItemclassName="mx-0 h-8 gap-1 px-3 py-1"onClick={() => {- openZendeskWindow()+ openZendeskWindow(deploymentEdition)onContactUsClick?.()}}>diff --git a/web/app/components/main-nav/components/workspace-card.tsx b/web/app/components/main-nav/components/workspace-card.tsxindex 1793ff5ef09..fe510a89de5 100644--- a/web/app/components/main-nav/components/workspace-card.tsx+++ b/web/app/components/main-nav/components/workspace-card.tsx@@ -4,7 +4,7 @@ import type { ReactNode } from 'react'import { cn } from '@langgenius/dify-ui/cn'import { Popover, PopoverContent, PopoverTitle, PopoverTrigger } from '@langgenius/dify-ui/popover'import { toast } from '@langgenius/dify-ui/toast'-import { useMutation, useQuery } from '@tanstack/react-query'+import { useMutation, useQuery, useSuspenseQuery } from '@tanstack/react-query'import { useAtomValue } from 'jotai'import { useState } from 'react'import { useTranslation } from 'react-i18next'@@ -13,10 +13,10 @@ import { Plan } from '@/app/components/billing/type'import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'import LicenseNav from '@/app/components/header/license-env'import { buildIntegrationPath } from '@/app/components/integrations/routes'-import { IS_CLOUD_EDITION } from '@/config'import { useModalContext } from '@/context/modal-context'import { workspacePermissionKeysAtom } from '@/context/permission-state'import { useProviderContext } from '@/context/provider-context'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import Link from '@/next/link'import { consoleQuery } from '@/service/client'import { hasPermission } from '@/utils/permission'@@ -236,6 +236,10 @@ const selectCurrentWorkspaceCardData = (workspace: {export function WorkspaceCard() {const { t } = useTranslation()+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })const currentWorkspaceQuery = useQuery(consoleQuery.workspaces.current.post.queryOptions({select: selectCurrentWorkspaceCardData,@@ -250,7 +254,7 @@ export function WorkspaceCard() {const { enableBilling } = useProviderContext()const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)const { setShowPricingModal, setShowAccountSettingModal } = useModalContext()- const showCloudBilling = IS_CLOUD_EDITION && enableBilling+ const showCloudBilling = deploymentEdition === 'CLOUD' && enableBillingconst [open, setOpen] = useState(false)if (@@ -278,8 +282,12 @@ export function WorkspaceCard() {{ ns: 'billing' },)const showInviteMembers = hasPermission(workspacePermissionKeys, 'workspace.member.manage')- const renderWorkspaceStatus = () =>- enableBilling ? <WorkspacePlanBadge plan={workspacePlan} /> : <LicenseNav />+ const renderWorkspaceStatus = () => {+ if (deploymentEdition === 'CLOUD')+ return enableBilling ? <WorkspacePlanBadge plan={workspacePlan} /> : null+ if (deploymentEdition === 'ENTERPRISE') return <LicenseNav />+ return null+ }const handleSwitchWorkspace = async (tenant_id: string) => {try {diff --git a/web/app/components/plugins/install-plugin/hooks/__tests__/use-install-plugin-limit.spec.ts b/web/app/components/plugins/install-plugin/hooks/__tests__/use-install-plugin-limit.spec.tsindex 32fe33f94f4..c1c5418578b 100644--- a/web/app/components/plugins/install-plugin/hooks/__tests__/use-install-plugin-limit.spec.ts+++ b/web/app/components/plugins/install-plugin/hooks/__tests__/use-install-plugin-limit.spec.ts@@ -138,19 +138,4 @@ describe('usePluginInstallLimit', () => {expect(result.current.canInstall).toBe(true)})-- it('should return a loading install limit state while system features are pending', async () => {- const { default: usePluginInstallLimit } = await import('../use-install-plugin-limit')- const plugin = {- from: 'marketplace' as const,- verification: { authorized_category: 'langgenius' },- }-- const { result } = renderHook(() => usePluginInstallLimit(plugin as never), {- systemFeatures: null,- })-- expect(result.current.canInstall).toBe(false)- expect(result.current.isLoading).toBe(true)- })})diff --git a/web/app/components/plugins/install-plugin/hooks/use-install-plugin-limit.tsx b/web/app/components/plugins/install-plugin/hooks/use-install-plugin-limit.tsxindex 5121d0601aa..933f065d80e 100644--- a/web/app/components/plugins/install-plugin/hooks/use-install-plugin-limit.tsx+++ b/web/app/components/plugins/install-plugin/hooks/use-install-plugin-limit.tsx@@ -1,6 +1,6 @@import type { GetSystemFeaturesResponse } from '@dify/contracts/api/console/system-features/types.gen'import type { Plugin, PluginManifestInMarket } from '../../types'-import { useQuery } from '@tanstack/react-query'+import { useSuspenseQuery } from '@tanstack/react-query'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { InstallationScope } from '@/features/system-features/constants'@@ -9,10 +9,12 @@ type PluginProps = (Plugin | PluginManifestInMarket) & {}type PluginInstallLimitResult = {canInstall: boolean- isLoading: boolean}-export function pluginInstallLimit(plugin: PluginProps, systemFeatures: GetSystemFeaturesResponse) {+export function pluginInstallLimit(+ plugin: PluginProps,+ systemFeatures: Pick<GetSystemFeaturesResponse, 'plugin_installation_permission'>,+) {if (systemFeatures.plugin_installation_permission.restrict_to_marketplace_only) {if (plugin.from === 'github' || plugin.from === 'package') return { canInstall: false }}@@ -61,16 +63,7 @@ export function pluginInstallLimit(plugin: PluginProps, systemFeatures: GetSyste}export default function usePluginInstallLimit(plugin: PluginProps): PluginInstallLimitResult {- const { data: systemFeatures, isPending } = useQuery(systemFeaturesQueryOptions())- if (!systemFeatures) {- return {- canInstall: false,- isLoading: isPending,- }- }+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())- return {- ...pluginInstallLimit(plugin, systemFeatures),- isLoading: false,- }+ return pluginInstallLimit(plugin, systemFeatures)}diff --git a/web/app/components/plugins/install-plugin/install-from-marketplace/steps/install.tsx b/web/app/components/plugins/install-plugin/install-from-marketplace/steps/install.tsxindex 2d72cfb7d76..986e9179f87 100644--- a/web/app/components/plugins/install-plugin/install-from-marketplace/steps/install.tsx+++ b/web/app/components/plugins/install-plugin/install-from-marketplace/steps/install.tsx@@ -136,7 +136,7 @@ const Installed: FC<Props> = ({)}, [langGeniusVersionInfo.current_version, pluginDeclaration])- const { canInstall, isLoading: isInstallLimitLoading } = useInstallPluginLimit({+ const { canInstall } = useInstallPluginLimit({...payload,from: 'marketplace',})@@ -167,7 +167,7 @@ const Installed: FC<Props> = ({/>)}- limitedInstall={!isInstallLimitLoading && !canInstall}+ limitedInstall={!canInstall}/></div></div>@@ -181,7 +181,7 @@ const Installed: FC<Props> = ({<Buttonvariant="primary"className="flex min-w-[72px] space-x-0.5"- disabled={isInstalling || isLoading || isInstallLimitLoading || !canInstall}+ disabled={isInstalling || isLoading || !canInstall}onClick={handleInstall}>{isInstalling && <RiLoader2Line className="size-4 animate-spin-slow" />}diff --git a/web/app/components/plugins/marketplace/__tests__/hydration-server.spec.tsx b/web/app/components/plugins/marketplace/__tests__/hydration-server.spec.tsxindex ad1e208a2ff..4e8c34004bb 100644--- a/web/app/components/plugins/marketplace/__tests__/hydration-server.spec.tsx+++ b/web/app/components/plugins/marketplace/__tests__/hydration-server.spec.tsx@@ -1,3 +1,5 @@+import type { DehydratedState } from '@tanstack/react-query'+import type { ReactElement } from 'react'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { render } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'@@ -28,16 +30,21 @@ vi.mock('@/service/client', () => ({},}))-let serverQueryClient: QueryClient+let rootQueryClient: QueryClient-vi.mock('@/context/query-client-server', () => ({- getQueryClientServer: () => serverQueryClient,-}))+vi.mock('@/context/query-client-server', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/context/query-client-server')>()++ return {+ ...actual,+ getQueryClientServer: () => rootQueryClient,+ }+})describe('HydrateQueryClient', () => {beforeEach(() => {vi.clearAllMocks()- serverQueryClient = new QueryClient({+ rootQueryClient = new QueryClient({defaultOptions: { queries: { retry: false, gcTime: 0 } },})mockCollections.mockResolvedValue({@@ -87,6 +94,26 @@ describe('HydrateQueryClient', () => {expect(mockCollections).toHaveBeenCalled()})+ it('should dehydrate only Marketplace-owned queries', async () => {+ rootQueryClient.setQueryData(['console', 'system-features'], {+ deployment_edition: 'CLOUD',+ })+ const { HydrateQueryClient } = await import('../hydration-server')++ const element = await HydrateQueryClient({+ searchParams: Promise.resolve({ category: 'all' }),+ children: <div>Child</div>,+ })+ const state = (element as ReactElement<{ state: DehydratedState }>).props.state++ expect(state.queries).toHaveLength(1)+ expect(state.queries[0]?.queryKey).toEqual([+ 'marketplace',+ 'collections',+ { input: { query: {} } },+ ])+ })+it('should prefetch when category has collections (tool)', async () => {const { HydrateQueryClient } = await import('../hydration-server')diff --git a/web/app/components/plugins/marketplace/hydration-server.tsx b/web/app/components/plugins/marketplace/hydration-server.tsxindex 8592a1f4ac9..5412f97cb6c 100644--- a/web/app/components/plugins/marketplace/hydration-server.tsx+++ b/web/app/components/plugins/marketplace/hydration-server.tsx@@ -2,7 +2,7 @@ import type { SearchParams } from 'nuqs/server'import type { MarketplaceSearchParams } from './search-params'import { dehydrate, HydrationBoundary } from '@tanstack/react-query'import { createLoader } from 'nuqs/server'-import { getQueryClientServer } from '@/context/query-client-server'+import { makeQueryClient } from '@/context/query-client-server'import { marketplaceQuery } from '@/service/client'import { PLUGIN_CATEGORY_WITH_COLLECTIONS } from './constants'import { marketplaceSearchParamsParsers } from './search-params'@@ -21,7 +21,7 @@ async function getDehydratedState(searchParams?: Promise<SearchParams>) {return}- const queryClient = getQueryClientServer()+ const queryClient = makeQueryClient()await queryClient.prefetchQuery({queryKey: marketplaceQuery.collections.queryKey({diff --git a/web/app/components/plugins/marketplace/index.tsx b/web/app/components/plugins/marketplace/index.tsxindex 5714dff3588..d3dd6946b0a 100644--- a/web/app/components/plugins/marketplace/index.tsx+++ b/web/app/components/plugins/marketplace/index.tsx@@ -1,6 +1,6 @@import type { SearchParams } from 'nuqs'import { PluginInstallPermissionProviderGuard } from '@/app/components/plugins/install-plugin/components/plugin-install-permission-provider'-import { TanstackQueryInitializer } from '@/context/query-client'+import { TanStackQueryProvider } from '@/context/query-client'import Description from './description'import { HydrateQueryClient } from './hydration-server'import ListWrapper from './list/list-wrapper'@@ -27,7 +27,7 @@ const Marketplace = async ({searchParams,}: MarketplaceProps) => {return (- <TanstackQueryInitializer>+ <TanStackQueryProvider><HydrateQueryClient searchParams={searchParams}><PluginInstallPermissionProviderGuard canInstallPlugin={showInstallButton}><Description@@ -43,7 +43,7 @@ const Marketplace = async ({/></PluginInstallPermissionProviderGuard></HydrateQueryClient>- </TanstackQueryInitializer>+ </TanStackQueryProvider>)}diff --git a/web/app/components/plugins/plugin-detail-panel/__tests__/endpoint-list.spec.tsx b/web/app/components/plugins/plugin-detail-panel/__tests__/endpoint-list.spec.tsxindex ffe4a228dfd..36b4855672d 100644--- a/web/app/components/plugins/plugin-detail-panel/__tests__/endpoint-list.spec.tsx+++ b/web/app/components/plugins/plugin-detail-panel/__tests__/endpoint-list.spec.tsx@@ -1,6 +1,7 @@import type { PluginDetail } from '@/app/components/plugins/types'-import { fireEvent, render, screen, waitFor } from '@testing-library/react'+import { fireEvent, screen, waitFor } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import EndpointList from '../endpoint-list'vi.mock('@langgenius/dify-ui/cn', () => ({diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsxindex b943abaa3d3..521b3bf1533 100644--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsx@@ -3,15 +3,15 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { act, fireEvent, screen, waitFor } from '@testing-library/react'import * as React from 'react'import { beforeEach, describe, expect, it, vi } from 'vitest'+import { seedSystemFeatures } from '@/test/console/query-data'import { render } from '@/test/console/render'import Publisher from '../index'import { Popup } from '../popup'-vi.mock('@/config', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/config')>()+vi.mock('@/context/system-features-state', async () => {+ const { atom } = await import('jotai')return {- ...actual,- IS_CLOUD_EDITION: true,+ deploymentEditionAtom: atom('CLOUD'),}})@@ -312,6 +312,7 @@ const createQueryClient = () =>const renderWithQueryClient = (ui: React.ReactElement) => {const queryClient = createQueryClient()+ seedSystemFeatures(queryClient, { deployment_edition: 'CLOUD' })return render(<QueryClientProvider client={queryClient}>{ui}</QueryClientProvider>)}diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/popup.spec.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/popup.spec.tsxindex 37ce084d08e..946230c46ce 100644--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/popup.spec.tsx+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/popup.spec.tsx@@ -1,8 +1,16 @@import { fireEvent, screen } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { render } from '@/test/console/render'+import { createConsoleQueryWrapper } from '@/test/console/query-data'+import { render as renderWithConsoleState } from '@/test/console/render'import { Popup } from '../popup'+const render = (ui: React.ReactElement) => {+ const { wrapper } = createConsoleQueryWrapper({+ systemFeatures: { deployment_edition: 'CLOUD' },+ })+ return renderWithConsoleState(ui, { wrapper })+}+vi.mock('@langgenius/dify-ui/alert-dialog', () => ({AlertDialog: ({children,@@ -160,8 +168,8 @@ vi.mock('@/app/components/base/premium-badge', () => ({),}))-vi.mock('@/config', () => ({- IS_CLOUD_EDITION: true,+vi.mock('@/config', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/config')>()),MARKETPLACE_API_PREFIX: '/marketplace/api',}))diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsxindex 2bd364da9b3..32039faf5e9 100644--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx@@ -14,6 +14,7 @@ import { Kbd, KbdGroup } from '@langgenius/dify-ui/kbd'import { toast } from '@langgenius/dify-ui/toast'import { RiArrowRightUpLine, RiPlayCircleLine, RiTerminalBoxLine } from '@remixicon/react'import { formatForDisplay, useHotkey } from '@tanstack/react-hotkeys'+import { useSuspenseQuery } from '@tanstack/react-query'import { useBoolean } from 'ahooks'import { useAtomValue } from 'jotai'import { useCallback, useState } from 'react'@@ -24,7 +25,6 @@ import { SparklesSoft } from '@/app/components/base/icons/src/public/common'import PremiumBadge from '@/app/components/base/premium-badge'import { useChecklistBeforePublish } from '@/app/components/workflow/hooks'import { useStore, useWorkflowStore } from '@/app/components/workflow/store'-import { IS_CLOUD_EDITION } from '@/config'import { userProfileIdAtom } from '@/context/account-state'import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'import { useModalContextSelector } from '@/context/modal-context'@@ -33,6 +33,7 @@ import {workspacePermissionKeysLoadingAtom,} from '@/context/permission-state'import { useProviderContextSelector } from '@/context/provider-context'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { useDatasetApiAccessUrl } from '@/hooks/use-api-access-url'import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'import Link from '@/next/link'@@ -62,6 +63,10 @@ export function Popup({onShowPublishAsKnowledgePipelineModal,}: PopupProps) {const { t } = useTranslation()+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })const { datasetId } = useParams()const { push } = useRouter()const publishedAt = useStore((s) => s.publishedAt)@@ -195,12 +200,13 @@ export function Popup({const handleClickPublishAsKnowledgePipeline = useCallback(() => {onRequestClose?.()if (!isAllowPublishAsCustomKnowledgePipelineTemplate) {- if (IS_CLOUD_EDITION) setShowPricingModal()+ if (deploymentEdition === 'CLOUD') setShowPricingModal()} else {onShowPublishAsKnowledgePipelineModal?.()}}, [isAllowPublishAsCustomKnowledgePipelineTemplate,+ deploymentEdition,onRequestClose,onShowPublishAsKnowledgePipelineModal,setShowPricingModal,@@ -294,7 +300,7 @@ export function Popup({>{t(($) => $['common.publishAs'], { ns: 'pipeline' })}</span>- {IS_CLOUD_EDITION && !isAllowPublishAsCustomKnowledgePipelineTemplate && (+ {deploymentEdition === 'CLOUD' && !isAllowPublishAsCustomKnowledgePipelineTemplate && (<PremiumBadge className="shrink-0 select-none" size="s" color="indigo"><SparklesSoftaria-hidden="true"diff --git a/web/app/components/rag-pipeline/hooks/__tests__/index.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/index.spec.tsindex a6a144296a7..1828399211c 100644--- a/web/app/components/rag-pipeline/hooks/__tests__/index.spec.ts+++ b/web/app/components/rag-pipeline/hooks/__tests__/index.spec.ts@@ -1,8 +1,8 @@import type { RAGPipelineVariables, VAR_TYPE_MAP } from '@/models/pipeline'-import { renderHook } from '@testing-library/react'import { act } from 'react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { BlockEnum } from '@/app/components/workflow/types'+import { renderHookWithConsoleQuery as renderHook } from '@/test/console/query-data'import { Resolution, TransferMethod } from '@/types/app'import { FlowType } from '@/types/common'import {diff --git a/web/app/components/share/text-generation/__tests__/text-generation-sidebar.spec.tsx b/web/app/components/share/text-generation/__tests__/text-generation-sidebar.spec.tsxindex a40f6c431af..4781a4b6f5e 100644--- a/web/app/components/share/text-generation/__tests__/text-generation-sidebar.spec.tsx+++ b/web/app/components/share/text-generation/__tests__/text-generation-sidebar.spec.tsx@@ -3,8 +3,8 @@ import type { PromptConfig, SavedMessage } from '@/models/debug'import type { SiteInfo } from '@/models/share'import type { VisionSettings } from '@/types/app'import { fireEvent, render, screen } from '@testing-library/react'-import { defaultSystemFeatures } from '@/features/system-features/config'import { AccessMode } from '@/models/access-control'+import { createSystemFeaturesFixture } from '@/test/console/system-features'import { Resolution, TransferMethod } from '@/types/app'import TextGenerationSidebar from '../text-generation-sidebar'@@ -92,7 +92,7 @@ const baseProps: ComponentProps<typeof TextGenerationSidebar> = {runControl: null,savedMessages,siteInfo,- systemFeatures: defaultSystemFeatures,+ systemFeatures: createSystemFeaturesFixture(),textToSpeechConfig: { enabled: true },visionConfig,}@@ -164,14 +164,12 @@ describe('TextGenerationSidebar', () => {it('should prefer workspace branding and hide powered-by block when branding is removed', () => {const { rerender } = renderSidebar({- systemFeatures: {- ...defaultSystemFeatures,+ systemFeatures: createSystemFeaturesFixture({branding: {- ...defaultSystemFeatures.branding,enabled: true,workspace_logo: 'https://example.com/workspace-logo.png',},- },+ }),})const brandingLogo = screen.getByRole('img', { name: 'logo' })diff --git a/web/app/components/step-by-step-tour/__tests__/mount.spec.tsx b/web/app/components/step-by-step-tour/__tests__/mount.spec.tsxindex 2f3c79cccef..e099f13a36f 100644--- a/web/app/components/step-by-step-tour/__tests__/mount.spec.tsx+++ b/web/app/components/step-by-step-tour/__tests__/mount.spec.tsx@@ -12,8 +12,8 @@ import { createStore, Provider as JotaiProvider } from 'jotai'import { queryClientAtom } from 'jotai-tanstack-query'import { Plan } from '@/app/components/billing/type'import { systemFeaturesQueryOptions } from '@/features/system-features/client'-import { defaultSystemFeatures } from '@/features/system-features/config'import { seedRegisteredConsoleStateFixture } from '@/test/console/state-fixture'+import { createSystemFeaturesFixture } from '@/test/console/system-features'import { createTestQueryClient } from '@/test/query-client'import StepByStepTourMount from '../mount'import { stepByStepTourSessionAtom } from '../state'@@ -199,14 +199,6 @@ const setViewportSize = ({ height, width }: { height: number; width: number }) =})}-vi.mock('@/config', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/config')>()- return {- ...actual,- IS_CLOUD_EDITION: true,- }-})-vi.mock('@/context/i18n', () => ({useDocLink: () => (path: string) => `https://docs.dify.ai${path}`,}))@@ -228,6 +220,10 @@ vi.mock('@/service/client', () => ({systemFeatures: {get: {queryKey: () => ['console', 'system-features'],+ queryOptions: (options: Record<string, unknown> = {}) => ({+ queryKey: ['console', 'system-features'],+ ...options,+ }),},},onboarding: {@@ -487,11 +483,14 @@ const setStepByStepTourTestState = (state: Partial<StepByStepTourFixtureState>)const renderStepByStepTourMount = () => {const queryClient = createTestQueryClient()queryClient.setQueryData(mockStepByStepTour.stateQueryKey, mockStepByStepTour.state)- queryClient.setQueryData(systemFeaturesQueryOptions().queryKey, {- ...defaultSystemFeatures,- enable_learn_app: mockEnableLearnApp.value,- enable_step_by_step_tour: mockEnableStepByStepTour.value,- })+ queryClient.setQueryData(+ systemFeaturesQueryOptions().queryKey,+ createSystemFeaturesFixture({+ deployment_edition: 'CLOUD',+ enable_learn_app: mockEnableLearnApp.value,+ enable_step_by_step_tour: mockEnableStepByStepTour.value,+ }),+ )const jotaiStore = createStore()seedRegisteredConsoleStateFixture(jotaiStore)jotaiStore.set(queryClientAtom, queryClient)diff --git a/web/app/components/step-by-step-tour/__tests__/state.spec.ts b/web/app/components/step-by-step-tour/__tests__/state.spec.tsindex 59499aa564e..7d842cfb6cd 100644--- a/web/app/components/step-by-step-tour/__tests__/state.spec.ts+++ b/web/app/components/step-by-step-tour/__tests__/state.spec.ts@@ -73,16 +73,17 @@ const patchStepByStepTourState = vi.fn(},)-vi.mock('@/config', () => ({- IS_CLOUD_EDITION: true,-}))-vi.mock('@/context/workspace-state', async () => {const { atom } = await vi.importActual<typeof import('jotai')>('jotai')return { currentWorkspaceIdAtom: atom('workspace-1') }})+vi.mock('@/context/system-features-state', async () => {+ const { atom } = await vi.importActual<typeof import('jotai')>('jotai')+ return { deploymentEditionAtom: atom('CLOUD') }+})+vi.mock('@/service/client', () => ({consoleQuery: {onboarding: {diff --git a/web/app/components/step-by-step-tour/mount.tsx b/web/app/components/step-by-step-tour/mount.tsxindex bafd0a38980..b50ea058f9d 100644--- a/web/app/components/step-by-step-tour/mount.tsx+++ b/web/app/components/step-by-step-tour/mount.tsx@@ -9,12 +9,11 @@ import type {import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'import { Popover, PopoverContent } from '@langgenius/dify-ui/popover'-import { useQuery } from '@tanstack/react-query'+import { useSuspenseQuery } from '@tanstack/react-query'import { useAtomValue, useSetAtom } from 'jotai'import { useEffect, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import { buildIntegrationPath } from '@/app/components/integrations/routes'-import { IS_CLOUD_EDITION } from '@/config'import { useDocLink } from '@/context/i18n'import { useModalContextSelector } from '@/context/modal-context'import { workspacePermissionKeysAtom } from '@/context/permission-state'@@ -131,7 +130,7 @@ export default function StepByStepTourMount({ className }: StepByStepTourMountPrconst isCurrentWorkspaceManager = useAtomValue(isCurrentWorkspaceManagerAtom)const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)const hasBlockingModalOpen = useModalContextSelector((state) => state.hasBlockingModalOpen)- const { data: systemFeatures } = useQuery(systemFeaturesQueryOptions())+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())const completedTaskIds = useAtomValue(completedStepByStepTourTaskIdsAtom)const skipped = useAtomValue(stepByStepTourSkippedAtom)const firstWorkspaceId = useAtomValue(stepByStepTourFirstWorkspaceIdAtom)@@ -182,8 +181,8 @@ export default function StepByStepTourMount({ className }: StepByStepTourMountPr[],)- const learnDifyEnabled = systemFeatures?.enable_learn_app ?? true- const stepByStepTourFeatureEnabled = Boolean(systemFeatures?.enable_step_by_step_tour)+ const learnDifyEnabled = systemFeatures.enable_learn_app+ const stepByStepTourFeatureEnabled = systemFeatures.enable_step_by_step_tourconst availableTasks = learnDifyEnabled? STEP_BY_STEP_TOUR_TASKS: STEP_BY_STEP_TOUR_TASKS.filter((task) => task.id !== 'home')@@ -229,7 +228,7 @@ export default function StepByStepTourMount({ className }: StepByStepTourMountPr}: undefinedconst visible =- IS_CLOUD_EDITION &&+ systemFeatures.deployment_edition === 'CLOUD' &&stepByStepTourFeatureEnabled &&enabledForCurrentWorkspace &&(hasActiveGuide || !shouldHideOnPathname(pathname))diff --git a/web/app/components/step-by-step-tour/state.ts b/web/app/components/step-by-step-tour/state.tsindex b7ba03422d4..d76481133d9 100644--- a/web/app/components/step-by-step-tour/state.ts+++ b/web/app/components/step-by-step-tour/state.ts@@ -14,7 +14,7 @@ import type {import { atom } from 'jotai'import { atomWithMutation, atomWithQuery, queryClientAtom } from 'jotai-tanstack-query'import { selectAtom } from 'jotai/utils'-import { IS_CLOUD_EDITION } from '@/config'+import { deploymentEditionAtom } from '@/context/system-features-state'import { currentWorkspaceIdAtom } from '@/context/workspace-state'import { consoleQuery } from '@/service/client'@@ -25,9 +25,9 @@ const stepByStepTourStateMutationScope = {id: 'step-by-step-tour-state',}-const stepByStepTourStateQueryAtom = atomWithQuery(() =>+const stepByStepTourStateQueryAtom = atomWithQuery((get) =>consoleQuery.onboarding.stepByStepTour.state.get.queryOptions({- enabled: IS_CLOUD_EDITION,+ enabled: get(deploymentEditionAtom) === 'CLOUD',}),)@@ -311,7 +311,7 @@ const patchStepByStepTourState = async (body: StepByStepTourStatePatchPayload,options?: StepByStepTourStateCommandOptions,) => {- if (!IS_CLOUD_EDITION) return+ if (get(deploymentEditionAtom) !== 'CLOUD') returnconst command: PendingStepByStepTourStateCommand = {body,diff --git a/web/app/components/tools/mcp/__tests__/create-card.spec.tsx b/web/app/components/tools/mcp/__tests__/create-card.spec.tsxindex c76b0e9ca9d..981c92315e2 100644--- a/web/app/components/tools/mcp/__tests__/create-card.spec.tsx+++ b/web/app/components/tools/mcp/__tests__/create-card.spec.tsx@@ -1,12 +1,10 @@-import type { ReactNode } from 'react'-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { fireEvent, screen, waitFor } from '@testing-library/react'-import * as React from 'react'import { beforeEach, describe, expect, it, vi } from 'vitest'import {getStepByStepTourTargetSelector,STEP_BY_STEP_TOUR_TARGETS,} from '@/app/components/step-by-step-tour/target-registry'+import { createConsoleQueryWrapper } from '@/test/console/query-data'import { render } from '@/test/console/render'import NewMCPCard, { NewMCPButton } from '../create-card'@@ -78,15 +76,7 @@ vi.mock('@/service/common', () => ({describe('NewMCPCard', () => {const createWrapper = () => {- const queryClient = new QueryClient({- defaultOptions: {- queries: {- retry: false,- },- },- })- return ({ children }: { children: ReactNode }) =>- React.createElement(QueryClientProvider, { client: queryClient }, children)+ return createConsoleQueryWrapper().wrapper}const defaultProps = {diff --git a/web/app/components/tools/mcp/__tests__/mcp-service-card.spec.tsx b/web/app/components/tools/mcp/__tests__/mcp-service-card.spec.tsxindex b22d2572a7e..45f5824c46d 100644--- a/web/app/components/tools/mcp/__tests__/mcp-service-card.spec.tsx+++ b/web/app/components/tools/mcp/__tests__/mcp-service-card.spec.tsx@@ -1,10 +1,12 @@import type { ReactNode } from 'react'import type { AppDetailResponse } from '@/models/app'import type { AppSSO } from '@/types/app'-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { QueryClient } from '@tanstack/react-query'import { fireEvent, render, screen, waitFor } from '@testing-library/react'import * as React from 'react'import { beforeEach, describe, expect, it, vi } from 'vitest'+import { seedSystemFeatures } from '@/test/console/query-data'+import { QueryClientTestProvider } from '@/test/console/query-provider'import { AppModeEnum } from '@/types/app'import MCPServiceCard from '../mcp-service-card'@@ -113,8 +115,9 @@ describe('MCPServiceCard', () => {const queryClient = new QueryClient({defaultOptions: { queries: { retry: false } },})+ seedSystemFeatures(queryClient)return ({ children }: { children: ReactNode }) =>- React.createElement(QueryClientProvider, { client: queryClient }, children)+ React.createElement(QueryClientTestProvider, { queryClient }, children)}const createMockAppInfo = (@@ -502,12 +505,15 @@ describe('MCPServiceCard', () => {rerender(<MCPServiceCard appInfo={createMockAppInfo()} />)expect(mockOnMcpServerUpdate).toHaveBeenCalledTimes(1)- expect(invalidateMCPServerDetailFns).toHaveLength(2)+ const latestInvalidateMCPServerDetail = invalidateMCPServerDetailFns.at(-1)+ expect(latestInvalidateMCPServerDetail).toBeDefined()mcpUpdateHandler?.({ type: 'mcp_server_update' })- expect(invalidateMCPServerDetailFns[0]).not.toHaveBeenCalled()- expect(invalidateMCPServerDetailFns[1]).toHaveBeenCalledWith('app-123')+ invalidateMCPServerDetailFns+ .slice(0, -1)+ .forEach((invalidate) => expect(invalidate).not.toHaveBeenCalled())+ expect(latestInvalidateMCPServerDetail).toHaveBeenCalledWith('app-123')})})})diff --git a/web/app/components/tools/mcp/__tests__/modal.spec.tsx b/web/app/components/tools/mcp/__tests__/modal.spec.tsxindex 97d8046122f..3f1d3304fde 100644--- a/web/app/components/tools/mcp/__tests__/modal.spec.tsx+++ b/web/app/components/tools/mcp/__tests__/modal.spec.tsx@@ -1,9 +1,7 @@-import type { ReactNode } from 'react'import type { ToolWithProvider } from '@/app/components/workflow/types'-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { fireEvent, render, screen, waitFor } from '@testing-library/react'-import * as React from 'react'import { beforeEach, describe, expect, it, vi } from 'vitest'+import { createConsoleQueryWrapper } from '@/test/console/query-data'import MCPModal from '../modal'// Mock the service API@@ -26,32 +24,13 @@ const mockSystemFeatures = vi.hoisted(() => ({sso_enforced_for_signin: false,sso_enforced_for_signin_protocol: '' as 'oidc' | 'oauth2' | 'saml' | '',}))-vi.mock('@/features/system-features/client', () => ({- systemFeaturesQueryOptions: () => ({- queryKey: ['mock-system-features'],- queryFn: async () => mockSystemFeatures,- }),-}))-describe('MCPModal', () => {beforeEach(() => {vi.clearAllMocks()})- const createWrapper = () => {- const queryClient = new QueryClient({- defaultOptions: {- queries: {- retry: false,- },- },- })- // useSuspenseQuery(systemFeaturesQueryOptions) reads from this key —- // pre-populate so the modal renders synchronously instead of suspending.- queryClient.setQueryData(['mock-system-features'], mockSystemFeatures)- return ({ children }: { children: ReactNode }) =>- React.createElement(QueryClientProvider, { client: queryClient }, children)- }+ const createWrapper = () =>+ createConsoleQueryWrapper({ systemFeatures: mockSystemFeatures }).wrapperconst defaultProps = {show: true,diff --git a/web/app/components/tools/provider/__tests__/empty.spec.tsx b/web/app/components/tools/provider/__tests__/empty.spec.tsxindex 130dfd90457..0bf9cfcbdb5 100644--- a/web/app/components/tools/provider/__tests__/empty.spec.tsx+++ b/web/app/components/tools/provider/__tests__/empty.spec.tsx@@ -1,5 +1,6 @@-import { render, screen } from '@testing-library/react'+import { screen } from '@testing-library/react'import { describe, expect, it, vi } from 'vitest'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { ToolType } from '../../../workflow/block-selector/types'import Empty from '../empty'diff --git a/web/app/components/workflow/hooks/__tests__/use-workflow-comment.spec.ts b/web/app/components/workflow/hooks/__tests__/use-workflow-comment.spec.tsindex 944cfe1c7a9..7f9593a74a8 100644--- a/web/app/components/workflow/hooks/__tests__/use-workflow-comment.spec.ts+++ b/web/app/components/workflow/hooks/__tests__/use-workflow-comment.spec.ts@@ -96,6 +96,10 @@ vi.mock('@/service/client', () => ({systemFeatures: {get: {queryKey: () => ['console', 'systemFeatures', 'get'],+ queryOptions: (options: Record<string, unknown> = {}) => ({+ queryKey: ['console', 'systemFeatures', 'get'],+ ...options,+ }),},},},diff --git a/web/app/components/workflow/nodes/_base/components/__tests__/agent-strategy-selector.spec.tsx b/web/app/components/workflow/nodes/_base/components/__tests__/agent-strategy-selector.spec.tsxindex 1ec98aaf2c0..6d13e22f62e 100644--- a/web/app/components/workflow/nodes/_base/components/__tests__/agent-strategy-selector.spec.tsx+++ b/web/app/components/workflow/nodes/_base/components/__tests__/agent-strategy-selector.spec.tsx@@ -19,10 +19,6 @@ vi.mock('@tanstack/react-query', () => ({useSuspenseQuery: mocks.useSuspenseQuery,}))-vi.mock('@/features/system-features/client', () => ({- systemFeaturesQueryOptions: () => ({}),-}))-vi.mock('@/service/use-strategy', () => ({useStrategyProviders: mocks.useStrategyProviders,}))diff --git a/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx b/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsxindex d4e5fac2ea6..189112c4e66 100644--- a/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx+++ b/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx@@ -3,9 +3,9 @@ import type {WorkflowAgentComposerResponse,} from '@dify/contracts/api/console/apps/types.gen'import type { ReactNode, Ref } from 'react'-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'-import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { act, fireEvent, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { FlowType } from '@/types/common'import { WorkflowInlineAgentConfigureWorkspace } from '../agent-orchestrate-panel-content'@@ -25,22 +25,6 @@ const mocks = vi.hoisted(() => ({uploadWorkflowSandboxFile: vi.fn(),}))-const editionState = vi.hoisted(() => ({- isSelfHosted: false,- licenseStatus: 'none',-}))--vi.mock('@/config', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/config')>()-- return {- ...actual,- get IS_CE_EDITION() {- return editionState.isSelfHosted- },- }-})-const permission = vi.hoisted(() => ({ canManageAgents: true }))vi.mock('@/features/agent-v2/permissions', () => ({@@ -205,37 +189,32 @@ vi.mock('@/app/components/workflow/nodes/agent-v2/agent-soul-config', () => ({}),}))-vi.mock('@/service/client', () => ({- consoleClient: {- systemFeatures: {- get: () =>- Promise.resolve({- license: {- status: editionState.licenseStatus,- },- }),- },- agent: {- byAgentId: {- sandbox: {- files: {- upload: {- post: mocks.uploadAgentSandboxFile,+vi.mock('@/service/client', async () => {+ const { createSystemFeaturesFixture } = await import('@/test/console/system-features')+ return {+ consoleClient: {+ agent: {+ byAgentId: {+ sandbox: {+ files: {+ upload: {+ post: mocks.uploadAgentSandboxFile,+ },},},},},- },- apps: {- byAppId: {- workflowRuns: {- byWorkflowRunId: {- agentNodes: {- byNodeId: {- sandbox: {- files: {- upload: {- post: mocks.uploadWorkflowSandboxFile,+ apps: {+ byAppId: {+ workflowRuns: {+ byWorkflowRunId: {+ agentNodes: {+ byNodeId: {+ sandbox: {+ files: {+ upload: {+ post: mocks.uploadWorkflowSandboxFile,+ },},},},@@ -245,154 +224,158 @@ vi.mock('@/service/client', () => ({},},},- },- consoleQuery: {- systemFeatures: {- get: {- queryKey: () => ['system-features'],- },- },- agent: {- byAgentId: {+ consoleQuery: {+ systemFeatures: {get: {- queryKey: () => ['agent-detail'],- },- debugConversation: {- refresh: {- post: {- mutationOptions: (options?: {- onSuccess?: (data: {- debug_conversation_has_messages: boolean- debug_conversation_id: string- debug_conversation_message_count: number- }) => void- }) => ({- mutationFn: mocks.refreshDebugConversation,- ...options,- }),- },- },- },- composer: {- get: {- queryOptions: vi.fn(),- },+ queryKey: () => ['system-features'],+ queryOptions: () => ({+ queryKey: ['system-features'],+ initialData: createSystemFeaturesFixture(),+ }),},- buildDraft: {+ },+ agent: {+ byAgentId: {get: {- queryOptions: () => ({- queryKey: ['build-draft'],- queryFn: mocks.loadBuildDraft,- }),- },- delete: {- mutationOptions: () => ({ mutationFn: mocks.deleteBuildDraft }),+ queryKey: () => ['agent-detail'],},- put: {- mutationOptions: () => ({ mutationFn: mocks.saveBuildDraft }),- },- apply: {- post: {- mutationOptions: () => ({ mutationFn: mocks.applyBuildDraft }),+ debugConversation: {+ refresh: {+ post: {+ mutationOptions: (options?: {+ onSuccess?: (data: {+ debug_conversation_has_messages: boolean+ debug_conversation_id: string+ debug_conversation_message_count: number+ }) => void+ }) => ({+ mutationFn: mocks.refreshDebugConversation,+ ...options,+ }),+ },},},- checkout: {- post: {- mutationOptions: () => ({ mutationFn: mocks.checkoutBuildDraft }),+ composer: {+ get: {+ queryOptions: vi.fn(),},},- },- buildChat: {- finalize: {- post: {- mutationOptions: () => ({ mutationFn: mocks.finalizeBuildChat }),+ buildDraft: {+ get: {+ queryOptions: () => ({+ queryKey: ['build-draft'],+ queryFn: mocks.loadBuildDraft,+ }),+ },+ delete: {+ mutationOptions: () => ({ mutationFn: mocks.deleteBuildDraft }),+ },+ put: {+ mutationOptions: () => ({ mutationFn: mocks.saveBuildDraft }),+ },+ apply: {+ post: {+ mutationOptions: () => ({ mutationFn: mocks.applyBuildDraft }),+ },+ },+ checkout: {+ post: {+ mutationOptions: () => ({ mutationFn: mocks.checkoutBuildDraft }),+ },},},- },- sandbox: {- get: {- queryOptions: () => ({- queryKey: ['sandbox-info'],- queryFn: () =>- Promise.resolve({- workspace_cwd: '.',- }),- }),+ buildChat: {+ finalize: {+ post: {+ mutationOptions: () => ({ mutationFn: mocks.finalizeBuildChat }),+ },+ },},- files: {+ sandbox: {get: {queryOptions: () => ({- queryKey: ['sandbox-files'],+ queryKey: ['sandbox-info'],queryFn: () =>Promise.resolve({- entries: [- {- name: 'result.txt',- type: 'file',- },- ],- path: '.',+ workspace_cwd: '.',}),}),},- read: {+ files: {get: {queryOptions: () => ({- queryKey: ['sandbox-file'],+ queryKey: ['sandbox-files'],queryFn: () =>Promise.resolve({- text: 'result',+ entries: [+ {+ name: 'result.txt',+ type: 'file',+ },+ ],+ path: '.',}),}),},- },- upload: {- post: {- mutationOptions: () => ({ mutationFn: mocks.uploadAgentSandboxFile }),+ read: {+ get: {+ queryOptions: () => ({+ queryKey: ['sandbox-file'],+ queryFn: () =>+ Promise.resolve({+ text: 'result',+ }),+ }),+ },+ },+ upload: {+ post: {+ mutationOptions: () => ({ mutationFn: mocks.uploadAgentSandboxFile }),+ },},},},},},- },- apps: {- byAppId: {- workflowRuns: {- byWorkflowRunId: {- agentNodes: {- byNodeId: {- sandbox: {- files: {- get: {- key: () => ['workflow-agent-node-sandbox-files'],- queryOptions: () => ({- queryKey: ['workflow-agent-node-sandbox-files'],- queryFn: () =>- Promise.resolve({- entries: [- {- name: 'result.txt',- type: 'file',- },- ],- path: '.',- }),- }),- },- read: {+ apps: {+ byAppId: {+ workflowRuns: {+ byWorkflowRunId: {+ agentNodes: {+ byNodeId: {+ sandbox: {+ files: {get: {+ key: () => ['workflow-agent-node-sandbox-files'],queryOptions: () => ({- queryKey: ['workflow-agent-node-sandbox-file'],+ queryKey: ['workflow-agent-node-sandbox-files'],queryFn: () =>Promise.resolve({- text: 'result',+ entries: [+ {+ name: 'result.txt',+ type: 'file',+ },+ ],+ path: '.',}),}),},- },- upload: {- post: {- mutationOptions: () => ({ mutationFn: mocks.uploadWorkflowSandboxFile }),+ read: {+ get: {+ queryOptions: () => ({+ queryKey: ['workflow-agent-node-sandbox-file'],+ queryFn: () =>+ Promise.resolve({+ text: 'result',+ }),+ }),+ },+ },+ upload: {+ post: {+ mutationOptions: () => ({ mutationFn: mocks.uploadWorkflowSandboxFile }),+ },},},},@@ -400,23 +383,23 @@ vi.mock('@/service/client', () => ({},},},- },- workflows: {- draft: {- nodes: {- byNodeId: {- agentComposer: {- get: {- queryKey: ({- input,- }: {- input: {- params: {- app_id: string- node_id: string+ workflows: {+ draft: {+ nodes: {+ byNodeId: {+ agentComposer: {+ get: {+ queryKey: ({+ input,+ }: {+ input: {+ params: {+ app_id: string+ node_id: string+ }}- }- }) => ['workflow-agent-composer', input.params.app_id, input.params.node_id],+ }) => ['workflow-agent-composer', input.params.app_id, input.params.node_id],+ },},},},@@ -425,8 +408,8 @@ vi.mock('@/service/client', () => ({},},},- },-}))+ }+})function createInlineComposerState({debugConversationHasMessages = false,@@ -485,8 +468,6 @@ describe('WorkflowInlineAgentConfigureWorkspace', () => {beforeEach(() => {vi.clearAllMocks()mocks.completeBuildConversation = undefined- editionState.isSelfHosted = false- editionState.licenseStatus = 'none'permission.canManageAgents = truemocks.loadBuildDraft.mockRejectedValue(new Response(null, { status: 404 }))mocks.checkoutBuildDraft.mockResolvedValue({@@ -532,24 +513,26 @@ describe('WorkflowInlineAgentConfigureWorkspace', () => {function renderWorkspace(props: {+ deploymentEdition?: 'CLOUD' | 'COMMUNITY' | 'ENTERPRISE'inlineComposerState?: WorkflowAgentComposerResponseonSaveInlineToRoster?: () => void} = {},) {- const queryClient = new QueryClient()-return render(- <QueryClientProvider client={queryClient}>- <WorkflowInlineAgentConfigureWorkspace- agentId="agent-1"- flowId="app-1"- flowType={FlowType.appFlow}- inlineComposerState={props.inlineComposerState ?? createInlineComposerState()}- nodeId="node-1"- onSaveInlineToRoster={props.onSaveInlineToRoster}- open- />- </QueryClientProvider>,+ <WorkflowInlineAgentConfigureWorkspace+ agentId="agent-1"+ flowId="app-1"+ flowType={FlowType.appFlow}+ inlineComposerState={props.inlineComposerState ?? createInlineComposerState()}+ nodeId="node-1"+ onSaveInlineToRoster={props.onSaveInlineToRoster}+ open+ />,+ {+ systemFeatures: {+ deployment_edition: props.deploymentEdition ?? 'CLOUD',+ },+ },)}@@ -823,8 +806,7 @@ describe('WorkflowInlineAgentConfigureWorkspace', () => {})it('should keep preview disabled for an inline agent in community edition', async () => {- editionState.isSelfHosted = true- renderWorkspace()+ renderWorkspace({ deploymentEdition: 'COMMUNITY' })expect(await screen.findByRole('button', {@@ -1423,16 +1405,14 @@ describe('WorkflowInlineAgentConfigureWorkspace', () => {fireEvent.change(localDraftInput, { target: { value: 'draft still mounted' } })rerender(- <QueryClientProvider client={new QueryClient()}>- <WorkflowInlineAgentConfigureWorkspace- agentId="agent-1"- flowId="app-1"- flowType={FlowType.appFlow}- inlineComposerState={createInlineComposerState({ snapshotId: 'snapshot-2' })}- nodeId="node-1"- open- />- </QueryClientProvider>,+ <WorkflowInlineAgentConfigureWorkspace+ agentId="agent-1"+ flowId="app-1"+ flowType={FlowType.appFlow}+ inlineComposerState={createInlineComposerState({ snapshotId: 'snapshot-2' })}+ nodeId="node-1"+ open+ />,)expect(screen.getByRole('textbox', { name: 'local composer draft' })).toHaveValue(diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsx b/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsxindex 377bf683245..25e2b41bd86 100644--- a/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsx+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsx@@ -28,7 +28,6 @@ import {useDefaultModel,useTextGenerationCurrentProviderAndModelAndModelList,} from '@/app/components/header/account-setting/model-provider-page/hooks'-import { IS_CE_EDITION } from '@/config'import {agentSoulConfigToFormState,formStateToAgentSoulConfig,@@ -68,7 +67,6 @@ import {import { useAgentConfigureSessionController } from '@/features/agent-v2/agent-detail/configure/use-agent-configure-session-controller'import { useCanManageAgents } from '@/features/agent-v2/permissions'import { systemFeaturesQueryOptions } from '@/features/system-features/client'-import { LicenseStatus } from '@/features/system-features/constants'import { consoleQuery } from '@/service/client'import { FlowType } from '@/types/common'import { useWorkflowInlineAgentConfigureSync } from '../agent-soul-config'@@ -319,10 +317,7 @@ function WorkflowInlineAgentConfigureWorkspaceContent({const appId = flowType === FlowType.appFlow ? flowId : undefinedconst conversationIds = useAtomValue(agentConfigureConversationIdsAtom)const [rightPanelMode, setRightPanelMode] = useAtom(agentConfigureRightPanelModeAtom)- const previewEnabled =- !IS_CE_EDITION ||- systemFeatures?.license.status === LicenseStatus.ACTIVE ||- systemFeatures?.license.status === LicenseStatus.EXPIRING+ const previewEnabled = systemFeatures?.deployment_edition !== 'COMMUNITY'const workingDirectoryPanel = useAgentWorkingDirectoryPanel({agentId,appId,diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/index.spec.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/index.spec.tsxindex 69ed86497d4..3aad1dd33db 100644--- a/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/index.spec.tsx+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/index.spec.tsx@@ -1,4 +1,5 @@-import { fireEvent, render, screen, waitFor } from '@testing-library/react'+import { fireEvent, screen, waitFor } from '@testing-library/react'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { withSelectorKey } from '@/test/i18n-mock'import { DeliveryMethodType } from '../../../types'import DeliveryMethodForm from '../index'diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/method-selector.spec.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/method-selector.spec.tsxindex 092c3613d3b..c0afaeafb98 100644--- a/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/method-selector.spec.tsx+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/method-selector.spec.tsx@@ -1,9 +1,13 @@import type { Node } from '@/app/components/workflow/types'-import { fireEvent, render, screen } from '@testing-library/react'+import { fireEvent, screen } from '@testing-library/react'import { BlockEnum } from '@/app/components/workflow/types'+import { renderWithConsoleQuery } from '@/test/console/query-data'import { DeliveryMethodType } from '../../../types'import MethodSelector from '../method-selector'+const render = (ui: React.ReactElement) =>+ renderWithConsoleQuery(ui, { systemFeatures: { deployment_edition: 'CLOUD' } })+const mockUuid = vi.hoisted(() => vi.fn())const mockUseWorkflowNodes = vi.hoisted(() => vi.fn())const mockUseProviderContextSelector = vi.hoisted(() => vi.fn())@@ -23,10 +27,6 @@ vi.mock('@/context/provider-context', () => ({) => mockUseProviderContextSelector(selector),}))-vi.mock('@/config', () => ({- IS_CE_EDITION: false,-}))-describe('human-input/delivery-method/method-selector', () => {beforeEach(() => {vi.clearAllMocks()diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/upgrade-modal.spec.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/upgrade-modal.spec.tsxindex 61dcb0fd389..40c59f5d291 100644--- a/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/upgrade-modal.spec.tsx+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/upgrade-modal.spec.tsx@@ -1,13 +1,9 @@-import { fireEvent, render, screen } from '@testing-library/react'+import { fireEvent, screen } from '@testing-library/react'+import { renderWithConsoleQuery } from '@/test/console/query-data'import { UpgradeModal } from '../upgrade-modal'-vi.mock('@/config', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/config')>()- return {- ...actual,- IS_CLOUD_EDITION: true,- }-})+const render = (ui: React.ReactElement) =>+ renderWithConsoleQuery(ui, { systemFeatures: { deployment_edition: 'CLOUD' } })const mockUseModalContextSelector = vi.hoisted(() => vi.fn())diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/method-selector.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/method-selector.tsxindex d90e2185938..13b8db2e098 100644--- a/web/app/components/workflow/nodes/human-input/components/delivery-method/method-selector.tsx+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/method-selector.tsx@@ -10,6 +10,7 @@ import {RiMailSendFill,RiRobot2Fill,} from '@remixicon/react'+import { useSuspenseQuery } from '@tanstack/react-query'import { memo, useMemo, useState } from 'react'import { Trans, useTranslation } from 'react-i18next'import { v4 as uuid4 } from 'uuid'@@ -18,8 +19,8 @@ import Badge from '@/app/components/base/badge'import { Slack, Teams } from '@/app/components/base/icons/src/public/other'import useWorkflowNodes from '@/app/components/workflow/store/workflow/use-nodes'import { isTriggerWorkflow } from '@/app/components/workflow/utils/workflow-entry'-import { IS_CE_EDITION } from '@/config'import { useProviderContextSelector } from '@/context/provider-context'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { DeliveryMethodType } from '../../types'const i18nPrefix = 'nodes.humanInput'@@ -32,6 +33,10 @@ type MethodSelectorProps = {const MethodSelector: FC<MethodSelectorProps> = ({ data, onAdd, onShowUpgradeTip }) => {const { t } = useTranslation()+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })const [open, setOpen] = useState(false)const humanInputEmailDeliveryEnabled = useProviderContextSelector((s) => s.humanInputEmailDeliveryEnabled,@@ -260,7 +265,7 @@ const MethodSelector: FC<MethodSelectorProps> = ({ data, onAdd, onShowUpgradeTip</div></div></div>- {!IS_CE_EDITION && (+ {deploymentEdition === 'CLOUD' && (<div className="mt-1 rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg backdrop-blur-xs"><div className="flex items-center gap-2 px-4 py-3"><divdiff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/upgrade-modal.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/upgrade-modal.tsxindex c53fc141b83..af50a6bfcd2 100644--- a/web/app/components/workflow/nodes/human-input/components/delivery-method/upgrade-modal.tsx+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/upgrade-modal.tsx@@ -1,11 +1,12 @@import { Button } from '@langgenius/dify-ui/button'import { RiMailSendFill } from '@remixicon/react'+import { useSuspenseQuery } from '@tanstack/react-query'import { useTranslation } from 'react-i18next'import { SparklesSoft } from '@/app/components/base/icons/src/public/common'import { PremiumBadgeButton } from '@/app/components/base/premium-badge'import { UpgradeModal as BaseUpgradeModal } from '@/app/components/base/upgrade-modal'-import { IS_CLOUD_EDITION } from '@/config'import { useModalContextSelector } from '@/context/modal-context'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'type UpgradeModalProps = {open: boolean@@ -14,6 +15,10 @@ type UpgradeModalProps = {export function UpgradeModal({ open, onOpenChange }: UpgradeModalProps) {const { t } = useTranslation()+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })const setShowPricingModal = useModalContextSelector((s) => s.setShowPricingModal)const handleUpgrade = () => {setShowPricingModal()@@ -36,7 +41,7 @@ export function UpgradeModal({ open, onOpenChange }: UpgradeModalProps) {<Button className="w-[72px]" onClick={() => onOpenChange(false)}>{t(($) => $['nodes.humanInput.deliveryMethod.upgradeTipHide'], { ns: 'workflow' })}</Button>- {IS_CLOUD_EDITION && (+ {deploymentEdition === 'CLOUD' && (<PremiumBadgeButtonsize="custom"color="blue"diff --git a/web/app/components/workflow/nodes/knowledge-base/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/knowledge-base/__tests__/panel.spec.tsxindex db8c74e4448..b30dd0c5df1 100644--- a/web/app/components/workflow/nodes/knowledge-base/__tests__/panel.spec.tsx+++ b/web/app/components/workflow/nodes/knowledge-base/__tests__/panel.spec.tsx@@ -15,12 +15,25 @@ const mockSummaryIndexSetting = vi.hoisted(() =>)const mockQueryOptions = vi.hoisted(() => vi.fn((options: unknown) => options))-vi.mock('@tanstack/react-query', () => ({+vi.mock('@tanstack/react-query', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@tanstack/react-query')>()),useQuery: mockUseQuery,+ useSuspenseQuery: ({ select }: { select: (value: unknown) => unknown }) => ({+ data: select({ deployment_edition: 'COMMUNITY' }),+ }),}))vi.mock('@/service/client', () => ({consoleQuery: {+ systemFeatures: {+ get: {+ queryKey: () => ['console', 'systemFeatures', 'get'],+ queryOptions: (options?: Record<string, unknown>) => ({+ queryKey: ['console', 'systemFeatures', 'get'],+ ...options,+ }),+ },+ },workspaces: {current: {modelProviders: {@@ -72,14 +85,6 @@ vi.mock('@/app/components/datasets/settings/utils', () => ({checkShowMultiModalTip: () => false,}))-vi.mock('@/config', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/config')>()- return {- ...actual,- IS_CE_EDITION: true,- }-})-vi.mock('@/app/components/workflow/nodes/_base/components/layout', () => ({Group: ({ children }: { children: ReactNode }) => <div data-testid="group">{children}</div>,BoxGroup: ({ children }: { children: ReactNode }) => (diff --git a/web/app/components/workflow/nodes/knowledge-base/panel.tsx b/web/app/components/workflow/nodes/knowledge-base/panel.tsxindex bb40f738fb6..23c8f0d6bbd 100644--- a/web/app/components/workflow/nodes/knowledge-base/panel.tsx+++ b/web/app/components/workflow/nodes/knowledge-base/panel.tsx@@ -1,7 +1,7 @@import type { FC } from 'react'import type { KnowledgeBaseNodeType } from './types'import type { NodePanelProps, Var } from '@/app/components/workflow/types'-import { useQuery } from '@tanstack/react-query'+import { useQuery, useSuspenseQuery } from '@tanstack/react-query'import { memo, useCallback, useMemo } from 'react'import { useTranslation } from 'react-i18next'import SummaryIndexSetting from '@/app/components/datasets/settings/summary-index-setting'@@ -16,7 +16,7 @@ import {Group,} from '@/app/components/workflow/nodes/_base/components/layout'import VarReferencePicker from '@/app/components/workflow/nodes/_base/components/variable/var-reference-picker'-import { IS_CE_EDITION } from '@/config'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { consoleQuery } from '@/service/client'import Split from '../_base/components/split'import ChunkStructure from './components/chunk-structure'@@ -30,6 +30,11 @@ import { getKnowledgeBaseValidationIssue, KnowledgeBaseValidationIssueCode } froconst Panel: FC<NodePanelProps<KnowledgeBaseNodeType>> = ({ id, data }) => {const { t } = useTranslation()+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })+ const isNonCloudEdition = deploymentEdition === 'COMMUNITY' || deploymentEdition === 'ENTERPRISE'const { nodesReadOnly } = useNodesReadOnly()const { data: embeddingModelList } = useModelList(ModelTypeEnum.textEmbedding)const { data: rerankModelList } = useModelList(ModelTypeEnum.rerank)@@ -243,7 +248,7 @@ const Panel: FC<NodePanelProps<KnowledgeBaseNodeType>> = ({ id, data }) => {[ChunkStructureEnum.general, ChunkStructureEnum.parent_child].includes(data.chunk_structure,) &&- IS_CE_EDITION && (+ isNonCloudEdition && (<><SummaryIndexSettingsummaryIndexSetting={data.summary_index_setting}diff --git a/web/app/components/workflow/panel/version-history-panel/__tests__/index.spec.tsx b/web/app/components/workflow/panel/version-history-panel/__tests__/index.spec.tsxindex 5c9abb58404..b004638db36 100644--- a/web/app/components/workflow/panel/version-history-panel/__tests__/index.spec.tsx+++ b/web/app/components/workflow/panel/version-history-panel/__tests__/index.spec.tsx@@ -3,7 +3,7 @@ import type { VersionHistory } from '@/types/workflow'import { fireEvent, screen, waitFor } from '@testing-library/react'import { useEffect, useRef } from 'react'import { Plan } from '@/app/components/billing/type'-import { render } from '@/test/console/render'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { VersionHistoryContextMenuOptions, WorkflowVersion } from '../../../types'const mockHandleRestoreFromPublishedWorkflow = vi.fn()diff --git a/web/app/components/workflow/panel/version-history-panel/action-menu/__tests__/index.spec.tsx b/web/app/components/workflow/panel/version-history-panel/action-menu/__tests__/index.spec.tsxindex 0058663d0b5..b27be377ed0 100644--- a/web/app/components/workflow/panel/version-history-panel/action-menu/__tests__/index.spec.tsx+++ b/web/app/components/workflow/panel/version-history-panel/action-menu/__tests__/index.spec.tsx@@ -1,15 +1,21 @@import { screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { Plan } from '@/app/components/billing/type'+import { createConsoleQueryClient, seedSystemFeatures } from '@/test/console/query-data'import { renderWorkflowComponent } from '../../../../__tests__/workflow-test-env'import { VersionHistoryContextMenuOptions } from '../../../../types'import ActionMenu from '../index'+const renderActionMenu = (ui: React.ReactElement) => {+ const queryClient = createConsoleQueryClient()+ seedSystemFeatures(queryClient, { deployment_edition: 'CLOUD' })+ return renderWorkflowComponent(ui, { queryClient })+}+vi.mock('@/config', async (importOriginal) => {const actual = await importOriginal<typeof import('@/config')>()return {...actual,- IS_CLOUD_EDITION: true,}})@@ -35,7 +41,7 @@ describe('ActionMenu', () => {const setOpen = vi.fn()const handleClickActionMenuItem = vi.fn()- renderWorkflowComponent(+ renderActionMenu(<ActionMenuisNamedVersionisShowDelete@@ -66,7 +72,7 @@ describe('ActionMenu', () => {const handleClickActionMenuItem = vi.fn()mockPlanType = Plan.sandbox- renderWorkflowComponent(+ renderActionMenu(<ActionMenuisNamedVersionisShowDeletediff --git a/web/app/components/workflow/run/__tests__/node.spec.tsx b/web/app/components/workflow/run/__tests__/node.spec.tsxindex 0dffd133c19..6a53de3f453 100644--- a/web/app/components/workflow/run/__tests__/node.spec.tsx+++ b/web/app/components/workflow/run/__tests__/node.spec.tsx@@ -1,5 +1,6 @@import type { NodeTracing } from '@/types/workflow'-import { fireEvent, render, screen, waitFor } from '@testing-library/react'+import { fireEvent, screen, waitFor } from '@testing-library/react'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { BlockEnum, NodeRunningStatus } from '../../types'import NodePanel from '../node'diff --git a/web/app/components/workflow/run/iteration-log/__tests__/iteration-result-panel.spec.tsx b/web/app/components/workflow/run/iteration-log/__tests__/iteration-result-panel.spec.tsxindex 03217b416be..85c458537d0 100644--- a/web/app/components/workflow/run/iteration-log/__tests__/iteration-result-panel.spec.tsx+++ b/web/app/components/workflow/run/iteration-log/__tests__/iteration-result-panel.spec.tsx@@ -1,6 +1,7 @@import type { IterationDurationMap, NodeTracing } from '@/types/workflow'-import { render, screen } from '@testing-library/react'+import { screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { BlockEnum, NodeRunningStatus } from '../../../types'import IterationResultPanel from '../iteration-result-panel'diff --git a/web/app/components/workflow/run/retry-log/__tests__/retry-result-panel.spec.tsx b/web/app/components/workflow/run/retry-log/__tests__/retry-result-panel.spec.tsxindex 0b3d8191c20..c1c43cc0cd4 100644--- a/web/app/components/workflow/run/retry-log/__tests__/retry-result-panel.spec.tsx+++ b/web/app/components/workflow/run/retry-log/__tests__/retry-result-panel.spec.tsx@@ -1,6 +1,7 @@import type { NodeTracing } from '@/types/workflow'-import { render, screen } from '@testing-library/react'+import { screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { BlockEnum, NodeRunningStatus } from '../../../types'import RetryResultPanel from '../retry-result-panel'diff --git a/web/app/components/workflow/workflow-generator/__tests__/index.spec.tsx b/web/app/components/workflow/workflow-generator/__tests__/index.spec.tsxindex 72c41b4e1b6..71a9e00d877 100644--- a/web/app/components/workflow/workflow-generator/__tests__/index.spec.tsx+++ b/web/app/components/workflow/workflow-generator/__tests__/index.spec.tsx@@ -18,10 +18,6 @@ vi.mock('@tanstack/react-query', async (importOriginal) => {}})-vi.mock('@/features/system-features/client', () => ({- systemFeaturesQueryOptions: vi.fn(() => ({})),-}))-vi.mock('@/next/navigation', () => ({useRouter: () => ({ push: vi.fn() }),}))diff --git a/web/app/device/__tests__/page-terminal.spec.tsx b/web/app/device/__tests__/page-terminal.spec.tsxindex 9317da86e97..9c3d7920736 100644--- a/web/app/device/__tests__/page-terminal.spec.tsx+++ b/web/app/device/__tests__/page-terminal.spec.tsx@@ -1,6 +1,7 @@import { useQuery } from '@tanstack/react-query'-import { fireEvent, render, screen } from '@testing-library/react'+import { fireEvent, screen } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import DevicePage from '../page'const mockPush = vi.fn()@@ -35,10 +36,6 @@ vi.mock('@/service/device-flow', () => ({},}))-vi.mock('@/features/system-features/client', () => ({- systemFeaturesQueryOptions: () => ({ queryKey: ['sys'], queryFn: async () => ({}) }),-}))-vi.mock('@/features/account-profile/client', () => ({userProfileQueryOptions: () => ({ queryKey: ['profile'], queryFn: async () => null }),}))diff --git a/web/app/device/page.tsx b/web/app/device/page.tsxindex 1b8b56a5f17..5926797ac3a 100644--- a/web/app/device/page.tsx+++ b/web/app/device/page.tsx@@ -1,7 +1,7 @@'use client'import { Button } from '@langgenius/dify-ui/button'-import { useQuery } from '@tanstack/react-query'+import { useQuery, useSuspenseQuery } from '@tanstack/react-query'import { useEffect, useState } from 'react'import { Trans, useTranslation } from 'react-i18next'import Divider from '@/app/components/base/divider'@@ -59,14 +59,14 @@ export default function DevicePage() {retry: false,refetchOnWindowFocus: false,})- const { data: sys } = useQuery(systemFeaturesQueryOptions())+ const { data: sys } = useSuspenseQuery(systemFeaturesQueryOptions())// Device-flow SSO branch uses external-user (webapp) SSO, not console SSO —// backend mints EXTERNAL_SSO tokens via Enterprise's external ACS. Gate on// webapp_auth.{enabled, allow_sso} + a configured webapp SSO protocol.const ssoAvailable =- !!sys?.webapp_auth?.enabled &&- !!sys?.webapp_auth?.allow_sso &&- (sys?.webapp_auth?.sso_config?.protocol || '') !== ''+ sys.webapp_auth.enabled &&+ sys.webapp_auth.allow_sso &&+ sys.webapp_auth.sso_config.protocol !== ''// URL-driven view transitions. Only advances while the user is still on// the entry/chooser screens — never clobbers terminal views (success /diff --git a/web/app/education-apply/__tests__/education-apply-page.spec.tsx b/web/app/education-apply/__tests__/education-apply-page.spec.tsxindex 46da4381588..62252fae62c 100644--- a/web/app/education-apply/__tests__/education-apply-page.spec.tsx+++ b/web/app/education-apply/__tests__/education-apply-page.spec.tsx@@ -1,9 +1,8 @@-import { QueryClient } from '@tanstack/react-query'import { cleanup, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { Plan } from '@/app/components/billing/type'import EducationApplyPage from '@/app/education-apply/education-apply-page'-import { createQueryClientWrapper } from '@/test/console/query-client'+import { createConsoleQueryWrapper } from '@/test/console/query-data'import { render } from '@/test/console/render'let mockProviderContext: Record<string, unknown> = {}@@ -64,6 +63,15 @@ vi.mock('@/service/client', () => ({},},consoleQuery: {+ systemFeatures: {+ get: {+ queryKey: () => ['system-features'],+ queryOptions: (options: Record<string, unknown> = {}) => ({+ queryKey: ['system-features'],+ ...options,+ }),+ },+ },workspaces: {get: {queryOptions: () => ({@@ -98,11 +106,9 @@ const setupContext = (isCurrentWorkspaceManager: boolean) => {}const renderPage = () => {- const queryClient = new QueryClient({- defaultOptions: { queries: { retry: false } },- })+ const { wrapper } = createConsoleQueryWrapper()return render(<EducationApplyPage />, {- wrapper: createQueryClientWrapper(queryClient),+ wrapper,})}diff --git a/web/app/education-apply/expire-notice-modal.tsx b/web/app/education-apply/expire-notice-modal.tsxindex cfec9829aa5..cc11adb4dfb 100644--- a/web/app/education-apply/expire-notice-modal.tsx+++ b/web/app/education-apply/expire-notice-modal.tsx@@ -2,11 +2,12 @@import { Button } from '@langgenius/dify-ui/button'import { Dialog, DialogCloseButton, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'import { RiExternalLinkLine } from '@remixicon/react'+import { useSuspenseQuery } from '@tanstack/react-query'import * as React from 'react'import { useTranslation } from 'react-i18next'-import { IS_CLOUD_EDITION } from '@/config'import { useDocLink } from '@/context/i18n'import { useModalContextSelector } from '@/context/modal-context'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import useTimestamp from '@/hooks/use-timestamp'import Link from '@/next/link'import { useRouter } from '@/next/navigation'@@ -25,6 +26,10 @@ const i18nPrefix = 'notice'const ExpireNoticeModal: React.FC<Props> = ({ expireAt, expired, onClose }) => {const { t } = useTranslation()+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })const docLink = useDocLink()const eduDocLink = docLink('/use-dify/workspace/subscription-management#dify-for-education')const { formatTime } = useTimestamp()@@ -103,7 +108,7 @@ const ExpireNoticeModal: React.FC<Props> = ({ expireAt, expired, onClose }) => {<RiExternalLinkLine className="size-3" /></Link><div className="flex space-x-2">- {expired && IS_CLOUD_EDITION ? (+ {expired && deploymentEdition === 'CLOUD' ? (<ButtononClick={() => {onClose()diff --git a/web/app/error.tsx b/web/app/error.tsxindex 0d17208ebe1..52b9275a304 100644--- a/web/app/error.tsx+++ b/web/app/error.tsx@@ -1,6 +1,7 @@'use client'import { Button } from '@langgenius/dify-ui/button'+import { useQueryErrorResetBoundary } from '@tanstack/react-query'import { useTranslation } from 'react-i18next'import { FullScreenLoading } from '@/app/components/full-screen-loading'import { isLegacyBase401 } from '@/features/account-profile/client'@@ -13,6 +14,7 @@ type Props = {export default function AppError({ error, reset, unstable_retry }: Props) {const { t } = useTranslation('common')+ const { reset: resetQueries } = useQueryErrorResetBoundary()const retry = reset ?? unstable_retryconsole.error(error)@@ -25,7 +27,14 @@ export default function AppError({ error, reset, unstable_retry }: Props) {{t(($) => $['errorBoundary.message'])}</div>{retry && (- <Button size="small" variant="secondary" onClick={() => retry()}>+ <Button+ size="small"+ variant="secondary"+ onClick={() => {+ resetQueries()+ retry()+ }}+ >{t(($) => $['errorBoundary.tryAgain'])}</Button>)}diff --git a/web/app/layout.tsx b/web/app/layout.tsxindex fa7188767b0..4618dc6ed5a 100644--- a/web/app/layout.tsx+++ b/web/app/layout.tsx@@ -1,21 +1,22 @@import type { Viewport } from '@/next'import { ToastHost } from '@langgenius/dify-ui/toast'import { TooltipProvider } from '@langgenius/dify-ui/tooltip'+import { dehydrate, HydrationBoundary } from '@tanstack/react-query'import { Provider as JotaiProvider } from 'jotai/react'import { ThemeProvider } from 'next-themes'import { NuqsAdapter } from 'nuqs/adapters/next/app'import { IS_PROD } from '@/config'-import { TanstackQueryInitializer } from '@/context/query-client'+import { TanStackQueryProvider } from '@/context/query-client'+import { getQueryClientServer } from '@/context/query-client-server'import { getDatasetMap } from '@/env'+import { SystemFeaturesBootstrapBoundary } from '@/features/system-features/bootstrap-boundary'import { getLocaleOnServer } from '@/i18n-config/server'import { headers } from '@/next/headers'-import { CloudAnalyticsBoundary } from './components/base/analytics-consent/cloud-analytics-boundary'-import { CloudAnalyticsRuntime } from './components/base/analytics-consent/cloud-analytics-runtime'-import { getCloudAnalyticsBoundaryState } from './components/base/analytics-consent/cloud-analytics-state'-import PartnerStackCookieRecorder from './components/billing/partner-stack/cookie-recorder'+import { serverConsoleQuery } from '@/service/server'+import { CloudAnalytics } from './components/base/analytics-consent/cloud-analytics'+import { PartnerStackCookieRecorder } from './components/billing/partner-stack/cookie-recorder'import { AgentationLoader } from './components/devtools/agentation-loader'import { ReactScanLoader } from './components/devtools/react-scan/loader'-import ExternalAttributionRecorder from './components/external-attribution-recorder'import { I18nServerProvider } from './components/provider/i18n-server'import RoutePrefixHandle from './routePrefixHandle'import './styles/globals.css'@@ -27,12 +28,17 @@ export const viewport: Viewport = {viewportFit: 'cover',}-const LocaleLayout = async ({ children }: { children: React.ReactNode }) => {- const locale = await getLocaleOnServer()+export default async function RootLayout({ children }: { children: React.ReactNode }) {const datasetMap = getDatasetMap()- const requestHeaders = await headers()+ const queryClient = getQueryClientServer()+ const systemFeaturesQuery = serverConsoleQuery.systemFeatures.get.queryOptions()+ const [locale, requestHeaders] = await Promise.all([+ getLocaleOnServer(),+ headers(),+ queryClient.prefetchQuery(systemFeaturesQuery),+ ])+ const dehydratedState = dehydrate(queryClient)const nonce = IS_PROD ? (requestHeaders.get('x-nonce') ?? undefined) : undefined- const cloudAnalyticsState = getCloudAnalyticsBoundaryState(requestHeaders)return (<html lang={locale ?? 'en'} className="h-full" suppressHydrationWarning>@@ -49,11 +55,10 @@ const LocaleLayout = async ({ children }: { children: React.ReactNode }) => {<meta name="msapplication-TileColor" content="#1C64F2" /><meta name="msapplication-config" content="/browserconfig.xml" />- <CloudAnalyticsBoundary {...cloudAnalyticsState} /><ReactScanLoader /></head><body className="h-full bg-background-body" {...datasetMap}>- {cloudAnalyticsState.enabled && <CloudAnalyticsRuntime />}+ <CloudAnalytics /><div className="isolate h-full"><JotaiProvider><ThemeProvider@@ -64,16 +69,19 @@ const LocaleLayout = async ({ children }: { children: React.ReactNode }) => {nonce={nonce}><NuqsAdapter>- <TanstackQueryInitializer>- <I18nServerProvider>- <ToastHost timeout={5000} limit={3} />- <PartnerStackCookieRecorder />- <ExternalAttributionRecorder />- <TooltipProvider delay={300} closeDelay={200}>- {children}- </TooltipProvider>- </I18nServerProvider>- </TanstackQueryInitializer>+ <TanStackQueryProvider>+ <HydrationBoundary state={dehydratedState}>+ <I18nServerProvider>+ <ToastHost timeout={5000} limit={3} />+ <SystemFeaturesBootstrapBoundary>+ <PartnerStackCookieRecorder />+ <TooltipProvider delay={300} closeDelay={200}>+ {children}+ </TooltipProvider>+ </SystemFeaturesBootstrapBoundary>+ </I18nServerProvider>+ </HydrationBoundary>+ </TanStackQueryProvider></NuqsAdapter></ThemeProvider></JotaiProvider>@@ -84,5 +92,3 @@ const LocaleLayout = async ({ children }: { children: React.ReactNode }) => {</html>)}--export default LocaleLayoutdiff --git a/web/app/signin/__tests__/_header.spec.tsx b/web/app/signin/__tests__/_header.spec.tsxindex 0ed0904e4c7..ffe7dfc66c1 100644--- a/web/app/signin/__tests__/_header.spec.tsx+++ b/web/app/signin/__tests__/_header.spec.tsx@@ -1,11 +1,8 @@-import { useSuspenseQuery } from '@tanstack/react-query'-import { fireEvent, render, screen } from '@testing-library/react'+import { fireEvent, screen } from '@testing-library/react'import { setLocaleOnClient } from '@/i18n-config'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import Header from '../_header'-vi.mock('@tanstack/react-query', () => ({- useSuspenseQuery: vi.fn(),-}))vi.mock('@/i18n-config', () => ({setLocaleOnClient: vi.fn(),}))@@ -14,10 +11,6 @@ vi.mock('@/next/dynamic', () => ({default: () => () => null,}))-vi.mock('@/features/system-features/client', () => ({- systemFeaturesQueryOptions: () => ({}),-}))-vi.mock('../_locale-menu', () => ({default: ({ onChange }: { onChange?: (value: string) => void }) => (<button type="button" onClick={() => onChange?.('ja-JP')}>@@ -26,20 +19,11 @@ vi.mock('../_locale-menu', () => ({),}))-const mockUseSuspenseQuery = vi.mocked(useSuspenseQuery)const mockSetLocaleOnClient = vi.mocked(setLocaleOnClient)describe('Signin Header', () => {beforeEach(() => {vi.clearAllMocks()- mockUseSuspenseQuery.mockReturnValue({- data: {- branding: {- enabled: false,- login_page_logo: '',- },- },- } as ReturnType<typeof useSuspenseQuery>)})it('should switch locale without forcing a full page reload', () => {diff --git a/web/app/signin/__tests__/normal-form.spec.tsx b/web/app/signin/__tests__/normal-form.spec.tsxindex 5bbb2eb6529..5d36aa5ed38 100644--- a/web/app/signin/__tests__/normal-form.spec.tsx+++ b/web/app/signin/__tests__/normal-form.spec.tsx@@ -1,7 +1,8 @@-import { QueryClient, QueryClientProvider, useQuery, useSuspenseQuery } from '@tanstack/react-query'-import { render, screen, waitFor } from '@testing-library/react'+import { useQuery } from '@tanstack/react-query'+import { screen, waitFor } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'import { useRouter, useSearchParams } from '@/next/navigation'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import NormalForm from '../normal-form'vi.mock('@tanstack/react-query', async () => {@@ -10,7 +11,6 @@ vi.mock('@tanstack/react-query', async () => {return {...actual,useQuery: vi.fn(),- useSuspenseQuery: vi.fn(),}})@@ -22,13 +22,6 @@ vi.mock('@/features/account-profile/client', () => ({})),}))-vi.mock('@/features/system-features/client', () => ({- systemFeaturesQueryOptions: vi.fn(() => ({- queryKey: ['system-features'],- queryFn: vi.fn(),- })),-}))-vi.mock('@/next/navigation', () => ({useRouter: vi.fn(),useSearchParams: vi.fn(),@@ -44,7 +37,6 @@ vi.mock('@/service/common', async () => {const mockReplace = vi.fn()const mockUseQuery = vi.mocked(useQuery)-const mockUseSuspenseQuery = vi.mocked(useSuspenseQuery)const mockUseRouter = useRouter as unknown as ReturnType<typeof vi.fn>const mockUseSearchParams = useSearchParams as unknown as ReturnType<typeof vi.fn>@@ -93,22 +85,6 @@ describe('NormalForm', () => {vi.clearAllMocks()mockUseRouter.mockReturnValue({ replace: mockReplace })mockUseSearchParams.mockReturnValue(new URLSearchParams())- mockUseSuspenseQuery.mockReturnValue({- data: {- enable_social_oauth_login: false,- sso_enforced_for_signin: false,- enable_email_code_login: false,- enable_email_password_login: true,- is_email_setup: true,- is_allow_register: false,- license: {- status: 'none',- },- branding: {- enabled: true,- },- },- } as unknown as ReturnType<typeof useSuspenseQuery>)})describe('Default Redirects', () => {@@ -176,12 +152,7 @@ describe('NormalForm', () => {invitationQueryResult as unknown as ReturnType<typeof useQuery>,)- const queryClient = new QueryClient()- render(- <QueryClientProvider client={queryClient}>- <NormalForm />- </QueryClientProvider>,- )+ render(<NormalForm />)expect(screen.getByRole('button', { name: 'login.signBtn' })).toBeInTheDocument()expect(mockReplace).not.toHaveBeenCalled()@@ -221,29 +192,12 @@ describe('NormalForm', () => {nonInviteQueryResult as unknown as ReturnType<typeof useQuery>,nonInviteQueryResult as unknown as ReturnType<typeof useQuery>,)- mockUseSuspenseQuery.mockReturnValue({- data: {- enable_social_oauth_login: false,- sso_enforced_for_signin: false,- enable_email_code_login: false,- enable_email_password_login: true,- is_email_setup: true,+ render(<NormalForm />, {+ systemFeatures: {is_allow_register: true,- license: {- status: 'none',- },- branding: {- enabled: true,- },+ branding: { enabled: true },},- } as unknown as ReturnType<typeof useSuspenseQuery>)-- const queryClient = new QueryClient()- render(- <QueryClientProvider client={queryClient}>- <NormalForm />- </QueryClientProvider>,- )+ })expect(screen.getByRole('link', { name: 'login.signup.signUp' })).toHaveAttribute('href',diff --git a/web/app/signin/check-code/__tests__/page.spec.tsx b/web/app/signin/check-code/__tests__/page.spec.tsxindex de69fee5f04..b8c4f7f5fa1 100644--- a/web/app/signin/check-code/__tests__/page.spec.tsx+++ b/web/app/signin/check-code/__tests__/page.spec.tsx@@ -22,7 +22,6 @@ vi.mock('@/app/components/base/amplitude', () => ({vi.mock('@/config', async (importOriginal) => ({...(await importOriginal<typeof import('@/config')>()),- IS_CLOUD_EDITION: true,}))vi.mock('@/next/navigation', () => ({diff --git a/web/app/signin/normal-form.tsx b/web/app/signin/normal-form.tsxindex 6604d1d8786..3b7d296540a 100644--- a/web/app/signin/normal-form.tsx+++ b/web/app/signin/normal-form.tsx@@ -4,7 +4,6 @@ import { RiContractLine, RiDoorLockLine, RiErrorWarningFill } from '@remixicon/rimport { useQuery, useSuspenseQuery } from '@tanstack/react-query'import { useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'-import { IS_CE_EDITION } from '@/config'import { isLegacyBase401, userProfileQueryOptions } from '@/features/account-profile/client'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { LicenseStatus } from '@/features/system-features/constants'@@ -46,6 +45,9 @@ function NormalForm() {const message = decodeURIComponent(searchParams.get('message') || '')const inviteToken = decodeURIComponent(searchParams.get('invite_token') || '')const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())+ const isNonCloudEdition =+ systemFeatures.deployment_edition === 'COMMUNITY' ||+ systemFeatures.deployment_edition === 'ENTERPRISE'const [selectedAuthType, setSelectedAuthType] = useState<AuthType | null>(null)const isInviteLink = Boolean(inviteToken && inviteToken !== 'null')@@ -328,7 +330,7 @@ function NormalForm() {{t(($) => $.pp, { ns: 'login' })}</Link></div>- {IS_CE_EDITION && (+ {isNonCloudEdition && (<div className="w-hull mt-2 block system-xs-regular text-text-tertiary">{t(($) => $.goToInit, { ns: 'login' })} diff --git a/web/config/__tests__/index.spec.ts b/web/config/__tests__/index.spec.tsdeleted file mode 100644index 81f0df542f0..00000000000--- a/web/config/__tests__/index.spec.ts+++ /dev/null@@ -1,59 +0,0 @@-type DeploymentCase = {- edition: 'CLOUD' | 'SELF_HOSTED'- enterpriseEnabled: boolean- expected: {- isCloud: boolean- isCommunity: boolean- isSelfHosted: boolean- }-}--const loadConfig = async ({ edition, enterpriseEnabled }: DeploymentCase) => {- vi.resetModules()- vi.doMock('@/env', () => ({- env: {- NEXT_PUBLIC_EDITION: edition,- NEXT_PUBLIC_ENTERPRISE_ENABLED: enterpriseEnabled,- },- }))-- return import('../index')-}--describe('deployment edition config', () => {- afterEach(() => {- vi.doUnmock('@/env')- vi.resetModules()- })-- it.each<DeploymentCase>([- {- edition: 'CLOUD',- enterpriseEnabled: false,- expected: { isCloud: true, isCommunity: false, isSelfHosted: false },- },- {- edition: 'CLOUD',- enterpriseEnabled: true,- expected: { isCloud: true, isCommunity: false, isSelfHosted: false },- },- {- edition: 'SELF_HOSTED',- enterpriseEnabled: false,- expected: { isCloud: false, isCommunity: true, isSelfHosted: true },- },- {- edition: 'SELF_HOSTED',- enterpriseEnabled: true,- expected: { isCloud: false, isCommunity: false, isSelfHosted: true },- },- ])('derives flags for $edition with enterpriseEnabled=$enterpriseEnabled', async (deployment) => {- const config = await loadConfig(deployment)-- expect({- isCloud: config.IS_CLOUD_EDITION,- isCommunity: config.IS_COMMUNITY_EDITION,- isSelfHosted: config.IS_CE_EDITION,- }).toEqual(deployment.expected)- })-})diff --git a/web/config/index.ts b/web/config/index.tsindex 26cc9edfe40..c0787671415 100644--- a/web/config/index.ts+++ b/web/config/index.ts@@ -25,18 +25,10 @@ export const MARKETPLACE_API_PREFIX = getStringConfig()export const MARKETPLACE_URL_PREFIX = getStringConfig(env.NEXT_PUBLIC_MARKETPLACE_URL_PREFIX, '')-const EDITION = env.NEXT_PUBLIC_EDITION--export const IS_CE_EDITION = EDITION === 'SELF_HOSTED'-export const IS_CLOUD_EDITION = EDITION === 'CLOUD'-export const IS_COMMUNITY_EDITION = IS_CE_EDITION && !env.NEXT_PUBLIC_ENTERPRISE_ENABLED-export const AMPLITUDE_API_KEY = getStringConfig(env.NEXT_PUBLIC_AMPLITUDE_API_KEY, '')export const COOKIEYES_SITE_KEY = getStringConfig(env.NEXT_PUBLIC_COOKIEYES_SITE_KEY, '')export const WEB_PREFIX = env.NEXT_PUBLIC_WEB_PREFIX-export const isAmplitudeEnabled = IS_CLOUD_EDITION && !!AMPLITUDE_API_KEY-export const IS_DEV = process.env.NODE_ENV === 'development'export const IS_PROD = process.env.NODE_ENV === 'production'export const TONE_LIST = [@@ -113,7 +105,7 @@ export const PASSPORT_LOCAL_STORAGE_NAME = (appCode: string) => `passport-${appCexport const PASSPORT_HEADER_NAME = 'X-App-Passport'export const WEB_APP_SHARE_CODE_HEADER_NAME = 'X-App-Code'-export const zhRegex = /^[\u4E00-\u9FA5]$/m+const zhRegex = /^[\u4E00-\u9FA5]$/mexport const emailRegex = /^[\w.!#$%&'*+\-/=?^{|}~]+@([\w-]+\.)+[\w-]{2,}$/mconst MAX_ZN_VAR_NAME_LENGTH = 8const MAX_EN_VAR_VALUE_LENGTH = 30diff --git a/web/context/__tests__/console-bootstrap.spec.tsx b/web/context/__tests__/console-bootstrap.spec.tsxindex 765afba557c..986b3329048 100644--- a/web/context/__tests__/console-bootstrap.spec.tsx+++ b/web/context/__tests__/console-bootstrap.spec.tsx@@ -1,3 +1,4 @@+import type { GetSystemFeaturesResponse } from '@dify/contracts/api/console/system-features/types.gen'import type { ReactNode } from 'react'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'@@ -11,6 +12,7 @@ import { flushRegistrationSuccess } from '@/app/components/base/amplitude/registimport { setAnalyticsConsent } from '@/app/components/base/analytics-consent/consent-store'import { setZendeskConversationFields } from '@/app/components/base/zendesk/utils'import { ZENDESK_FIELD_IDS } from '@/config'+import { createSystemFeaturesFixture } from '@/test/console/system-features'import { refreshUserProfileAtom, userProfileAtom } from '../account-state'import { initialWorkspaceInfo } from '../app-context-defaults'import {@@ -79,11 +81,7 @@ const mockUserProfileResponseState = vi.hoisted(() => ({},}))const mockSystemFeaturesState = vi.hoisted(() => ({- data: {- branding: {- enabled: false,- },- },+ data: null as unknown as GetSystemFeaturesResponse,}))const mockLangGeniusVersionState = vi.hoisted(() => ({data: {@@ -122,13 +120,6 @@ vi.mock('@/config', async (importOriginal) => {}})-vi.mock('@/features/system-features/client', () => ({- systemFeaturesQueryOptions: () => ({- queryKey: ['system-features'],- queryFn: async () => mockSystemFeaturesState.data,- }),-}))-vi.mock('@/features/account-profile/client', () => ({userProfileQueryOptions: () => ({queryKey: ['user-profile'],@@ -138,6 +129,14 @@ vi.mock('@/features/account-profile/client', () => ({vi.mock('@/service/client', () => ({consoleQuery: {+ systemFeatures: {+ get: {+ queryOptions: () => ({+ queryKey: ['system-features'],+ queryFn: async () => mockSystemFeaturesState.data,+ }),+ },+ },workspaces: {current: {post: {@@ -341,11 +340,9 @@ describe('Console bootstrap', () => {currentEnv: 'cloud',},}- mockSystemFeaturesState.data = {- branding: {- enabled: false,- },- }+ mockSystemFeaturesState.data = createSystemFeaturesFixture({+ deployment_edition: 'CLOUD',+ })mockLangGeniusVersionState.data = {version: '1.0.1',release_date: '',@@ -461,32 +458,44 @@ describe('Console bootstrap', () => {renderConsoleBootstrap()await waitFor(() => {- expect(setZendeskConversationFields).toHaveBeenCalledWith([+ expect(setZendeskConversationFields).toHaveBeenCalledWith(+ [+ {+ id: ZENDESK_FIELD_IDS.ENVIRONMENT,+ value: 'cloud',+ },+ ],+ 'CLOUD',+ )+ })+ expect(setZendeskConversationFields).toHaveBeenCalledWith(+ [{- id: ZENDESK_FIELD_IDS.ENVIRONMENT,- value: 'cloud',+ id: ZENDESK_FIELD_IDS.VERSION,+ value: '1.0.1',},- ])- })- expect(setZendeskConversationFields).toHaveBeenCalledWith([- {- id: ZENDESK_FIELD_IDS.VERSION,- value: '1.0.1',- },- ])- expect(setZendeskConversationFields).toHaveBeenCalledWith([- {- id: ZENDESK_FIELD_IDS.EMAIL,- value: '[email protected]',- },- ])- await waitFor(() => {- expect(setZendeskConversationFields).toHaveBeenCalledWith([+ ],+ 'CLOUD',+ )+ expect(setZendeskConversationFields).toHaveBeenCalledWith(+ [{- id: ZENDESK_FIELD_IDS.WORKSPACE_ID,- value: 'workspace-1',+ id: ZENDESK_FIELD_IDS.EMAIL,+ value: '[email protected]',},- ])+ ],+ 'CLOUD',+ )+ await waitFor(() => {+ expect(setZendeskConversationFields).toHaveBeenCalledWith(+ [+ {+ id: ZENDESK_FIELD_IDS.WORKSPACE_ID,+ value: 'workspace-1',+ },+ ],+ 'CLOUD',+ )})await waitFor(() => {expect(setUserId).toHaveBeenCalledWith('[email protected]')diff --git a/web/context/hooks/use-trigger-events-limit-modal.ts b/web/context/hooks/use-trigger-events-limit-modal.tsindex 2ace70c4509..bb8bb02790e 100644--- a/web/context/hooks/use-trigger-events-limit-modal.ts+++ b/web/context/hooks/use-trigger-events-limit-modal.ts@@ -1,10 +1,11 @@import type { Dispatch, SetStateAction } from 'react'import type { ModalState } from '../modal-context'+import { useSuspenseQuery } from '@tanstack/react-query'import dayjs from 'dayjs'import { useCallback, useEffect, useRef, useState } from 'react'import { NUM_INFINITE } from '@/app/components/billing/config'import { Plan } from '@/app/components/billing/type'-import { IS_CLOUD_EDITION } from '@/config'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { isServer } from '@/utils/client'export type TriggerEventsLimitModalPayload = {@@ -43,12 +44,16 @@ export const useTriggerEventsLimitModal = ({isFetchedPlan,currentWorkspaceId,}: UseTriggerEventsLimitModalOptions): UseTriggerEventsLimitModalResult => {+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })const [showTriggerEventsLimitModal, setShowTriggerEventsLimitModal] =useState<ModalState<TriggerEventsLimitModalPayload> | null>(null)const dismissedTriggerEventsLimitStorageKeysRef = useRef<Record<string, boolean>>({})useEffect(() => {- if (!IS_CLOUD_EDITION) return+ if (deploymentEdition !== 'CLOUD') returnif (isServer) returnif (!currentWorkspaceId) returnif (!isFetchedPlan) {@@ -98,7 +103,7 @@ export const useTriggerEventsLimitModal = ({persistDismiss,},})- }, [plan, isFetchedPlan, showTriggerEventsLimitModal, currentWorkspaceId])+ }, [plan, isFetchedPlan, showTriggerEventsLimitModal, currentWorkspaceId, deploymentEdition])const persistTriggerEventsLimitModalDismiss = useCallback(() => {const storageKey = showTriggerEventsLimitModal?.payload.storageKeydiff --git a/web/context/i18n.spec.ts b/web/context/i18n.spec.tsindex c75b7bce279..496ac82b17e 100644--- a/web/context/i18n.spec.ts+++ b/web/context/i18n.spec.ts@@ -5,8 +5,8 @@ import { useTranslation } from '#i18n'import { getDocLanguage } from '@/i18n-config/language'import { defaultDocBaseUrl, useDocLink } from './i18n'-const mockConfig = vi.hoisted(() => ({- IS_CLOUD_EDITION: true,+const mockDeploymentEdition = vi.hoisted(() => ({+ value: 'CLOUD' as 'COMMUNITY' | 'ENTERPRISE' | 'CLOUD',}))// Mock dependencies@@ -16,10 +16,9 @@ vi.mock('#i18n', () => ({})),}))-vi.mock('@/config', () => ({- get IS_CLOUD_EDITION() {- return mockConfig.IS_CLOUD_EDITION- },+vi.mock('jotai', async (importOriginal) => ({+ ...(await importOriginal<typeof import('jotai')>()),+ useAtomValue: () => mockDeploymentEdition.value,}))vi.mock('@/i18n-config/language', () => ({@@ -38,7 +37,7 @@ vi.mock('@/i18n-config/language', () => ({describe('useDocLink', () => {beforeEach(() => {vi.clearAllMocks()- mockConfig.IS_CLOUD_EDITION = true+ mockDeploymentEdition.value = 'CLOUD'vi.mocked(useTranslation).mockReturnValue({i18n: { language: 'en-US' },} as ReturnType<typeof useTranslation>)@@ -150,7 +149,7 @@ describe('useDocLink', () => {describe('Product prefix handling', () => {it('should add cloud product prefix for product docs available in both editions', () => {- mockConfig.IS_CLOUD_EDITION = true+ mockDeploymentEdition.value = 'CLOUD'const { result } = renderHook(() => useDocLink())const url = result.current('/use-dify/workspace/tools#mcp')@@ -158,7 +157,7 @@ describe('useDocLink', () => {})it('should add self-host product prefix for product docs available in both editions outside cloud edition', () => {- mockConfig.IS_CLOUD_EDITION = false+ mockDeploymentEdition.value = 'COMMUNITY'const { result } = renderHook(() => useDocLink())const url = result.current('/use-dify/workspace/tools#mcp')@@ -166,7 +165,7 @@ describe('useDocLink', () => {})it('should use the existing cloud docs path for cloud-only product docs outside cloud edition', () => {- mockConfig.IS_CLOUD_EDITION = false+ mockDeploymentEdition.value = 'COMMUNITY'const { result } = renderHook(() => useDocLink())const url = result.current('/use-dify/workspace/subscription-management#dify-for-education')@@ -176,7 +175,7 @@ describe('useDocLink', () => {})it('should use the self-host Start node docs path outside cloud edition', () => {- mockConfig.IS_CLOUD_EDITION = false+ mockDeploymentEdition.value = 'COMMUNITY'const { result } = renderHook(() => useDocLink())const url = result.current('/use-dify/nodes/start')@@ -184,7 +183,7 @@ describe('useDocLink', () => {})it('should use the existing self-host docs path for self-host-only product docs in cloud edition', () => {- mockConfig.IS_CLOUD_EDITION = true+ mockDeploymentEdition.value = 'CLOUD'const { result } = renderHook(() => useDocLink())const url = result.current('/deploy/overview')@@ -192,7 +191,7 @@ describe('useDocLink', () => {})it('should not add a product prefix for unknown productless paths', () => {- mockConfig.IS_CLOUD_EDITION = false+ mockDeploymentEdition.value = 'COMMUNITY'const { result } = renderHook(() => useDocLink())const url = result.current('/use-dify/unknown-page' as DocPathWithoutLang)@@ -200,7 +199,7 @@ describe('useDocLink', () => {})it('should open shared docs home when no path is provided outside cloud edition', () => {- mockConfig.IS_CLOUD_EDITION = false+ mockDeploymentEdition.value = 'COMMUNITY'const { result } = renderHook(() => useDocLink())const url = result.current()@@ -208,7 +207,7 @@ describe('useDocLink', () => {})it('should keep self-host deploy paths without adding use-dify product prefix', () => {- mockConfig.IS_CLOUD_EDITION = true+ mockDeploymentEdition.value = 'CLOUD'const { result } = renderHook(() => useDocLink())const url = result.current('/self-host/deploy/overview' as DocPathWithoutLang)diff --git a/web/context/i18n.ts b/web/context/i18n.tsindex 6e172231eab..864660816bb 100644--- a/web/context/i18n.ts+++ b/web/context/i18n.ts@@ -1,8 +1,10 @@+import type { DeploymentEdition } from '@dify/contracts/api/console/system-features/types.gen'import type { Locale } from '@/i18n-config/language'import type { DocPathWithoutLang, DocsProduct } from '@/types/doc-paths'+import { useAtomValue } from 'jotai'import { useCallback } from 'react'import { useTranslation } from '#i18n'-import { IS_CLOUD_EDITION } from '@/config'+import { deploymentEditionAtom } from '@/context/system-features-state'import { getDocLanguage, getLanguage, getPricingPageLanguage } from '@/i18n-config/language'import { docPathProductAvailability } from '@/types/doc-paths'@@ -27,8 +29,9 @@ export type DocPathMap = Partial<Record<Locale, DocPathWithoutLang>>export const getDocHomePath = () => '/home'-const getCurrentDocsProduct = (): DocsProduct => {- return IS_CLOUD_EDITION ? 'cloud' : 'self-host'+const getCurrentDocsProduct = (deploymentEdition: DeploymentEdition): DocsProduct => {+ if (deploymentEdition === 'CLOUD') return 'cloud'+ return 'self-host'}const splitPathHash = (path: string) => {@@ -46,12 +49,12 @@ const splitPathHash = (path: string) => {}}-const getProductAwarePath = (path: string): string => {+const getProductAwarePath = (path: string, deploymentEdition: DeploymentEdition): string => {const { pathname, hash } = splitPathHash(path)const availableProducts = docPathProductAvailability[pathname]if (!availableProducts?.length) return path- const currentProduct = getCurrentDocsProduct()+ const currentProduct = getCurrentDocsProduct(deploymentEdition)const targetProduct = availableProducts.includes(currentProduct)? currentProduct: availableProducts[0]@@ -67,6 +70,7 @@ export const useDocLink = (let baseDocUrl = baseUrl || defaultDocBaseUrlbaseDocUrl = baseDocUrl.endsWith('/') ? baseDocUrl.slice(0, -1) : baseDocUrlconst locale = useLocale()+ const deploymentEdition = useAtomValue(deploymentEditionAtom)return useCallback((path?: DocPathWithoutLang, pathMap?: DocPathMap): string => {const docLanguage = getDocLanguage(locale)@@ -77,11 +81,11 @@ export const useDocLink = (if (!targetPath) {targetPath = getDocHomePath()} else {- targetPath = getProductAwarePath(targetPath)+ targetPath = getProductAwarePath(targetPath, deploymentEdition)}return `${baseDocUrl}${languagePrefix}${targetPath}`},- [baseDocUrl, locale],+ [baseDocUrl, deploymentEdition, locale],)}diff --git a/web/context/modal-context.test.tsx b/web/context/modal-context.test.tsxindex 2d4bfbc2c51..76f78ef43ab 100644--- a/web/context/modal-context.test.tsx+++ b/web/context/modal-context.test.tsx@@ -6,18 +6,12 @@ import { Plan } from '@/app/components/billing/type'import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'import { useModalContextSelector } from '@/context/modal-context'import { ModalContextProvider } from '@/context/modal-context-provider'-import { renderWithNuqs } from '@/test/nuqs-testing'+import { createConsoleQueryWrapper } from '@/test/console/query-data'+import { render } from '@/test/console/render'+import { createNuqsTestWrapper } from '@/test/nuqs-testing'const mockSetEducationVerifying = vi.hoisted(() => vi.fn())-vi.mock('@/config', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/config')>()- return {- ...actual,- IS_CLOUD_EDITION: true,- }-})-vi.mock('@/next/navigation', () => ({useRouter: () => ({push: vi.fn(),@@ -89,7 +83,19 @@ const createPlan = (overrides: PlanOverrides = {}): PlanShape => ({const renderProvider = (children: React.ReactNode = <div data-testid="modal-context-test-child" />,-) => renderWithNuqs(<ModalContextProvider>{children}</ModalContextProvider>)+) => {+ const { wrapper: QueryWrapper } = createConsoleQueryWrapper({+ systemFeatures: { deployment_edition: 'CLOUD' },+ })+ const { wrapper: NuqsWrapper } = createNuqsTestWrapper()+ const wrapper = ({ children: wrapperChildren }: { children: React.ReactNode }) => (+ <QueryWrapper>+ <NuqsWrapper>{wrapperChildren}</NuqsWrapper>+ </QueryWrapper>+ )++ return render(<ModalContextProvider>{children}</ModalContextProvider>, { wrapper })+}const AccountSettingOpener = () => {const setShowAccountSettingModal = useModalContextSelector(diff --git a/web/context/provider-context-provider.tsx b/web/context/provider-context-provider.tsxindex 93464d14c0c..60b7bc62ce6 100644--- a/web/context/provider-context-provider.tsx+++ b/web/context/provider-context-provider.tsx@@ -5,6 +5,7 @@ import type { ProviderContextState } from './provider-context'import { toast } from '@langgenius/dify-ui/toast'import { useQueryClient } from '@tanstack/react-query'import dayjs from 'dayjs'+import { useAtomValue } from 'jotai'import { useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'import { setZendeskConversationFields } from '@/app/components/base/zendesk/utils'@@ -16,6 +17,7 @@ import {ModelTypeEnum,} from '@/app/components/header/account-setting/model-provider-page/declarations'import { ZENDESK_FIELD_IDS } from '@/config'+import { deploymentEditionAtom } from '@/context/system-features-state'import { fetchCurrentPlanInfo } from '@/service/billing'import {useModelListByType,@@ -63,6 +65,7 @@ const resolveMemberInviteLimit = (}export const ProviderContextProvider = ({ children }: ProviderContextProviderProps) => {+ const deploymentEdition = useAtomValue(deploymentEditionAtom)const queryClient = useQueryClient()const { data: providersData, isLoading: isLoadingModelProviders } = useModelProviders()const { data: textGenerationModelList } = useModelListByType(ModelTypeEnum.textGeneration)@@ -149,14 +152,17 @@ export const ProviderContextProvider = ({ children }: ProviderContextProviderPro// #region Zendesk conversation fieldsuseEffect(() => {if (ZENDESK_FIELD_IDS.PLAN && plan.type) {- setZendeskConversationFields([- {- id: ZENDESK_FIELD_IDS.PLAN,- value: `${plan.type}-plan`,- },- ])+ setZendeskConversationFields(+ [+ {+ id: ZENDESK_FIELD_IDS.PLAN,+ value: `${plan.type}-plan`,+ },+ ],+ deploymentEdition,+ )}- }, [plan.type])+ }, [deploymentEdition, plan.type])// #endregion Zendesk conversation fieldsconst { t } = useTranslation()diff --git a/web/context/query-client.tsx b/web/context/query-client.tsxindex fe2c43ab06b..6d8e03e9723 100644--- a/web/context/query-client.tsx+++ b/web/context/query-client.tsx@@ -1,7 +1,8 @@'use client'import type { QueryClient } from '@tanstack/react-query'-import { QueryClientProvider } from '@tanstack/react-query'+import type { ReactNode } from 'react'+import { QueryClientProvider, QueryErrorResetBoundary } from '@tanstack/react-query'import { queryClientAtom } from 'jotai-tanstack-query'import { useHydrateAtoms } from 'jotai/react/utils'import { isServer } from '@/utils/client'@@ -17,20 +18,22 @@ function getQueryClient() {return browserQueryClient}-export const TanstackQueryInitializer = ({ children }: { children: React.ReactNode }) => {+export function TanStackQueryProvider({ children }: { children: ReactNode }) {const queryClient = getQueryClient()return (<QueryClientProvider client={queryClient}>- <HydrateJotaiQueryClient queryClient={queryClient}>{children}</HydrateJotaiQueryClient>+ <QueryErrorResetBoundary>+ <JotaiQueryClientHydrator queryClient={queryClient}>{children}</JotaiQueryClientHydrator>+ </QueryErrorResetBoundary></QueryClientProvider>)}-function HydrateJotaiQueryClient({+function JotaiQueryClientHydrator({children,queryClient,}: {- children: React.ReactNode+ children: ReactNodequeryClient: QueryClient}) {useHydrateAtoms(new Map([[queryClientAtom, queryClient]]))diff --git a/web/context/system-features-state.ts b/web/context/system-features-state.tsindex 25eb9115a57..2b6929dd862 100644--- a/web/context/system-features-state.ts+++ b/web/context/system-features-state.ts@@ -6,10 +6,14 @@ import { atomWithResolvedSuspenseQuery } from '@/utils/query-atoms'const systemFeaturesQueryAtom = atomWithResolvedSuspenseQuery(() => systemFeaturesQueryOptions())-export const systemFeaturesAtom = atom((get) => {+const systemFeaturesAtom = atom((get) => {return get(systemFeaturesQueryAtom).data})-export const datasetRbacEnabledAtom = atom((get) => {- return get(systemFeaturesAtom).rbac_enabled+export const deploymentEditionAtom = atom((get) => {+ return get(systemFeaturesAtom).deployment_edition+})++export const brandingEnabledAtom = atom((get) => {+ return get(systemFeaturesAtom).branding.enabled})diff --git a/web/context/version-state.ts b/web/context/version-state.tsindex 8a4242f805d..4568bc3d77c 100644--- a/web/context/version-state.ts+++ b/web/context/version-state.ts@@ -6,12 +6,12 @@ import { consoleQuery } from '@/service/client'import { accountProfileMetaAtom } from './account-state'import { initialLangGeniusVersionInfo } from './app-context-defaults'import { getLangGeniusVersionInfo } from './app-context-normalizers'-import { systemFeaturesAtom } from './system-features-state'+import { brandingEnabledAtom } from './system-features-state'const versionQueryAtom = atomWithQuery((get) => {const meta = get(accountProfileMetaAtom)- const systemFeatures = get(systemFeaturesAtom)- const enabled = Boolean(meta.currentVersion && !systemFeatures.branding.enabled)+ const brandingEnabled = get(brandingEnabledAtom)+ const enabled = Boolean(meta.currentVersion && !brandingEnabled)return consoleQuery.version.get.queryOptions({input: {diff --git a/web/context/web-app-context.tsx b/web/context/web-app-context.tsxindex 2c9f26b5a79..2197c025cef 100644--- a/web/context/web-app-context.tsx+++ b/web/context/web-app-context.tsx@@ -3,7 +3,7 @@import type { FC, PropsWithChildren } from 'react'import type { ChatConfig } from '@/app/components/base/chat/types'import type { AppData, AppMeta } from '@/models/share'-import { useQuery } from '@tanstack/react-query'+import { useSuspenseQuery } from '@tanstack/react-query'import { useEffect } from 'react'import { create } from 'zustand'import {@@ -67,7 +67,7 @@ const getShareCodeFromPathname = (pathname: string): string | null => {}const WebAppStoreProvider: FC<PropsWithChildren> = ({ children }) => {- const { isPending: isGlobalPending } = useQuery(systemFeaturesQueryOptions())+ useSuspenseQuery(systemFeaturesQueryOptions())const updateWebAppAccessMode = useWebAppStore((state) => state.updateWebAppAccessMode)const updateShareCode = useWebAppStore((state) => state.updateShareCode)const updateEmbeddedUserId = useWebAppStore((state) => state.updateEmbeddedUserId)@@ -113,7 +113,7 @@ const WebAppStoreProvider: FC<PropsWithChildren> = ({ children }) => {if (accessModeResult?.accessMode) updateWebAppAccessMode(accessModeResult.accessMode)}, [accessModeResult, updateWebAppAccessMode, shareCode])- if (isGlobalPending || isLoading) {+ if (isLoading) {return (<div className="flex size-full items-center justify-center"><Loading />diff --git a/web/context/zendesk-conversation-sync.ts b/web/context/zendesk-conversation-sync.tsindex b43e2909922..072dedb1b7d 100644--- a/web/context/zendesk-conversation-sync.ts+++ b/web/context/zendesk-conversation-sync.ts@@ -1,10 +1,12 @@'use client'+import type { DeploymentEdition } from '@dify/contracts/api/console/system-features/types.gen'import { atom } from 'jotai'import { atomEffect } from 'jotai-effect'import { setZendeskConversationFields } from '@/app/components/base/zendesk/utils'import { ZENDESK_FIELD_IDS } from '@/config'import { userProfileAtom } from './account-state'+import { deploymentEditionAtom } from './system-features-state'import { langGeniusVersionInfoAtom } from './version-state'import { currentWorkspaceAtom } from './workspace-state'@@ -19,23 +21,28 @@ const zendeskConversationSyncStateAtom = atom<ZendeskSyncState>({})function syncZendeskField({fieldId,+ deploymentEdition,previousValue,setNextValue,value,}: {fieldId: string | undefined+ deploymentEdition: DeploymentEditionpreviousValue: string | undefinedsetNextValue: (value: string) => voidvalue: string}) {- if (!fieldId || !value || value === previousValue) return false+ if (deploymentEdition !== 'CLOUD' || !fieldId || !value || value === previousValue) return false- setZendeskConversationFields([- {- id: fieldId,- value,- },- ])+ setZendeskConversationFields(+ [+ {+ id: fieldId,+ value,+ },+ ],+ deploymentEdition,+ )setNextValue(value)return true@@ -45,6 +52,7 @@ export const zendeskConversationSyncAtom = atomEffect((get, set) => {const userProfile = get(userProfileAtom)const currentWorkspace = get(currentWorkspaceAtom)const langGeniusVersionInfo = get(langGeniusVersionInfoAtom)+ const deploymentEdition = get(deploymentEditionAtom)const state = get.peek(zendeskConversationSyncStateAtom)const nextState = { ...state }@@ -52,6 +60,7 @@ export const zendeskConversationSyncAtom = atomEffect((get, set) => {didSync =syncZendeskField({fieldId: ZENDESK_FIELD_IDS.ENVIRONMENT,+ deploymentEdition,value: langGeniusVersionInfo.current_env.toLowerCase(),previousValue: state.environment,setNextValue: (value) => {@@ -61,6 +70,7 @@ export const zendeskConversationSyncAtom = atomEffect((get, set) => {didSync =syncZendeskField({fieldId: ZENDESK_FIELD_IDS.VERSION,+ deploymentEdition,value: langGeniusVersionInfo.version,previousValue: state.version,setNextValue: (value) => {@@ -70,6 +80,7 @@ export const zendeskConversationSyncAtom = atomEffect((get, set) => {didSync =syncZendeskField({fieldId: ZENDESK_FIELD_IDS.EMAIL,+ deploymentEdition,value: userProfile.email,previousValue: state.email,setNextValue: (value) => {@@ -79,6 +90,7 @@ export const zendeskConversationSyncAtom = atomEffect((get, set) => {didSync =syncZendeskField({fieldId: ZENDESK_FIELD_IDS.WORKSPACE_ID,+ deploymentEdition,value: currentWorkspace.id,previousValue: state.workspaceId,setNextValue: (value) => {diff --git a/web/docker/entrypoint.sh b/web/docker/entrypoint.shindex 205748a2aed..e600b6cd4de 100755--- a/web/docker/entrypoint.sh+++ b/web/docker/entrypoint.sh@@ -13,8 +13,6 @@set -eexport NEXT_PUBLIC_DEPLOY_ENV=${DEPLOY_ENV}-export NEXT_PUBLIC_EDITION=${EDITION}-export NEXT_PUBLIC_ENTERPRISE_ENABLED=${NEXT_PUBLIC_ENTERPRISE_ENABLED:-${ENTERPRISE_ENABLED}}export NEXT_PUBLIC_BASE_PATH=${NEXT_PUBLIC_BASE_PATH}export NEXT_PUBLIC_API_PREFIX=${CONSOLE_API_URL}/console/apiexport NEXT_PUBLIC_PUBLIC_API_PREFIX=${APP_API_URL}/api@@ -31,23 +29,6 @@ export NEXT_TELEMETRY_DISABLED=${NEXT_TELEMETRY_DISABLED}export NEXT_PUBLIC_AMPLITUDE_API_KEY=${AMPLITUDE_API_KEY}export NEXT_PUBLIC_COOKIEYES_SITE_KEY=${NEXT_PUBLIC_COOKIEYES_SITE_KEY:-${COOKIEYES_SITE_KEY}}-# Cloud system-features frontend defaults.-# These values are only used when EDITION=CLOUD (IS_CLOUD_EDITION).-export NEXT_PUBLIC_ENABLE_MARKETPLACE=${NEXT_PUBLIC_ENABLE_MARKETPLACE:-${MARKETPLACE_ENABLED}}-export NEXT_PUBLIC_ENABLE_EMAIL_CODE_LOGIN=${NEXT_PUBLIC_ENABLE_EMAIL_CODE_LOGIN:-${ENABLE_EMAIL_CODE_LOGIN}}-export NEXT_PUBLIC_ENABLE_EMAIL_PASSWORD_LOGIN=${NEXT_PUBLIC_ENABLE_EMAIL_PASSWORD_LOGIN:-${ENABLE_EMAIL_PASSWORD_LOGIN}}-export NEXT_PUBLIC_ENABLE_SOCIAL_OAUTH_LOGIN=${NEXT_PUBLIC_ENABLE_SOCIAL_OAUTH_LOGIN:-${ENABLE_SOCIAL_OAUTH_LOGIN}}-export NEXT_PUBLIC_ENABLE_COLLABORATION_MODE=${NEXT_PUBLIC_ENABLE_COLLABORATION_MODE:-${ENABLE_COLLABORATION_MODE}}-export NEXT_PUBLIC_ALLOW_REGISTER=${NEXT_PUBLIC_ALLOW_REGISTER:-${ALLOW_REGISTER}}-export NEXT_PUBLIC_ALLOW_CREATE_WORKSPACE=${NEXT_PUBLIC_ALLOW_CREATE_WORKSPACE:-${ALLOW_CREATE_WORKSPACE}}-export NEXT_PUBLIC_IS_EMAIL_SETUP=${NEXT_PUBLIC_IS_EMAIL_SETUP:-${IS_EMAIL_SETUP}}-export NEXT_PUBLIC_ENABLE_CHANGE_EMAIL=${NEXT_PUBLIC_ENABLE_CHANGE_EMAIL:-${ENABLE_CHANGE_EMAIL}}-export NEXT_PUBLIC_CREATORS_PLATFORM_FEATURES_ENABLED=${NEXT_PUBLIC_CREATORS_PLATFORM_FEATURES_ENABLED:-${CREATORS_PLATFORM_FEATURES_ENABLED}}-export NEXT_PUBLIC_ENABLE_TRIAL_APP=${NEXT_PUBLIC_ENABLE_TRIAL_APP:-${ENABLE_TRIAL_APP}}-export NEXT_PUBLIC_ENABLE_EXPLORE_BANNER=${NEXT_PUBLIC_ENABLE_EXPLORE_BANNER:-${ENABLE_EXPLORE_BANNER}}-export NEXT_PUBLIC_ENABLE_LEARN_APP=${NEXT_PUBLIC_ENABLE_LEARN_APP:-${ENABLE_LEARN_APP}}-export NEXT_PUBLIC_RBAC_ENABLED=${NEXT_PUBLIC_RBAC_ENABLED:-${RBAC_ENABLED}}-export NEXT_PUBLIC_TEXT_GENERATION_TIMEOUT_MS=${TEXT_GENERATION_TIMEOUT_MS}export NEXT_PUBLIC_WORKFLOW_GENERATION_TIMEOUT_MS=${NEXT_PUBLIC_WORKFLOW_GENERATION_TIMEOUT_MS:-${WORKFLOW_GENERATION_TIMEOUT_MS}}export NEXT_PUBLIC_CSP_WHITELIST=${CSP_WHITELIST}diff --git a/web/env.ts b/web/env.tsindex fdd7e6a0577..330bf7b3080 100644--- a/web/env.ts+++ b/web/env.ts@@ -71,10 +71,6 @@ const clientSchema = {*/NEXT_PUBLIC_DEPLOY_ENV: z.enum(['DEVELOPMENT', 'PRODUCTION', 'TESTING']).optional(),NEXT_PUBLIC_DISABLE_UPLOAD_IMAGE_AS_ICON: coercedBoolean.default(false),- /**- * The deployment edition, SELF_HOSTED- */- NEXT_PUBLIC_EDITION: z.enum(['SELF_HOSTED', 'CLOUD']).default('SELF_HOSTED'),NEXT_PUBLIC_ENABLE_AGENT_V2: coercedBoolean.default(false),/*** Enable preview features that are still in development.@@ -82,32 +78,6 @@ const clientSchema = {* "Go to Anything" command palette (Cmd/Ctrl+K).*/NEXT_PUBLIC_ENABLE_FEATURE_PREVIEW: coercedBoolean.default(true),- /**- * Whether a self-hosted deployment runs Enterprise Edition.- */- NEXT_PUBLIC_ENTERPRISE_ENABLED: coercedBoolean.default(false),-- /**- * Cloud-only system-features defaults.- * These values are only used when NEXT_PUBLIC_EDITION=CLOUD (IS_CLOUD_EDITION).- */- NEXT_PUBLIC_ENABLE_MARKETPLACE: coercedBoolean.default(true),- NEXT_PUBLIC_ENABLE_EMAIL_CODE_LOGIN: coercedBoolean.default(true),- NEXT_PUBLIC_ENABLE_EMAIL_PASSWORD_LOGIN: coercedBoolean.default(false),- NEXT_PUBLIC_ENABLE_SOCIAL_OAUTH_LOGIN: coercedBoolean.default(true),- NEXT_PUBLIC_ENABLE_COLLABORATION_MODE: coercedBoolean.default(false),- NEXT_PUBLIC_ALLOW_REGISTER: coercedBoolean.default(true),- NEXT_PUBLIC_ALLOW_CREATE_WORKSPACE: coercedBoolean.default(true),- NEXT_PUBLIC_IS_EMAIL_SETUP: coercedBoolean.default(true),- NEXT_PUBLIC_KNOWLEDGE_FS_ENABLED: coercedBoolean.default(false),- NEXT_PUBLIC_ENABLE_CHANGE_EMAIL: coercedBoolean.default(true),- NEXT_PUBLIC_CREATORS_PLATFORM_FEATURES_ENABLED: coercedBoolean.default(true),- NEXT_PUBLIC_ENABLE_TRIAL_APP: coercedBoolean.default(true),- NEXT_PUBLIC_ENABLE_EXPLORE_BANNER: coercedBoolean.default(true),- NEXT_PUBLIC_ENABLE_LEARN_APP: coercedBoolean.default(true),- NEXT_PUBLIC_ENABLE_STEP_BY_STEP_TOUR: coercedBoolean.default(true),- NEXT_PUBLIC_RBAC_ENABLED: coercedBoolean.default(false),-/*** Enable inline LaTeX rendering with single dollar signs ($...$)* Default is false for security reasons to prevent conflicts with regular text@@ -249,72 +219,12 @@ export const env = createEnv({NEXT_PUBLIC_DISABLE_UPLOAD_IMAGE_AS_ICON: isServer? process.env.NEXT_PUBLIC_DISABLE_UPLOAD_IMAGE_AS_ICON: getRuntimeEnvFromBody('disableUploadImageAsIcon'),- NEXT_PUBLIC_EDITION: isServer- ? process.env.NEXT_PUBLIC_EDITION- : getRuntimeEnvFromBody('edition'),NEXT_PUBLIC_ENABLE_AGENT_V2: isServer? process.env.NEXT_PUBLIC_ENABLE_AGENT_V2: getRuntimeEnvFromBody('enableAgentV2'),NEXT_PUBLIC_ENABLE_FEATURE_PREVIEW: isServer? process.env.NEXT_PUBLIC_ENABLE_FEATURE_PREVIEW: getRuntimeEnvFromBody('enableFeaturePreview'),- NEXT_PUBLIC_ENTERPRISE_ENABLED: isServer- ? process.env.NEXT_PUBLIC_ENTERPRISE_ENABLED- : getRuntimeEnvFromBody('enterpriseEnabled'),-- /**- * Cloud-only system-features defaults.- * These values are only used when NEXT_PUBLIC_EDITION=CLOUD (IS_CLOUD_EDITION).- */- NEXT_PUBLIC_ENABLE_MARKETPLACE: isServer- ? process.env.NEXT_PUBLIC_ENABLE_MARKETPLACE- : getRuntimeEnvFromBody('enableMarketplace'),- NEXT_PUBLIC_ENABLE_EMAIL_CODE_LOGIN: isServer- ? process.env.NEXT_PUBLIC_ENABLE_EMAIL_CODE_LOGIN- : getRuntimeEnvFromBody('enableEmailCodeLogin'),- NEXT_PUBLIC_ENABLE_EMAIL_PASSWORD_LOGIN: isServer- ? process.env.NEXT_PUBLIC_ENABLE_EMAIL_PASSWORD_LOGIN- : getRuntimeEnvFromBody('enableEmailPasswordLogin'),- NEXT_PUBLIC_ENABLE_SOCIAL_OAUTH_LOGIN: isServer- ? process.env.NEXT_PUBLIC_ENABLE_SOCIAL_OAUTH_LOGIN- : getRuntimeEnvFromBody('enableSocialOauthLogin'),- NEXT_PUBLIC_ENABLE_COLLABORATION_MODE: isServer- ? process.env.NEXT_PUBLIC_ENABLE_COLLABORATION_MODE- : getRuntimeEnvFromBody('enableCollaborationMode'),- NEXT_PUBLIC_ALLOW_REGISTER: isServer- ? process.env.NEXT_PUBLIC_ALLOW_REGISTER- : getRuntimeEnvFromBody('allowRegister'),- NEXT_PUBLIC_ALLOW_CREATE_WORKSPACE: isServer- ? process.env.NEXT_PUBLIC_ALLOW_CREATE_WORKSPACE- : getRuntimeEnvFromBody('allowCreateWorkspace'),- NEXT_PUBLIC_IS_EMAIL_SETUP: isServer- ? process.env.NEXT_PUBLIC_IS_EMAIL_SETUP- : getRuntimeEnvFromBody('isEmailSetup'),- NEXT_PUBLIC_KNOWLEDGE_FS_ENABLED: isServer- ? process.env.NEXT_PUBLIC_KNOWLEDGE_FS_ENABLED- : getRuntimeEnvFromBody('knowledgeFsEnabled'),- NEXT_PUBLIC_ENABLE_CHANGE_EMAIL: isServer- ? process.env.NEXT_PUBLIC_ENABLE_CHANGE_EMAIL- : getRuntimeEnvFromBody('enableChangeEmail'),- NEXT_PUBLIC_CREATORS_PLATFORM_FEATURES_ENABLED: isServer- ? process.env.NEXT_PUBLIC_CREATORS_PLATFORM_FEATURES_ENABLED- : getRuntimeEnvFromBody('creatorsPlatformFeaturesEnabled'),- NEXT_PUBLIC_ENABLE_TRIAL_APP: isServer- ? process.env.NEXT_PUBLIC_ENABLE_TRIAL_APP- : getRuntimeEnvFromBody('enableTrialApp'),- NEXT_PUBLIC_ENABLE_EXPLORE_BANNER: isServer- ? process.env.NEXT_PUBLIC_ENABLE_EXPLORE_BANNER- : getRuntimeEnvFromBody('enableExploreBanner'),- NEXT_PUBLIC_ENABLE_LEARN_APP: isServer- ? process.env.NEXT_PUBLIC_ENABLE_LEARN_APP- : getRuntimeEnvFromBody('enableLearnApp'),- NEXT_PUBLIC_ENABLE_STEP_BY_STEP_TOUR: isServer- ? process.env.NEXT_PUBLIC_ENABLE_STEP_BY_STEP_TOUR- : getRuntimeEnvFromBody('enableStepByStepTour'),- NEXT_PUBLIC_RBAC_ENABLED: isServer- ? process.env.NEXT_PUBLIC_RBAC_ENABLED- : getRuntimeEnvFromBody('rbacEnabled'),-NEXT_PUBLIC_ENABLE_SINGLE_DOLLAR_LATEX: isServer? process.env.NEXT_PUBLIC_ENABLE_SINGLE_DOLLAR_LATEX: getRuntimeEnvFromBody('enableSingleDollarLatex'),diff --git a/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-cards.spec.tsx b/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-cards.spec.tsxindex e24852eec40..f8095df4d2c 100644--- a/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-cards.spec.tsx+++ b/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-cards.spec.tsx@@ -127,6 +127,10 @@ vi.mock('@/service/client', () => ({systemFeatures: {get: {queryKey: () => ['system-features'],+ queryOptions: (options: Record<string, unknown> = {}) => ({+ queryKey: ['system-features'],+ ...options,+ }),},},apps: {diff --git a/web/features/agent-v2/agent-detail/configure/__tests__/page.spec.tsx b/web/features/agent-v2/agent-detail/configure/__tests__/page.spec.tsxindex 00418b9b62a..1f64a7613f1 100644--- a/web/features/agent-v2/agent-detail/configure/__tests__/page.spec.tsx+++ b/web/features/agent-v2/agent-detail/configure/__tests__/page.spec.tsx@@ -78,7 +78,7 @@ const modelHooksState = vi.hoisted(() => ({}))const editionState = vi.hoisted(() => ({- isSelfHosted: false,+ deploymentEdition: 'CLOUD' as 'CLOUD' | 'COMMUNITY' | 'ENTERPRISE',licenseStatus: 'none',}))@@ -151,8 +151,9 @@ vi.mock('@tanstack/react-query', async (importOriginal) => {if (queryKey === 'system-features') {return {data: {+ deployment_edition: editionState.deploymentEdition,license: {- status: editionState.licenseStatus,+ status: 'none',},},isPending: false,@@ -167,13 +168,25 @@ vi.mock('@tanstack/react-query', async (importOriginal) => {isSuccess: false,}}),- useSuspenseQuery: vi.fn(() => ({- data: {- license: {- status: editionState.licenseStatus,- },+ useSuspenseQuery: vi.fn(+ (options: {+ select?: (data: {+ deployment_edition: 'CLOUD' | 'COMMUNITY' | 'ENTERPRISE'+ license: { status: string }+ }) => unknown+ }) => {+ const data = {+ deployment_edition: editionState.deploymentEdition,+ license: {+ status: editionState.licenseStatus,+ },+ }++ return {+ data: options.select ? options.select(data) : data,+ }},- })),+ ),}})@@ -181,22 +194,12 @@ vi.mock('@langgenius/dify-ui/toast', () => ({toast: toastMock,}))-vi.mock('@/config', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/config')>()-- return {- ...actual,- get IS_CE_EDITION() {- return editionState.isSelfHosted- },- }-})-vi.mock('@/service/client', () => ({consoleQuery: {systemFeatures: {get: {queryKey: () => ['system-features'],+ queryOptions: () => ({ queryKey: ['system-features'] }),},},agent: {@@ -523,7 +526,7 @@ describe('AgentConfigurePage', () => {beforeEach(() => {vi.clearAllMocks()mocks.completeBuildConversation = undefined- editionState.isSelfHosted = false+ editionState.deploymentEdition = 'CLOUD'editionState.licenseStatus = 'none'modelHooksState.defaultTextGenerationModel = {provider: {@@ -1572,7 +1575,7 @@ describe('AgentConfigurePage', () => {})it('should keep preview disabled in community edition', () => {- editionState.isSelfHosted = true+ editionState.deploymentEdition = 'COMMUNITY'mocks.queryState.composer = {data: {},isFetching: false,@@ -1595,9 +1598,9 @@ describe('AgentConfigurePage', () => {)})- it('should enable preview for a self-hosted enterprise license', () => {- editionState.isSelfHosted = true- editionState.licenseStatus = 'active'+ it('should enable preview in enterprise edition regardless of license status', () => {+ editionState.deploymentEdition = 'ENTERPRISE'+ editionState.licenseStatus = 'lost'mocks.queryState.composer = {data: {},isFetching: false,diff --git a/web/features/agent-v2/agent-detail/configure/components/__tests__/community-edition-tip.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/__tests__/community-edition-tip.spec.tsxindex 57b64bc79af..f41feb4a1dd 100644--- a/web/features/agent-v2/agent-detail/configure/components/__tests__/community-edition-tip.spec.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/__tests__/community-edition-tip.spec.tsx@@ -1,33 +1,26 @@-import { render, screen } from '@testing-library/react'+import { screen } from '@testing-library/react'+import { renderWithConsoleQuery } from '@/test/console/query-data'import { CommunityEditionTip } from '../community-edition-tip'-const edition = vi.hoisted(() => ({ isCommunity: true }))--vi.mock('@/config', async (importOriginal) => ({- ...(await importOriginal<typeof import('@/config')>()),- get IS_COMMUNITY_EDITION() {- return edition.isCommunity- },-}))-const tip = 'sandbox runs as a non-root user'describe('CommunityEditionTip', () => {it('shows the warning on community edition (self-hosted, non-enterprise)', () => {- edition.isCommunity = true-- render(<CommunityEditionTip tip={tip} />)+ renderWithConsoleQuery(<CommunityEditionTip tip={tip} />, {+ systemFeatures: { deployment_edition: 'COMMUNITY' },+ })expect(screen.getByLabelText(tip)).toBeInTheDocument()})- it('renders nothing on an enterprise or cloud deployment', () => {- // Sandbox isolation is a property of the community build, so the tip is- // gated on edition alone — not on license or billing state.- edition.isCommunity = false+ it.each(['ENTERPRISE', 'CLOUD'] as const)(+ 'renders nothing when deployment edition is %s',+ (deploymentEdition) => {+ renderWithConsoleQuery(<CommunityEditionTip tip={tip} />, {+ systemFeatures: { deployment_edition: deploymentEdition },+ })- render(<CommunityEditionTip tip={tip} />)-- expect(screen.queryByLabelText(tip)).not.toBeInTheDocument()- })+ expect(screen.queryByLabelText(tip)).not.toBeInTheDocument()+ },+ )})diff --git a/web/features/agent-v2/agent-detail/configure/components/community-edition-tip.tsx b/web/features/agent-v2/agent-detail/configure/components/community-edition-tip.tsxindex 074faaf1a40..12e3a435a16 100644--- a/web/features/agent-v2/agent-detail/configure/components/community-edition-tip.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/community-edition-tip.tsx@@ -3,7 +3,8 @@import type { Placement } from '@langgenius/dify-ui/popover'import { cn } from '@langgenius/dify-ui/cn'import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'-import { IS_COMMUNITY_EDITION } from '@/config'+import { useSuspenseQuery } from '@tanstack/react-query'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'type CommunityEditionTipProps = {tip: string@@ -21,7 +22,12 @@ export function CommunityEditionTip({placement = 'bottom',popupClassName,}: CommunityEditionTipProps) {- if (!IS_COMMUNITY_EDITION) return null+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: ({ deployment_edition }) => deployment_edition,+ })++ if (deploymentEdition !== 'COMMUNITY') return nullreturn (<Popover>diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/__tests__/index.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/__tests__/index.spec.tsxindex 8d2a1b5546e..4c036deed2b 100644--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/__tests__/index.spec.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/__tests__/index.spec.tsx@@ -2,7 +2,7 @@ import type { AgentSoulConfig } from '@dify/contracts/api/console/agent/types.geimport type { AgentConfigApiContext } from '../../config-context'import type { AgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'import { toast } from '@langgenius/dify-ui/toast'-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { QueryClient } from '@tanstack/react-query'import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { useAtomValue } from 'jotai'@@ -11,6 +11,8 @@ import { formStateToAgentSoulConfig } from '@/features/agent-v2/agent-composer/cimport { defaultAgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'import { AgentComposerProvider } from '@/features/agent-v2/agent-composer/provider'import { agentComposerDraftAtom } from '@/features/agent-v2/agent-composer/store'+import { QueryClientTestProvider } from '@/test/console/query-provider'+import { createSystemFeaturesFixture } from '@/test/console/system-features'import { AgentConfigApiContextProvider } from '../../config-context'import { AgentOrchestrateReadOnlyContext } from '../../read-only-context'import { AgentFiles } from '../index'@@ -60,6 +62,16 @@ vi.mock('@/utils/download', () => ({vi.mock('@/service/client', () => ({consoleQuery: {+ systemFeatures: {+ get: {+ queryKey: () => ['console', 'systemFeatures', 'get'],+ queryOptions: (options?: Record<string, unknown>) => ({+ queryKey: ['console', 'systemFeatures', 'get'],+ queryFn: () => new Promise(() => {}),+ ...options,+ }),+ },+ },agent: {byAgentId: {config: {@@ -173,9 +185,13 @@ function renderAgentFiles({mutations: { retry: false },},})+ queryClient.setQueryData(+ ['console', 'systemFeatures', 'get'],+ createSystemFeaturesFixture({ deployment_edition: 'COMMUNITY' }),+ )return render(- <QueryClientProvider client={queryClient}>+ <QueryClientTestProvider queryClient={queryClient}><AgentConfigApiContextProvider value={apiContext}><AgentComposerProviderinitialDraft={initialDraft}@@ -187,7 +203,7 @@ function renderAgentFiles({</AgentOrchestrateReadOnlyContext></AgentComposerProvider></AgentConfigApiContextProvider>- </QueryClientProvider>,+ </QueryClientTestProvider>,)}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/__tests__/index.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/__tests__/index.spec.tsxindex a39b96f55d8..a4ad8009e6f 100644--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/__tests__/index.spec.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/__tests__/index.spec.tsx@@ -1,5 +1,4 @@import type { AgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { fireEvent, screen, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { useAtomValue } from 'jotai'@@ -10,7 +9,7 @@ import { defaultAgentSoulConfigFormState } from '@/features/agent-v2/agent-compoimport { AgentComposerProvider } from '@/features/agent-v2/agent-composer/provider'import { agentComposerDraftAtom } from '@/features/agent-v2/agent-composer/store'import { RerankingModeEnum } from '@/models/datasets'-import { renderWithAccountProfile as render } from '@/test/console/account-profile'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { AgentOrchestrateReadOnlyContext } from '../../read-only-context'import { AgentKnowledgeRetrieval } from '../index'@@ -114,17 +113,13 @@ function renderKnowledgeRetrieval({readOnly?: booleanshowConfigSnapshot?: boolean} = {}) {- const queryClient = new QueryClient()-return render(- <QueryClientProvider client={queryClient}>- <AgentComposerProvider initialDraft={initialDraft}>- <AgentOrchestrateReadOnlyContext value={readOnly}>- <AgentKnowledgeRetrieval />- </AgentOrchestrateReadOnlyContext>- {showConfigSnapshot && <ConfigSnapshotPreview />}- </AgentComposerProvider>- </QueryClientProvider>,+ <AgentComposerProvider initialDraft={initialDraft}>+ <AgentOrchestrateReadOnlyContext value={readOnly}>+ <AgentKnowledgeRetrieval />+ </AgentOrchestrateReadOnlyContext>+ {showConfigSnapshot && <ConfigSnapshotPreview />}+ </AgentComposerProvider>,)}diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/chat.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/chat.spec.tsxindex 886d6c1ce54..dfb547a04c5 100644--- a/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/chat.spec.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/chat.spec.tsx@@ -28,17 +28,13 @@ const sendResultRef = vi.hoisted(() => ({const chatMessagesGetMock = vi.hoisted(() => vi.fn())const suggestedQuestionsGetMock = vi.hoisted(() => vi.fn())const stopPostMock = vi.hoisted(() => vi.fn())-const editionState = vi.hoisted(() => ({ isCommunity: true }))--vi.mock('@/config', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/config')>()+const mockConsoleState = vi.hoisted(() => ({+ deploymentEdition: 'COMMUNITY' as 'CLOUD' | 'COMMUNITY' | 'ENTERPRISE',+}))- return {- ...actual,- get IS_CE_EDITION() {- return editionState.isCommunity- },- }+vi.mock('@/context/system-features-state', async () => {+ const { createSystemFeaturesStateModuleMock } = await import('@/test/console/state-fixture')+ return createSystemFeaturesStateModuleMock(() => mockConsoleState)})vi.mock('@/next/dynamic', async () => {@@ -373,7 +369,7 @@ function renderPreviewChatWithClearCommandHarness() {describe('AgentPreviewChat', () => {beforeEach(() => {- editionState.isCommunity = true+ mockConsoleState.deploymentEdition = 'COMMUNITY'useChatMock.mockClear()handleSendMock.mockClear()chatMessagesGetMock.mockResolvedValue({ data: [] })@@ -1207,7 +1203,7 @@ describe('AgentPreviewChat', () => {})it('should hide only the sandbox notice infotip outside community edition', () => {- editionState.isCommunity = false+ mockConsoleState.deploymentEdition = 'CLOUD'renderPreviewChat({renderEmptyState: () => null,diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/header.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/header.spec.tsxindex ef4b6b4716c..1d4a503b779 100644--- a/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/header.spec.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/header.spec.tsx@@ -1,5 +1,6 @@-import { render, screen, within } from '@testing-library/react'+import { screen, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { AgentPreviewHeader } from '../header'function renderHeader({diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/chat-session.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/chat-session.tsxindex 7f5eb32bb95..0696f38597a 100644--- a/web/features/agent-v2/agent-detail/configure/components/preview/chat-session.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/preview/chat-session.tsx@@ -16,7 +16,7 @@ import { useAtomValue } from 'jotai'import { useCallback, useImperativeHandle, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import ChatInputArea from '@/app/components/base/chat/chat/chat-input-area'-import { IS_CE_EDITION } from '@/config'+import { deploymentEditionAtom } from '@/context/system-features-state'import { agentComposerModelAtom } from '@/features/agent-v2/agent-composer/store-modules/model'import { agentComposerPromptAtom } from '@/features/agent-v2/agent-composer/store-modules/prompt'import { buildChatConfig, getAgentSoulInputs, getAgentSoulInputsForm } from './chat-config'@@ -133,6 +133,7 @@ export function AgentPreviewChatSession({)const { isEmptyChat, isResponding, isSendPending } = runtimeStateconst hasInstructions = !!config.pre_prompt.trim()+ const deploymentEdition = useAtomValue(deploymentEditionAtom)const sendButtonLoading = isEmptyChat && !!sendButtonLabel && (isSendPending || isResponding)const sandboxNotice = t(($) => $['agentDetail.configure.preview.sandboxNotice'])const sandboxNoticeTooltip = t(($) => $['agentDetail.configure.preview.sandboxNoticeTooltip'])@@ -162,7 +163,9 @@ export function AgentPreviewChatSession({isResponding={isEmptyChat ? undefined : isResponding}sendButtonLabel={isEmptyChat ? sendButtonLabel : undefined}footerNotice={showSandboxNotice ? sandboxNotice : undefined}- footerNoticeTooltip={showSandboxNotice && IS_CE_EDITION ? sandboxNoticeTooltip : undefined}+ footerNoticeTooltip={+ showSandboxNotice && deploymentEdition === 'COMMUNITY' ? sandboxNoticeTooltip : undefined+ }/>)diff --git a/web/features/agent-v2/agent-detail/configure/page.tsx b/web/features/agent-v2/agent-detail/configure/page.tsxindex eda33c9e3d9..815558fb768 100644--- a/web/features/agent-v2/agent-detail/configure/page.tsx+++ b/web/features/agent-v2/agent-detail/configure/page.tsx@@ -7,9 +7,7 @@ import { ScopeProvider } from 'jotai-scope'import { parseAsStringLiteral, useQueryState } from 'nuqs'import { useCallback } from 'react'import { useTranslation } from 'react-i18next'-import { IS_CE_EDITION } from '@/config'import { systemFeaturesQueryOptions } from '@/features/system-features/client'-import { LicenseStatus } from '@/features/system-features/constants'import { AgentConfigureComposerScope } from './components/composer-session'import { AgentConfigurePageLoading } from './components/page-loading'import { useAgentConfigureData } from './hooks'@@ -46,11 +44,11 @@ function AgentConfigurePageContent({ agentId }: AgentConfigurePageProps) {const rebaseComposer = useSetAtom(rebaseAgentConfigureComposerAtom)const selectVersion = useSetAtom(agentConfigureSelectVersionAtom)const configureData = useAgentConfigureData(agentId, selectedVersionId)- const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())- const previewEnabled =- !IS_CE_EDITION ||- systemFeatures.license.status === LicenseStatus.ACTIVE ||- systemFeatures.license.status === LicenseStatus.EXPIRING+ const { data: deploymentEdition } = useSuspenseQuery({+ ...systemFeaturesQueryOptions(),+ select: (systemFeatures) => systemFeatures.deployment_edition,+ })+ const previewEnabled = deploymentEdition !== 'COMMUNITY'const rightPanelMode = requestedMode === 'preview' && previewEnabled ? 'preview' : 'build'const changeRightPanelMode = useCallback((nextMode: AgentConfigureRightPanelMode) => {diff --git a/web/features/agent-v2/agent-detail/logs/__tests__/page.spec.tsx b/web/features/agent-v2/agent-detail/logs/__tests__/page.spec.tsxindex acd2eca6a35..f5b8abfd3c2 100644--- a/web/features/agent-v2/agent-detail/logs/__tests__/page.spec.tsx+++ b/web/features/agent-v2/agent-detail/logs/__tests__/page.spec.tsx@@ -3,9 +3,11 @@ import type {AgentLogMessageListResponse,AgentLogSourceListResponse,} from '@dify/contracts/api/console/agent/types.gen'-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { QueryClient } from '@tanstack/react-query'import { render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { QueryClientTestProvider } from '@/test/console/query-provider'+import { createSystemFeaturesFixture } from '@/test/console/system-features'import { AgentLogsPage } from '../page'type AgentLogsQueryInput = {@@ -43,6 +45,16 @@ vi.mock('@/hooks/use-timestamp', () => ({vi.mock('@/service/client', () => ({consoleQuery: {+ systemFeatures: {+ get: {+ queryKey: () => ['console', 'systemFeatures', 'get'],+ queryOptions: (options?: Record<string, unknown>) => ({+ queryKey: ['console', 'systemFeatures', 'get'],+ queryFn: () => new Promise(() => {}),+ ...options,+ }),+ },+ },agent: {byAgentId: {logSources: {@@ -215,11 +227,15 @@ const renderPage = () => {},},})+ queryClient.setQueryData(+ ['console', 'systemFeatures', 'get'],+ createSystemFeaturesFixture({ deployment_edition: 'COMMUNITY' }),+ )render(- <QueryClientProvider client={queryClient}>+ <QueryClientTestProvider queryClient={queryClient}><AgentLogsPage agentId="agent-1" />- </QueryClientProvider>,+ </QueryClientTestProvider>,)return queryClientdiff --git a/web/features/deployments/detail/access/permissions/__tests__/permissions.spec.tsx b/web/features/deployments/detail/access/permissions/__tests__/permissions.spec.tsxindex d5ef6b45449..5fa3b8b14c8 100644--- a/web/features/deployments/detail/access/permissions/__tests__/permissions.spec.tsx+++ b/web/features/deployments/detail/access/permissions/__tests__/permissions.spec.tsx@@ -65,6 +65,10 @@ vi.mock('@/service/client', () => ({systemFeatures: {get: {queryKey: () => ['console', 'systemFeatures'],+ queryOptions: (options?: Record<string, unknown>) => ({+ queryKey: ['console', 'systemFeatures'],+ ...options,+ }),},},},diff --git a/web/features/new-rag/__tests__/knowledge-route-guard.spec.tsx b/web/features/new-rag/__tests__/knowledge-route-guard.spec.tsxdeleted file mode 100644index 68b54f0da70..00000000000--- a/web/features/new-rag/__tests__/knowledge-route-guard.spec.tsx+++ /dev/null@@ -1,60 +0,0 @@-import { screen, waitFor } from '@testing-library/react'-import { render } from '@/test/console/render'-import { KnowledgeRouteGuard } from '../knowledge-route-guard'--const featureMock = vi.hoisted(() => ({- enabled: true,- atom: Symbol('systemFeaturesAtom'),-}))--const routerMock = vi.hoisted(() => ({ replace: vi.fn() }))--vi.mock('@/next/navigation', () => ({- useRouter: () => routerMock,-}))--vi.mock('@/context/system-features-state', () => ({- systemFeaturesAtom: featureMock.atom,-}))--vi.mock('jotai', async (importOriginal) => {- const original = await importOriginal<typeof import('jotai')>()- return {- ...original,- useAtomValue: (atom: unknown) =>- atom === featureMock.atom- ? { knowledge_fs_enabled: featureMock.enabled }- : original.useAtomValue(atom as Parameters<typeof original.useAtomValue>[0]),- }-})--describe('KnowledgeRouteGuard', () => {- beforeEach(() => {- vi.clearAllMocks()- featureMock.enabled = true- })-- it('renders new KnowledgeFS routes while enabled', () => {- render(- <KnowledgeRouteGuard>- <div>protected content</div>- </KnowledgeRouteGuard>,- )-- expect(screen.getByText('protected content')).toBeInTheDocument()- expect(routerMock.replace).not.toHaveBeenCalled()- })-- it('redirects without mounting KnowledgeFS route content while disabled', async () => {- featureMock.enabled = false-- render(- <KnowledgeRouteGuard>- <div>protected content</div>- </KnowledgeRouteGuard>,- )-- expect(screen.queryByText('protected content')).not.toBeInTheDocument()- await waitFor(() => expect(routerMock.replace).toHaveBeenCalledWith('/datasets'))- })-})diff --git a/web/features/new-rag/knowledge-route-guard.tsx b/web/features/new-rag/knowledge-route-guard.tsxdeleted file mode 100644index aa522224e6a..00000000000--- a/web/features/new-rag/knowledge-route-guard.tsx+++ /dev/null@@ -1,20 +0,0 @@-'use client'--import type { ReactNode } from 'react'-import { useAtomValue } from 'jotai'-import { useEffect } from 'react'-import { systemFeaturesAtom } from '@/context/system-features-state'-import { useRouter } from '@/next/navigation'--export function KnowledgeRouteGuard({ children }: { children: ReactNode }) {- const { knowledge_fs_enabled: knowledgeFsEnabled } = useAtomValue(systemFeaturesAtom)- const router = useRouter()-- useEffect(() => {- if (!knowledgeFsEnabled) router.replace('/datasets')- }, [knowledgeFsEnabled, router])-- if (!knowledgeFsEnabled) return null-- return children-}diff --git a/web/features/system-features/README.md b/web/features/system-features/README.mdnew file mode 100644index 00000000000..d656ee4b171--- /dev/null+++ b/web/features/system-features/README.md@@ -0,0 +1,13 @@+# System Features++Loads deployment-wide capabilities for server prefetching, client hydration, and application bootstrap.++## Internal Modules++None.++## External Modules++- `app/components/full-screen-loading`+- `context/server-console-client`+- `utils/client`diff --git a/web/features/system-features/__tests__/bootstrap-boundary.spec.tsx b/web/features/system-features/__tests__/bootstrap-boundary.spec.tsxnew file mode 100644index 00000000000..6437792a61c--- /dev/null+++ b/web/features/system-features/__tests__/bootstrap-boundary.spec.tsx@@ -0,0 +1,120 @@+import type { ReactNode } from 'react'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { act, render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { createSystemFeaturesFixture } from '@/test/console/system-features'+import { SystemFeaturesBootstrapBoundary } from '../bootstrap-boundary'++const queryKey = ['console', 'system-features', 'get']++type Deferred<T> = {+ promise: Promise<T>+ resolve: (value: T) => void+}++function createDeferred<T>(): Deferred<T> {+ let resolve!: (value: T) => void+ const promise = new Promise<T>((nextResolve) => {+ resolve = nextResolve+ })++ return { promise, resolve }+}++const mocks = vi.hoisted(() => ({+ isClient: true,+ query: vi.fn(),+}))++vi.mock('../client', () => ({+ systemFeaturesQueryOptions: () => ({+ queryKey,+ queryFn: mocks.query,+ retryDelay: 0,+ staleTime: Infinity,+ }),+}))++vi.mock('@/app/components/full-screen-loading', () => ({+ FullScreenLoading: () => <div role="status">Loading system features</div>,+}))++vi.mock('@/utils/client', () => ({+ get isClient() {+ return mocks.isClient+ },+}))++function createQueryClient() {+ return new QueryClient()+}++function renderBoundary(children: ReactNode, queryClient = createQueryClient()) {+ render(+ <QueryClientProvider client={queryClient}>+ <SystemFeaturesBootstrapBoundary>{children}</SystemFeaturesBootstrapBoundary>+ </QueryClientProvider>,+ )++ return queryClient+}++describe('SystemFeaturesBootstrapBoundary', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mocks.isClient = true+ })++ it('renders immediately from hydrated data without a client request', () => {+ const queryClient = createQueryClient()+ queryClient.setQueryData(queryKey, createSystemFeaturesFixture())++ renderBoundary(<div>Application</div>, queryClient)++ expect(screen.getByText('Application')).toBeInTheDocument()+ expect(screen.queryByRole('status')).not.toBeInTheDocument()+ expect(mocks.query).not.toHaveBeenCalled()+ })++ it('shows loading only while the client recovers missing server data', async () => {+ const deferred = createDeferred<ReturnType<typeof createSystemFeaturesFixture>>()+ mocks.query.mockReturnValue(deferred.promise)++ renderBoundary(<div>Application</div>)++ expect(screen.getByRole('status')).toHaveTextContent('Loading system features')+ expect(screen.queryByText('Application')).not.toBeInTheDocument()++ await act(async () => {+ deferred.resolve(createSystemFeaturesFixture())+ })++ expect(await screen.findByText('Application')).toBeInTheDocument()+ expect(screen.queryByRole('status')).not.toBeInTheDocument()+ })++ it('does not duplicate the request during server rendering when prefetched data is missing', () => {+ mocks.isClient = false++ renderBoundary(<div>Application</div>)++ expect(screen.getByRole('status')).toHaveTextContent('Loading system features')+ expect(mocks.query).not.toHaveBeenCalled()+ })++ it('allows a manual retry after the client retry budget is exhausted', async () => {+ const user = userEvent.setup()+ mocks.query.mockRejectedValue(new Error('system features unavailable'))++ renderBoundary(<div>Application</div>)++ const retryButton = await screen.findByRole('button', {+ name: 'common.errorBoundary.tryAgain',+ })++ mocks.query.mockResolvedValue(createSystemFeaturesFixture())+ await user.click(retryButton)++ expect(await screen.findByText('Application')).toBeInTheDocument()+ })+})diff --git a/web/features/system-features/__tests__/system-features.spec.ts b/web/features/system-features/__tests__/system-features.spec.tsdeleted file mode 100644index fa7a3728488..00000000000--- a/web/features/system-features/__tests__/system-features.spec.ts+++ /dev/null@@ -1,287 +0,0 @@-import type { GetSystemFeaturesResponse } from '@dify/contracts/api/console/system-features/types.gen'-import { describe, expect, it, vi } from 'vitest'-import { defaultSystemFeatures } from '../config'--type LoadOptions = {- cloudEnv?: Partial<typeof defaultCloudEnv>- isCloudEdition: boolean- systemFeaturesResult?: GetSystemFeaturesResponse- systemFeaturesError?: Error-}--const defaultCloudEnv = {- NEXT_PUBLIC_ALLOW_CREATE_WORKSPACE: true,- NEXT_PUBLIC_ALLOW_REGISTER: true,- NEXT_PUBLIC_CREATORS_PLATFORM_FEATURES_ENABLED: true,- NEXT_PUBLIC_ENABLE_CHANGE_EMAIL: true,- NEXT_PUBLIC_ENABLE_COLLABORATION_MODE: false,- NEXT_PUBLIC_ENABLE_EMAIL_CODE_LOGIN: true,- NEXT_PUBLIC_ENABLE_EMAIL_PASSWORD_LOGIN: false,- NEXT_PUBLIC_ENABLE_EXPLORE_BANNER: true,- NEXT_PUBLIC_ENABLE_LEARN_APP: true,- NEXT_PUBLIC_ENABLE_MARKETPLACE: true,- NEXT_PUBLIC_ENABLE_SOCIAL_OAUTH_LOGIN: true,- NEXT_PUBLIC_ENABLE_STEP_BY_STEP_TOUR: true,- NEXT_PUBLIC_ENABLE_TRIAL_APP: true,- NEXT_PUBLIC_IS_EMAIL_SETUP: true,- NEXT_PUBLIC_RBAC_ENABLED: false,-}--const queryKey = ['console', 'systemFeatures'] as const-const queryContext = {- queryKey,- signal: new AbortController().signal,- meta: undefined,-} as never--const loadSystemFeaturesModule = async ({- cloudEnv,- isCloudEdition,- systemFeaturesResult = defaultSystemFeatures,- systemFeaturesError,-}: LoadOptions) => {- vi.resetModules()-- const systemFeatures = systemFeaturesError- ? vi.fn().mockRejectedValue(systemFeaturesError)- : vi.fn().mockResolvedValue(systemFeaturesResult)-- vi.doMock('@/config', () => ({- IS_CLOUD_EDITION: isCloudEdition,- }))- vi.doMock('@/env', () => ({- env: {- ...defaultCloudEnv,- ...cloudEnv,- },- }))- vi.doMock('@/service/client', () => ({- consoleClient: {- systemFeatures: {- get: systemFeatures,- },- },- consoleQuery: {- systemFeatures: {- get: {- queryKey: () => queryKey,- },- },- },- }))-- const module = await import('../client')-- return {- module,- systemFeatures,- }-}--const loadServerSystemFeaturesModule = async ({- cloudEnv,- isCloudEdition,- systemFeaturesResult = defaultSystemFeatures,- systemFeaturesError,-}: LoadOptions) => {- vi.resetModules()-- const getServerConsoleClientContext = vi.fn().mockResolvedValue({ cookie: 'session=1' })- const systemFeatures = systemFeaturesError- ? vi.fn().mockRejectedValue(systemFeaturesError)- : vi.fn().mockResolvedValue(systemFeaturesResult)-- vi.doMock('@/config', () => ({- IS_CLOUD_EDITION: isCloudEdition,- }))- vi.doMock('@/env', () => ({- env: {- ...defaultCloudEnv,- ...cloudEnv,- },- }))- vi.doMock('@/service/server', () => ({- getServerConsoleClientContext,- serverConsoleClient: {- systemFeatures: {- get: systemFeatures,- },- },- serverConsoleQuery: {- systemFeatures: {- get: {- queryKey: () => queryKey,- },- },- },- }))-- const module = await import('../server')-- return {- getServerConsoleClientContext,- module,- systemFeatures,- }-}--describe('systemFeaturesQueryOptions', () => {- it('should return Cloud defaults without calling system-features when Cloud edition is enabled', async () => {- const { module, systemFeatures } = await loadSystemFeaturesModule({- isCloudEdition: true,- })-- const options = module.systemFeaturesQueryOptions()- const data = await options.queryFn?.(queryContext)-- expect(systemFeatures).not.toHaveBeenCalled()- expect(options.staleTime).toBe('static')- expect(data).toMatchObject({- enable_marketplace: true,- enable_email_code_login: true,- enable_email_password_login: false,- enable_social_oauth_login: true,- enable_trial_app: true,- enable_learn_app: true,- enable_step_by_step_tour: true,- rbac_enabled: false,- })- })-- it('should use Cloud environment flags with local defaults for fixed fields', async () => {- const { module } = await loadSystemFeaturesModule({- isCloudEdition: true,- cloudEnv: {- NEXT_PUBLIC_ENABLE_MARKETPLACE: false,- NEXT_PUBLIC_ENABLE_EMAIL_PASSWORD_LOGIN: true,- NEXT_PUBLIC_ENABLE_COLLABORATION_MODE: true,- NEXT_PUBLIC_ALLOW_REGISTER: false,- NEXT_PUBLIC_ENABLE_EXPLORE_BANNER: false,- NEXT_PUBLIC_ENABLE_LEARN_APP: true,- NEXT_PUBLIC_ENABLE_STEP_BY_STEP_TOUR: true,- NEXT_PUBLIC_RBAC_ENABLED: true,- },- })-- const options = module.systemFeaturesQueryOptions()- const data = await options.queryFn?.(queryContext)-- expect(data).toMatchObject({- enable_marketplace: false,- enable_email_password_login: true,- enable_collaboration_mode: true,- is_allow_register: false,- enable_explore_banner: false,- enable_learn_app: true,- enable_step_by_step_tour: true,- rbac_enabled: true,- branding: {- enabled: false,- application_title: '',- favicon: '',- },- license: {- status: 'none',- },- })- })-- it('should fetch system-features when Cloud edition is disabled', async () => {- const systemFeaturesResult = {- ...defaultSystemFeatures,- enable_marketplace: true,- }- const { module, systemFeatures } = await loadSystemFeaturesModule({- isCloudEdition: false,- systemFeaturesResult,- })-- const options = module.systemFeaturesQueryOptions()- const data = await options.queryFn?.(queryContext)-- expect(systemFeatures).toHaveBeenCalledTimes(1)- expect(data).toBe(systemFeaturesResult)- })-- it('should fall back to defaults when the non-Cloud request fails', async () => {- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})- const { module, systemFeatures } = await loadSystemFeaturesModule({- isCloudEdition: false,- systemFeaturesError: new Error('network failed'),- })-- const options = module.systemFeaturesQueryOptions()- const data = await options.queryFn?.(queryContext)-- expect(systemFeatures).toHaveBeenCalledTimes(1)- expect(data).toEqual(defaultSystemFeatures)-- errorSpy.mockRestore()- })-})--describe('serverSystemFeaturesQueryOptions', () => {- it('should prefetch Cloud defaults without calling server system-features when Cloud edition is enabled', async () => {- const { getServerConsoleClientContext, module, systemFeatures } =- await loadServerSystemFeaturesModule({- isCloudEdition: true,- cloudEnv: {- NEXT_PUBLIC_ENABLE_MARKETPLACE: false,- NEXT_PUBLIC_ENABLE_EMAIL_PASSWORD_LOGIN: true,- NEXT_PUBLIC_ENABLE_LEARN_APP: true,- NEXT_PUBLIC_ENABLE_STEP_BY_STEP_TOUR: true,- },- })-- const options = module.serverSystemFeaturesQueryOptions()- const data = await options.queryFn?.(queryContext)-- expect(getServerConsoleClientContext).not.toHaveBeenCalled()- expect(systemFeatures).not.toHaveBeenCalled()- expect(options.staleTime).toBe('static')- expect(data).toMatchObject({- enable_marketplace: false,- enable_email_password_login: true,- enable_learn_app: true,- enable_step_by_step_tour: true,- })- })-- it('should fetch server system-features when Cloud edition is disabled', async () => {- const systemFeaturesResult = {- ...defaultSystemFeatures,- enable_marketplace: true,- }- const { getServerConsoleClientContext, module, systemFeatures } =- await loadServerSystemFeaturesModule({- isCloudEdition: false,- systemFeaturesResult,- })-- const options = module.serverSystemFeaturesQueryOptions()- const data = await options.queryFn?.(queryContext)-- expect(getServerConsoleClientContext).toHaveBeenCalledTimes(1)- expect(systemFeatures).toHaveBeenCalledTimes(1)- expect(systemFeatures).toHaveBeenCalledWith(undefined, {- context: { cookie: 'session=1' },- })- expect(data).toBe(systemFeaturesResult)- })-- it('should fall back to defaults when the non-Cloud server request fails', async () => {- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})- const { module, systemFeatures } = await loadServerSystemFeaturesModule({- isCloudEdition: false,- systemFeaturesError: new Error('server failed'),- })-- const options = module.serverSystemFeaturesQueryOptions()- const data = await options.queryFn?.(queryContext)-- expect(systemFeatures).toHaveBeenCalledTimes(1)- expect(data).toEqual(defaultSystemFeatures)-- errorSpy.mockRestore()- })-})diff --git a/web/features/system-features/bootstrap-boundary.tsx b/web/features/system-features/bootstrap-boundary.tsxnew file mode 100644index 00000000000..8926894126a--- /dev/null+++ b/web/features/system-features/bootstrap-boundary.tsx@@ -0,0 +1,31 @@+'use client'++import type { ReactNode } from 'react'+import { Button } from '@langgenius/dify-ui/button'+import { useQuery } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import { FullScreenLoading } from '@/app/components/full-screen-loading'+import { isClient } from '@/utils/client'+import { systemFeaturesQueryOptions } from './client'++export function SystemFeaturesBootstrapBoundary({ children }: { children: ReactNode }) {+ const { t } = useTranslation('common')+ const { data, error, isFetching, refetch } = useQuery({+ ...systemFeaturesQueryOptions(),+ enabled: isClient,+ })++ if (data) return children+ if (!error || isFetching) return <FullScreenLoading />++ return (+ <div className="flex min-h-dvh w-full flex-1 flex-col items-center justify-center gap-4 bg-background-body">+ <div role="alert" className="system-sm-regular text-text-tertiary">+ {t(($) => $['errorBoundary.message'])}+ </div>+ <Button size="small" variant="secondary" onClick={() => void refetch()}>+ {t(($) => $['errorBoundary.tryAgain'])}+ </Button>+ </div>+ )+}diff --git a/web/features/system-features/client.ts b/web/features/system-features/client.tsindex aaef4fad356..976505d9bb4 100644--- a/web/features/system-features/client.ts+++ b/web/features/system-features/client.ts@@ -1,43 +1,6 @@-import type { GetSystemFeaturesResponse } from '@dify/contracts/api/console/system-features/types.gen'-import { queryOptions } from '@tanstack/react-query'-import { IS_CLOUD_EDITION } from '@/config'-import { consoleClient, consoleQuery } from '@/service/client'-import { cloudSystemFeatures, defaultSystemFeatures } from './config'+import { consoleQuery } from '@/service/client'-/**- * Soft-fallback to defaults so the dashboard stays usable when /system-features fails.- *- * No `retry`: the queryFn never throws (errors are caught and turned into the- * default payload), so react-query's retry would never fire under this model.- * This trades main's transient-blip resilience for guaranteed dashboard- * availability via defaults; the trade-off is acceptable because /system-features- * is a small, dependency-free endpoint in the community edition.- *- * For Cloud, this query is intentionally local-only and uses `staleTime:- * 'static'`: the payload comes from frontend config/defaults, so invalidation- * should not re-run the same local merge. For non-Cloud, do not override- * `staleTime`: inherit the 5-minute default from query-client-server.ts.- */-export const systemFeaturesQueryOptions = () => {- const queryKey = consoleQuery.systemFeatures.get.queryKey()-- if (IS_CLOUD_EDITION) {- return queryOptions<GetSystemFeaturesResponse>({- queryKey,- queryFn: async () => cloudSystemFeatures,- staleTime: 'static',- })- }-- return queryOptions<GetSystemFeaturesResponse>({- queryKey,- queryFn: async () => {- try {- return await consoleClient.systemFeatures.get()- } catch (err) {- console.error('[systemFeatures] fetch failed, using defaults', err)- return defaultSystemFeatures- }- },+export const systemFeaturesQueryOptions = () =>+ consoleQuery.systemFeatures.get.queryOptions({+ staleTime: Infinity,})-}diff --git a/web/features/system-features/config.ts b/web/features/system-features/config.tsdeleted file mode 100644index a6d8468407b..00000000000--- a/web/features/system-features/config.ts+++ /dev/null@@ -1,118 +0,0 @@-import type { GetSystemFeaturesResponse } from '@dify/contracts/api/console/system-features/types.gen'-import { env } from '@/env'-import { InstallationScope, LicenseStatus } from './constants'--export const defaultSystemFeatures = {- enable_app_deploy: false,- sso_enforced_for_signin: false,- sso_enforced_for_signin_protocol: '',- enable_marketplace: false,- enable_email_code_login: false,- enable_email_password_login: true,- enable_social_oauth_login: false,- enable_collaboration_mode: true,- is_allow_create_workspace: false,- is_allow_register: false,- is_email_setup: false,- enable_change_email: true,- max_plugin_package_size: 15728640,- license: {- status: LicenseStatus.NONE,- expired_at: '',- workspaces: {- enabled: false,- size: 0,- limit: 0,- },- seats: {- enabled: false,- size: 0,- limit: 0,- },- },- branding: {- enabled: false,- login_page_logo: '',- workspace_logo: '',- favicon: '',- application_title: '',- },- webapp_auth: {- enabled: false,- allow_sso: false,- sso_config: {- protocol: '',- },- allow_email_code_login: false,- allow_email_password_login: false,- allow_public_access: true,- },- plugin_installation_permission: {- plugin_installation_scope: InstallationScope.ALL,- restrict_to_marketplace_only: false,- },- plugin_manager: {- enabled: false,- },- rbac_enabled: false,- enable_creators_platform: false,- enable_trial_app: false,- enable_explore_banner: false,- enable_learn_app: true,- enable_step_by_step_tour: false,- knowledge_fs_enabled: false,-} satisfies GetSystemFeaturesResponse--export const cloudSystemFeatures = {- ...defaultSystemFeatures,- sso_enforced_for_signin: false,- sso_enforced_for_signin_protocol: '',-- enable_marketplace: env.NEXT_PUBLIC_ENABLE_MARKETPLACE,- enable_email_code_login: env.NEXT_PUBLIC_ENABLE_EMAIL_CODE_LOGIN,- enable_email_password_login: env.NEXT_PUBLIC_ENABLE_EMAIL_PASSWORD_LOGIN,- enable_social_oauth_login: env.NEXT_PUBLIC_ENABLE_SOCIAL_OAUTH_LOGIN,- enable_collaboration_mode: env.NEXT_PUBLIC_ENABLE_COLLABORATION_MODE,- is_allow_register: env.NEXT_PUBLIC_ALLOW_REGISTER,- is_allow_create_workspace: env.NEXT_PUBLIC_ALLOW_CREATE_WORKSPACE,- is_email_setup: env.NEXT_PUBLIC_IS_EMAIL_SETUP,- enable_change_email: env.NEXT_PUBLIC_ENABLE_CHANGE_EMAIL,- knowledge_fs_enabled: env.NEXT_PUBLIC_KNOWLEDGE_FS_ENABLED,-- license: {- ...defaultSystemFeatures.license,- status: LicenseStatus.NONE,- expired_at: '',- },-- branding: {- enabled: false,- application_title: '',- login_page_logo: '',- workspace_logo: '',- favicon: '',- },-- webapp_auth: {- enabled: false,- allow_sso: false,- sso_config: {- protocol: '',- },- allow_email_code_login: false,- allow_email_password_login: false,- allow_public_access: true,- },-- plugin_installation_permission: {- plugin_installation_scope: InstallationScope.ALL,- restrict_to_marketplace_only: false,- },-- enable_creators_platform: env.NEXT_PUBLIC_CREATORS_PLATFORM_FEATURES_ENABLED,- enable_trial_app: env.NEXT_PUBLIC_ENABLE_TRIAL_APP,- enable_explore_banner: env.NEXT_PUBLIC_ENABLE_EXPLORE_BANNER,- enable_learn_app: env.NEXT_PUBLIC_ENABLE_LEARN_APP,- enable_step_by_step_tour: env.NEXT_PUBLIC_ENABLE_STEP_BY_STEP_TOUR,- rbac_enabled: env.NEXT_PUBLIC_RBAC_ENABLED,-} satisfies GetSystemFeaturesResponsediff --git a/web/features/system-features/server.ts b/web/features/system-features/server.tsdeleted file mode 100644index c363a95b3bf..00000000000--- a/web/features/system-features/server.ts+++ /dev/null@@ -1,35 +0,0 @@-import type { GetSystemFeaturesResponse } from '@dify/contracts/api/console/system-features/types.gen'-import { queryOptions } from '@tanstack/react-query'-import { IS_CLOUD_EDITION } from '@/config'-import {- getServerConsoleClientContext,- serverConsoleClient,- serverConsoleQuery,-} from '@/service/server'-import { cloudSystemFeatures, defaultSystemFeatures } from './config'--export const serverSystemFeaturesQueryOptions = () => {- const queryKey = serverConsoleQuery.systemFeatures.get.queryKey()-- if (IS_CLOUD_EDITION) {- return queryOptions<GetSystemFeaturesResponse>({- queryKey,- queryFn: async () => cloudSystemFeatures,- staleTime: 'static',- })- }-- return queryOptions<GetSystemFeaturesResponse>({- queryKey,- queryFn: async () => {- try {- return await serverConsoleClient.systemFeatures.get(undefined, {- context: await getServerConsoleClientContext(),- })- } catch (err) {- console.error('[systemFeatures] server fetch failed', err)- return defaultSystemFeatures- }- },- })-}diff --git a/web/hooks/use-document-title.ts b/web/hooks/use-document-title.tsindex f4c0f8c88b0..5b66fae7210 100644--- a/web/hooks/use-document-title.ts+++ b/web/hooks/use-document-title.ts@@ -1,30 +1,20 @@'use client'-import { useQuery } from '@tanstack/react-query'+import { useSuspenseQuery } from '@tanstack/react-query'import { useFavicon, useTitle } from 'ahooks'import { useEffect } from 'react'import { systemFeaturesQueryOptions } from '@/features/system-features/client'-import { defaultSystemFeatures } from '@/features/system-features/config'import { basePath } from '@/utils/var'export default function useDocumentTitle(title: string) {- const { data, isPending } = useQuery(systemFeaturesQueryOptions())- const systemFeatures = data ?? defaultSystemFeatures+ const { data } = useSuspenseQuery(systemFeaturesQueryOptions())+ const branding = data.brandingconst prefix = title ? `${title} - ` : ''- let titleStr = ''- let favicon = ''- if (isPending === false) {- if (systemFeatures.branding.enabled) {- titleStr = `${prefix}${systemFeatures.branding.application_title}`- favicon = systemFeatures.branding.favicon- } else {- titleStr = `${prefix}Dify`- favicon = `${basePath}/favicon.ico`- }- }+ const titleStr = branding.enabled ? `${prefix}${branding.application_title}` : `${prefix}Dify`+ const favicon = branding.enabled ? branding.favicon : `${basePath}/favicon.ico`useTitle(titleStr)useEffect(() => {let apple: HTMLLinkElement | null = null- if (systemFeatures.branding.favicon) {+ if (branding.favicon) {document.querySelectorAll("link[rel='icon'], link[rel='shortcut icon'], link[rel='apple-touch-icon'], link[rel='mask-icon']",@@ -33,13 +23,13 @@ export default function useDocumentTitle(title: string) {apple = document.createElement('link')apple.rel = 'apple-touch-icon'- apple.href = systemFeatures.branding.favicon+ apple.href = branding.favicondocument.head.appendChild(apple)}return () => {apple?.remove()}- }, [systemFeatures.branding.favicon])+ }, [branding.favicon])useFavicon(favicon)}diff --git a/web/service/__tests__/base.spec.ts b/web/service/__tests__/base.spec.tsindex b9df08598c3..1884e2fa90f 100644--- a/web/service/__tests__/base.spec.ts+++ b/web/service/__tests__/base.spec.ts@@ -8,7 +8,6 @@ vi.mock('@/utils/var', () => ({basePath: '/app',API_PREFIX: '/console/api',PUBLIC_API_PREFIX: '/api',- IS_CE_EDITION: false,}))describe('buildSigninUrlWithRedirect', () => {diff --git a/web/service/__tests__/server.spec.ts b/web/service/__tests__/server.spec.tsindex 9aa0fb44293..de2debd67dc 100644--- a/web/service/__tests__/server.spec.ts+++ b/web/service/__tests__/server.spec.ts@@ -71,9 +71,9 @@ describe('server console oRPC client', () => {})it('should call contracts with forwarded cookies, csrf header, and no-store cache', async () => {- const { defaultSystemFeatures } = await import('@/features/system-features/config')+ const { createSystemFeaturesFixture } = await import('@/test/console/system-features')const fetchMock = vi.fn().mockResolvedValue(- new Response(JSON.stringify(defaultSystemFeatures), {+ new Response(JSON.stringify(createSystemFeaturesFixture()), {status: 200,headers: {'content-type': 'application/json',diff --git a/web/service/__tests__/sse-generator-post.spec.ts b/web/service/__tests__/sse-generator-post.spec.tsindex 16c4343a166..89a99bf703f 100644--- a/web/service/__tests__/sse-generator-post.spec.ts+++ b/web/service/__tests__/sse-generator-post.spec.ts@@ -6,7 +6,6 @@ vi.mock('@/utils/var', () => ({basePath: '/app',API_PREFIX: '/console/api',PUBLIC_API_PREFIX: '/api',- IS_CE_EDITION: false,}))// Minimal streaming Response: a body whose reader yields the given chunks indiff --git a/web/service/access-control/__tests__/use-app-access-control.spec.tsx b/web/service/access-control/__tests__/use-app-access-control.spec.tsxindex 95c43ac24c9..7ec890fb130 100644--- a/web/service/access-control/__tests__/use-app-access-control.spec.tsx+++ b/web/service/access-control/__tests__/use-app-access-control.spec.tsx@@ -1,8 +1,7 @@-import type { ReactNode } from 'react'-import { QueryClient, QueryClientProvider, queryOptions } from '@tanstack/react-query'import { renderHook, waitFor } from '@testing-library/react'import { get } from '@/service/base'import { getUserCanAccess } from '@/service/share'+import { createConsoleQueryWrapper } from '@/test/console/query-data'import {useAppWhiteListSubjects,useGetUserCanAccessApp,@@ -25,46 +24,37 @@ vi.mock('@/service/share', () => ({getUserCanAccess: vi.fn(),}))-vi.mock('@/service/client', () => ({- consoleQuery: {- enterprise: {- webAppAuth: {- getWebAppWhitelistSubjects: {- queryOptions: ({ input }: { input: { query: { appId?: string } } }) => ({- queryKey: ['web-app-whitelist-subjects', input.query.appId],- queryFn: () => mockGetWebAppWhitelistSubjects(input),- }),+vi.mock('@/service/client', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/service/client')>()+ return {+ ...actual,+ consoleQuery: {+ ...actual.consoleQuery,+ systemFeatures: actual.consoleQuery.systemFeatures,+ enterprise: {+ ...actual.consoleQuery.enterprise,+ webAppAuth: {+ ...actual.consoleQuery.enterprise.webAppAuth,+ getWebAppWhitelistSubjects: {+ queryOptions: ({ input }: { input: { query: { appId?: string } } }) => ({+ queryKey: ['web-app-whitelist-subjects', input.query.appId],+ queryFn: () => mockGetWebAppWhitelistSubjects(input),+ }),+ },},},},- },-}))--vi.mock('@/features/system-features/client', () => ({- systemFeaturesQueryOptions: () =>- queryOptions({- queryKey: ['system-features'],- queryFn: () =>- Promise.resolve({- webapp_auth: {- enabled: mockSystemFeatures.webappAuthEnabled,- },- }),- }),-}))+ }+})-const createWrapper = () => {- const queryClient = new QueryClient({- defaultOptions: {- queries: { retry: false },- mutations: { retry: false },+const createWrapper = () =>+ createConsoleQueryWrapper({+ systemFeatures: {+ webapp_auth: {+ enabled: mockSystemFeatures.webappAuthEnabled,+ },},- })-- return ({ children }: { children: ReactNode }) => (- <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>- )-}+ }).wrapperdescribe('use-app-access-control', () => {beforeEach(() => {diff --git a/web/service/access-control/use-app-access-control.ts b/web/service/access-control/use-app-access-control.tsindex 513d61e795a..97d5e37c828 100644--- a/web/service/access-control/use-app-access-control.ts+++ b/web/service/access-control/use-app-access-control.ts@@ -1,5 +1,5 @@import type { AccessControlGroup, Subject } from '@/models/access-control'-import { useInfiniteQuery, useQuery } from '@tanstack/react-query'+import { useInfiniteQuery, useQuery, useSuspenseQuery } from '@tanstack/react-query'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { get } from '../base'import { consoleQuery } from '../client'@@ -87,11 +87,8 @@ export const useGetUserCanAccessApp = ({isInstalledApp?: booleanenabled?: boolean}) => {- // useQuery (not useSuspenseQuery) to keep this service hook's call contract- // unchanged from the zustand era: callers should not need a Suspense boundary.- // First-fetch undefined is bridged via `?? false` so the inner queryKey is stable.- const { data: systemFeatures } = useQuery(systemFeaturesQueryOptions())- const webappAuthEnabled = systemFeatures?.webapp_auth.enabled ?? false+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())+ const webappAuthEnabled = systemFeatures.webapp_auth.enabledreturn useQuery({queryKey: [NAME_SPACE, 'user-can-access-app', appId, webappAuthEnabled, isInstalledApp],queryFn: () => {diff --git a/web/service/base.ts b/web/service/base.tsindex 35e34631cbe..f2e456b3dd5 100644--- a/web/service/base.ts+++ b/web/service/base.ts@@ -34,7 +34,6 @@ import {API_PREFIX,CSRF_COOKIE_NAME,CSRF_HEADER_NAME,- IS_CE_EDITION,PASSPORT_HEADER_NAME,PUBLIC_API_PREFIX,WEB_APP_SHARE_CODE_HEADER_NAME,@@ -975,15 +974,15 @@ export const request = async <T>(url: string, options = {}, otherOptions?: IOtherequiredWebSSOLogin()return Promise.reject(err)}- if (code === 'init_validate_failed' && IS_CE_EDITION && !silent) {+ if (code === 'init_validate_failed' && !silent) {toast.error(message, { timeout: 4000 })return Promise.reject(err)}- if (code === 'not_init_validated' && IS_CE_EDITION) {+ if (code === 'not_init_validated') {jumpTo(`${window.location.origin}${basePath}/init`)return Promise.reject(err)}- if (code === 'not_setup' && IS_CE_EDITION) {+ if (code === 'not_setup') {jumpTo(`${window.location.origin}${basePath}/install`)return Promise.reject(err)}@@ -995,7 +994,7 @@ export const request = async <T>(url: string, options = {}, otherOptions?: IOthe// there. Redirecting to /signin loses the user_code context and// the post-login flow lands on /apps instead of returning here.if (window.location.pathname === `${basePath}/device`) return Promise.reject(err)- if (window.location.pathname !== `${basePath}/signin` || !IS_CE_EDITION) {+ if (window.location.pathname !== `${basePath}/signin`) {jumpTo(buildSigninUrlWithRedirect())return Promise.reject(err)}diff --git a/web/service/use-explore.ts b/web/service/use-explore.tsindex b2a817862b9..a974132dd0f 100644--- a/web/service/use-explore.ts+++ b/web/service/use-explore.ts@@ -1,5 +1,5 @@import type { App, AppCategory } from '@/models/explore'-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { useMutation, useQuery, useQueryClient, useSuspenseQuery } from '@tanstack/react-query'import { useLocale } from '@/context/i18n'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { AccessMode } from '@/models/access-control'@@ -95,11 +95,8 @@ export const useUpdateAppPinStatus = () => {}export const useGetInstalledAppAccessModeByAppId = (appId: string | null) => {- // useQuery (not useSuspenseQuery) to keep this service hook's call contract- // unchanged from the zustand era: callers should not need a Suspense boundary.- // First-fetch undefined is bridged via `?? false` so the inner queryKey is stable.- const { data: systemFeatures } = useQuery(systemFeaturesQueryOptions())- const webappAuthEnabled = systemFeatures?.webapp_auth.enabled ?? false+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())+ const webappAuthEnabled = systemFeatures.webapp_auth.enabledconst appAccessModeInput = { query: { appId: appId ?? '' } }const installedAppId = appAccessModeInput.query.appIddiff --git a/web/test/console/query-data.ts b/web/test/console/query-data.tsindex bbc13448f28..e4ff7574709 100644--- a/web/test/console/query-data.ts+++ b/web/test/console/query-data.ts@@ -1,5 +1,8 @@import type { GetAccountProfileResponse } from '@dify/contracts/api/console/account/types.gen'-import type { GetSystemFeaturesResponse } from '@dify/contracts/api/console/system-features/types.gen'+import type {+ GetSystemFeaturesLicenseResponse,+ GetSystemFeaturesResponse,+} from '@dify/contracts/api/console/system-features/types.gen'import type { PostWorkspacesCurrentResponse } from '@dify/contracts/api/console/workspaces/types.gen'import type { QueryClient } from '@tanstack/react-query'import type {@@ -9,8 +12,8 @@ import type {RenderResult,} from '@testing-library/react'import type { ReactElement, ReactNode } from 'react'+import type { DeepPartial } from '@/test/console/system-features'import { render, renderHook } from '@testing-library/react'-import { defaultSystemFeatures } from '@/features/system-features/config'import { consoleQuery } from '@/service/client'import { ensureAccountProfileQuery, seedAccountProfileQuery } from '@/test/console/account-profile'import {@@ -19,6 +22,10 @@ import {seedCurrentWorkspaceQuery,} from '@/test/console/current-workspace'import { createQueryClientWrapper } from '@/test/console/query-client'+import {+ createSystemFeaturesFixture,+ createSystemFeaturesLicenseFixture,+} from '@/test/console/system-features'import {ensureWorkspacePermissionsQuery,seedWorkspacePermissionsQuery,@@ -67,51 +74,6 @@ const getCurrentWorkspaceQueryKey = () => {return currentWorkspaceQuery?.post?.queryKey() ?? currentWorkspaceQueryKey}-type DeepPartial<T> =- T extends Array<infer U>- ? Array<U>- : T extends object- ? { [K in keyof T]?: DeepPartial<T[K]> }- : T--const buildSystemFeatures = (- overrides: DeepPartial<GetSystemFeaturesResponse> = {},-): GetSystemFeaturesResponse => {- const o = overrides as Partial<GetSystemFeaturesResponse>- return {- ...defaultSystemFeatures,- ...o,- branding: {- ...defaultSystemFeatures.branding,- ...(o.branding ?? {}),- },- webapp_auth: {- ...defaultSystemFeatures.webapp_auth,- ...(o.webapp_auth ?? {}),- sso_config: {- ...defaultSystemFeatures.webapp_auth.sso_config,- ...(o.webapp_auth?.sso_config ?? {}),- },- },- plugin_installation_permission: {- ...defaultSystemFeatures.plugin_installation_permission,- ...(o.plugin_installation_permission ?? {}),- },- license: {- ...defaultSystemFeatures.license,- ...(o.license ?? {}),- workspaces: {- ...defaultSystemFeatures.license.workspaces,- ...(o.license?.workspaces ?? {}),- },- },- plugin_manager: {- ...defaultSystemFeatures.plugin_manager,- ...(o.plugin_manager ?? {}),- },- }-}-/*** Build a QueryClient suitable for tests. Any unseeded query stays in the* "pending" state forever because the default queryFn never resolves; this@@ -125,8 +87,19 @@ export const seedSystemFeatures = (queryClient: QueryClient,overrides: DeepPartial<GetSystemFeaturesResponse> = {},): GetSystemFeaturesResponse => {- const data = buildSystemFeatures(overrides)- queryClient.setQueryData(consoleQuery.systemFeatures.get.queryKey(), data)+ const data = createSystemFeaturesFixture(overrides)+ const queryKey = consoleQuery.systemFeatures.get.queryKey() as readonly unknown[]+ queryClient.setQueryData<GetSystemFeaturesResponse>(queryKey, data)+ return data+}++export const seedSystemFeaturesLicense = (+ queryClient: QueryClient,+ overrides: DeepPartial<GetSystemFeaturesLicenseResponse> = {},+): GetSystemFeaturesLicenseResponse => {+ const data = createSystemFeaturesLicenseFixture(overrides)+ const queryKey = consoleQuery.systemFeatures.license.get.queryOptions().queryKey+ queryClient.setQueryData<GetSystemFeaturesLicenseResponse>(queryKey, data)return data}@@ -161,7 +134,7 @@ export const seedAppDslVersion = (queryClient: QueryClient, appDslVersion = '0.6export type ConsoleQueryTestOptions = {/*** Partial overrides for the systemFeatures payload. When omitted, the cache- * is seeded with `defaultSystemFeatures` so consumers using+ * is seeded with a valid Community response so consumers using* `useSuspenseQuery` resolve immediately. Pass `null` to skip seeding and* keep the systemFeatures query in the pending state.*/diff --git a/web/test/console/state-fixture.ts b/web/test/console/state-fixture.tsindex d82cbbc6a4a..9de2d5fec37 100644--- a/web/test/console/state-fixture.ts+++ b/web/test/console/state-fixture.ts@@ -2,7 +2,7 @@ import type { createStore } from 'jotai'import type { LangGeniusVersionInfo } from '@/context/app-context-types'import type { ICurrentWorkspace } from '@/models/common'import { atom } from 'jotai'-import { defaultSystemFeatures } from '@/features/system-features/config'+import { createSystemFeaturesFixture } from '@/test/console/system-features'export type ConsoleStateFixture = {userProfile?: {@@ -28,6 +28,8 @@ export type ConsoleStateFixture = {workspacePermissionKeys?: string[]datasetRbacEnabled?: booleanknowledgeFsEnabled?: boolean+ deploymentEdition?: 'COMMUNITY' | 'ENTERPRISE' | 'CLOUD'+ brandingEnabled?: booleanlangGeniusVersionInfo?: Partial<LangGeniusVersionInfo>refreshUserProfile?: () => voidrefreshCurrentWorkspace?: () => void@@ -96,8 +98,9 @@ const refreshCurrentWorkspaceAtom = atom(null, (get) =>const workspacePermissionKeysAtom = atom<string[]>([])const workspacePermissionKeysLoadingAtom = atom(false)-const systemFeaturesAtom = atom(defaultSystemFeatures)-const datasetRbacEnabledAtom = atom((get) => get(systemFeaturesAtom).rbac_enabled)+const systemFeaturesAtom = atom(createSystemFeaturesFixture())+const deploymentEditionAtom = atom((get) => get(systemFeaturesAtom).deployment_edition)+const brandingEnabledAtom = atom((get) => get(systemFeaturesAtom).branding.enabled)const langGeniusVersionInfoAtom = atom<LangGeniusVersionInfo>(defaultLangGeniusVersionInfo)const langGeniusCurrentVersionAtom = atom((get) => get(langGeniusVersionInfoAtom).current_version)@@ -133,11 +136,17 @@ export const seedRegisteredConsoleStateFixture = (store: JotaiStore) => {store.set(currentWorkspaceLoadingAtom, state.isLoadingCurrentWorkspace ?? false)store.set(workspacePermissionKeysAtom, state.workspacePermissionKeys ?? [])store.set(workspacePermissionKeysLoadingAtom, state.isLoadingWorkspacePermissionKeys ?? false)- store.set(systemFeaturesAtom, {- ...defaultSystemFeatures,- rbac_enabled: state.datasetRbacEnabled ?? false,- knowledge_fs_enabled: state.knowledgeFsEnabled ?? false,- })+ store.set(+ systemFeaturesAtom,+ createSystemFeaturesFixture({+ rbac_enabled: state.datasetRbacEnabled ?? false,+ knowledge_fs_enabled: state.knowledgeFsEnabled ?? false,+ deployment_edition: state.deploymentEdition ?? 'COMMUNITY',+ branding: {+ enabled: state.brandingEnabled ?? false,+ },+ }),+ )store.set(langGeniusVersionInfoAtom, {...defaultLangGeniusVersionInfo,...state.langGeniusVersionInfo,@@ -208,12 +217,12 @@ export const createPermissionStateModuleMock = (getState: ConsoleStateFixtureResexport const createSystemFeaturesStateModuleMock = (getState: ConsoleStateFixtureResolver) => {registerConsoleStateFixture('systemFeatures', () => ({- datasetRbacEnabled: getState().datasetRbacEnabled,- knowledgeFsEnabled: getState().knowledgeFsEnabled,+ deploymentEdition: getState().deploymentEdition,+ brandingEnabled: getState().brandingEnabled,}))return {- systemFeaturesAtom,- datasetRbacEnabledAtom,+ deploymentEditionAtom,+ brandingEnabledAtom,}}diff --git a/web/test/console/system-features.ts b/web/test/console/system-features.tsnew file mode 100644index 00000000000..761a0213927--- /dev/null+++ b/web/test/console/system-features.ts@@ -0,0 +1,124 @@+import type {+ GetSystemFeaturesLicenseResponse,+ GetSystemFeaturesResponse,+} from '@dify/contracts/api/console/system-features/types.gen'+import { InstallationScope, LicenseStatus } from '@/features/system-features/constants'++export type DeepPartial<T> =+ T extends Array<infer U>+ ? Array<U>+ : T extends object+ ? { [K in keyof T]?: DeepPartial<T[K]> }+ : T++const baseSystemFeatures = {+ deployment_edition: 'COMMUNITY',+ enable_app_deploy: false,+ sso_enforced_for_signin: false,+ sso_enforced_for_signin_protocol: '',+ enable_marketplace: false,+ enable_email_code_login: false,+ enable_email_password_login: true,+ enable_social_oauth_login: false,+ enable_collaboration_mode: true,+ is_allow_create_workspace: false,+ is_allow_register: false,+ is_email_setup: false,+ enable_change_email: true,+ max_plugin_package_size: 15728640,+ license: {+ status: LicenseStatus.NONE,+ },+ branding: {+ enabled: false,+ login_page_logo: '',+ workspace_logo: '',+ favicon: '',+ application_title: '',+ },+ webapp_auth: {+ enabled: false,+ allow_sso: false,+ sso_config: {+ protocol: '',+ },+ allow_email_code_login: false,+ allow_email_password_login: false,+ allow_public_access: true,+ },+ plugin_installation_permission: {+ plugin_installation_scope: InstallationScope.ALL,+ restrict_to_marketplace_only: false,+ },+ plugin_manager: {+ enabled: false,+ },+ rbac_enabled: false,+ enable_creators_platform: false,+ enable_trial_app: false,+ enable_explore_banner: false,+ enable_learn_app: true,+ enable_step_by_step_tour: false,+ knowledge_fs_enabled: false,+} satisfies GetSystemFeaturesResponse++const baseSystemFeaturesLicense = {+ status: LicenseStatus.NONE,+ expired_at: '',+ workspaces: {+ enabled: false,+ size: 0,+ limit: 0,+ },+ seats: {+ enabled: false,+ size: 0,+ limit: 0,+ },+} satisfies GetSystemFeaturesLicenseResponse++export const createSystemFeaturesFixture = (+ overrides: DeepPartial<GetSystemFeaturesResponse> = {},+): GetSystemFeaturesResponse => ({+ ...baseSystemFeatures,+ ...overrides,+ branding: {+ ...baseSystemFeatures.branding,+ ...overrides.branding,+ },+ webapp_auth: {+ ...baseSystemFeatures.webapp_auth,+ ...overrides.webapp_auth,+ sso_config: {+ ...baseSystemFeatures.webapp_auth.sso_config,+ ...overrides.webapp_auth?.sso_config,+ },+ },+ plugin_installation_permission: {+ ...baseSystemFeatures.plugin_installation_permission,+ ...overrides.plugin_installation_permission,+ },+ license: {+ ...baseSystemFeatures.license,+ ...overrides.license,+ },+ plugin_manager: {+ ...baseSystemFeatures.plugin_manager,+ ...overrides.plugin_manager,+ },+})++export const createSystemFeaturesLicenseFixture = (+ overrides: DeepPartial<GetSystemFeaturesLicenseResponse> = {},+): GetSystemFeaturesLicenseResponse => ({+ ...baseSystemFeaturesLicense,+ ...overrides,+ workspaces: {+ ...baseSystemFeaturesLicense.workspaces,+ ...overrides.workspaces,+ },+ seats: {+ ...baseSystemFeaturesLicense.seats,+ ...overrides.seats,+ },+})